feat: add account-free settings and server management panels

This commit is contained in:
omar committed 2026-11-01 22:14:32 +03:00
1 parent 672540499c
commit cf42de67e2
179 files changed
+18817 -810

No files matched your search

+6 -1
View File
@@ -33,7 +33,7 @@ jobs:
- name: Rust toolchain - name: Rust toolchain
run: | run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: glibc baseline - name: glibc baseline
@@ -42,6 +42,11 @@ jobs:
- name: Node dependencies - name: Node dependencies
run: npm ci run: npm ci
- name: Portable microphone DSP
run: |
node scripts/build-denoise.mjs
cargo test --manifest-path dsp/Cargo.toml --locked
- name: Unit tests (desktop) - name: Unit tests (desktop)
run: npm test run: npm test
+4 -2
View File
@@ -41,13 +41,15 @@ jobs:
- name: Rust toolchain - name: Rust toolchain
run: | run: |
set -euo pipefail set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Tests - name: Tests
run: | run: |
set -euo pipefail set -euo pipefail
npm ci npm ci
node scripts/build-denoise.mjs
cargo test --manifest-path dsp/Cargo.toml --locked
npm test npm test
cargo test --manifest-path core/Cargo.toml --locked cargo test --manifest-path core/Cargo.toml --locked
@@ -122,7 +124,7 @@ jobs:
- name: Rust toolchain - name: Rust toolchain
run: | run: |
set -euo pipefail set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Core cross build and checks - name: Core cross build and checks
+33
View File
@@ -2,6 +2,39 @@
## Unreleased ## Unreleased
- Added nested bookmark folders with inline creation, rename, ordering, move/duplicate menus and
confirmed subtree deletion, using validated local preferences rather than a separate bookmark store.
- Added Privacy with trusted-site management and remembered confirmations; reset and concurrent
confirmation changes are serialized so an older save cannot overwrite a later reset.
- Added a loopback Remote Apps WebSocket service with explicit per-application approval, origin-bound
keys, request expiry and connection quotas. Keys never enter renderer status data; revocation and
disconnect release held buttons. Official native event-schema interoperability remains unverified.
- Added account-free local UID contacts and public badge artwork display. These are not myTeamSpeak
contacts, owned-badge management, cloud presence or offline messaging.
- Added server icon management bound to the listing's connection generation. Reconnecting invalidates
mutation grants; old icon/snapshot transfers cannot cancel a new session's reused transfer ID.
- Added the four-level noise-reduction control with persisted per-input settings. Processing remains
an independent implementation, not a claim of identity with TeamSpeak's private native DSP.
- Fixed key recording in the contents-layout settings host by checking the enclosing panel's visibility.
Packaged verification covers saving the binding and retaining it across an application restart.
- Isolated Mermaid rendering from the privileged application renderer; nested renderers cannot acquire
media/presentation permissions. Local diagram/math rendering and hostile-content rejection were exercised.
- Corrected smoke polling to await asynchronous IPC/import predicates instead of accepting a Promise
as a satisfied condition. Persistence checks now wait for actual saved state.
- Fixed full Changelog and Open Source Licenses pages rendering arrays as text instead of appending
their DOM nodes. Added a real offscreen navigation smoke covering document text and back-focus restoration.
- Whispers follow the original manager: Live Preview highlights the current list's clients and channels in
the server tree (resolved from the current snapshot only), "Switch to Server and Overlay" shows the list
next to the microphone's server, and the status bar Whisper History lists received whispers with Delete.
Replies and avatars use only entries whose client id and UID are still on the same server session.
- Key Bindings follow the original page: "Require exact key match" toggle, named profiles (inline
"New Profile Name" editor, rename, choose, Activate, delete of inactive profiles) and every official
hotkey action, each running the app's real operation. Push-to-mute stops sending without touching your
mute choice; global push-to-talk survives window focus loss while local keys still release on it. Go Live
opens the broadcast source chooser instead of guessing the focused application. Bindings can be in-window,
global or an approved Remote App button; with exact matching off, global keys also register their
extra-modifier combinations. keybinds.json moves to version 2; version 1 whisper bindings migrate unchanged
into one active profile and the original file is kept as `keybinds.v1-<time>.json`.
- Reworked the interface against the actual installed TeamSpeak frontend rather than the earlier - Reworked the interface against the actual installed TeamSpeak frontend rather than the earlier
hand-reconstructed component sheet: original non-brand SVG artwork, Noto Sans 2.013, channel and hand-reconstructed component sheet: original non-brand SVG artwork, Noto Sans 2.013, channel and
client chat layouts, membership event rows, sidebar actions, in-pane administration, settings client chat layouts, membership event rows, sidebar actions, in-pane administration, settings
+6 -2
View File
@@ -211,7 +211,7 @@ notifications opaque; forced colours use system tokens.
local server connections/bookmarks only. Connecting and identity selection use a detail-pane form. local server connections/bookmarks only. Connecting and identity selection use a detail-pane form.
The account-bound community action slot instead exposes the real New Connection action. Bookmark The account-bound community action slot instead exposes the real New Connection action. Bookmark
search/add/disclosure remain working; no decorative, nonfunctional folder action is introduced. search/add/disclosure remain working; no decorative, nonfunctional folder action is introduced.
- No notification bell, contacts, myTeamSpeak presence or "Setup Chat" footer state: TeamsPeach is - No notification bell, cloud contacts, myTeamSpeak presence or "Setup Chat" footer state: TeamsPeach is
strictly account-free. Offline onboarding includes a real persisted System/Dark/Light choice before strictly account-free. Offline onboarding includes a real persisted System/Dark/Light choice before
local identity creation/restoration, adapting the official `first_launch.theme` stage (render@2995390) local identity creation/restoration, adapting the official `first_launch.theme` stage (render@2995390)
without its account stages. Existing profiles keep their theme and do not repeat onboarding. The footer without its account stages. Existing profiles keep their theme and do not repeat onboarding. The footer
@@ -227,6 +227,10 @@ notifications opaque; forced colours use system tokens.
- A "System" theme tile exists beside the official Dark and Light tiles. - A "System" theme tile exists beside the official Dark and Light tiles.
- New server administration, identity, snapshot, whisper, recording and file surfaces use the source - New server administration, identity, snapshot, whisper, recording and file surfaces use the source
control tokens around real APIs. Token conformity alone does not establish identical screen composition. control tokens around real APIs. Token conformity alone does not establish identical screen composition.
- Local UID contacts, public badge display, bookmark folders, Privacy, loopback Remote Apps and the
whisper manager bind real local/server operations. They do not emulate a myTeamSpeak account.
The whisper overlay shares the settings controls and list reset; its tree preview derives only from
current-session snapshots, and received-whisper history distinguishes departed identities.
- The refreshed actual-frontend matrix remains a strict visual failure: 168 evaluated pairs, none - The refreshed actual-frontend matrix remains a strict visual failure: 168 evaluated pairs, none
blocked and none fully passing. A later focused 32-pair confirmation also failed; it measures a blocked and none fully passing. A later focused 32-pair confirmation also failed; it measures a
newer build and is not substituted for the full matrix. Native/account/branding exceptions remain newer build and is not substituted for the full matrix. Native/account/branding exceptions remain
@@ -239,5 +243,5 @@ notifications opaque; forced colours use system tokens.
- **Do** keep the native caption overlay colours equal to `--ts-new-header-bg` and `--tsv-font-color`. - **Do** keep the native caption overlay colours equal to `--ts-new-header-bg` and `--tsv-font-color`.
- **Do** keep the stock `--tsv-*` token declarations at (0,1,0) specificity. - **Do** keep the stock `--tsv-*` token declarations at (0,1,0) specificity.
- **Don't** reinterpret, restyle or "improve" the official look; deviations above are product constraints. - **Don't** reinterpret, restyle or "improve" the official look; deviations above are product constraints.
- **Don't** add account-bound controls (bell, contacts, presence) that would do nothing. - **Don't** add account-bound controls (bell, cloud contacts, presence) that would do nothing.
- **Don't** claim full feature parity from visual parity; see `FEATURE_COMPATIBILITY.md`. - **Don't** claim full feature parity from visual parity; see `FEATURE_COMPATIBILITY.md`.
+26 -1
View File
@@ -1,5 +1,30 @@
# TeamsPeach ↔ TeamSpeak 6 server features # TeamsPeach ↔ TeamSpeak 6 server features
## Expanded local panels checkpoint (2026-11-01)
This supersedes the earlier exclusion of Remote Apps and the absence of local contacts below.
The earlier tables remain historical evidence, not a declaration that all current screens match TS6.
Runtime artifacts are under `C:/Users/Admin/tmp/teamspeach-exact-design-20261101/`;
the exact build hashes and limits are in `docs/evidence/official-parity/qa-parity-harness.md`.
| Surface | Current exercised result | Boundary |
|---|---|---|
| Bookmark folders | Actual create, nested bookmark, rename, warning and subtree deletion through prefs IPC | Does not establish the original's saved password/default-channel/startup options |
| Privacy and Markdown Help | Actual trusted-host subpage and production Markdown examples opened; concurrent confirmation/reset regression passed | No cloud typing/presence or telemetry service |
| Key bindings | Actual profile/binding persistence and process restart passed after the contents-layout visibility fix | Native global shortcut registration was not exercised |
| Four-level noise reduction | All levels persisted via the native range control for the selected input device | Independent processing; no physical microphone or native-DSP identity proof |
| Remote Apps | Actual loopback WebSocket approval, key confinement and held-button release on revoke passed | Official undocumented native event payload compatibility remains unverified |
| Server icons and snapshot transfer ownership | Main/renderer consumer tests cover session grants, reconnect, partial failure and recycled transfer IDs | No successful live server icon mutation is claimed |
| Local contacts and public badges | Model/prefs/catalog tests and actual contact add/alias/restart passed; offline state is retained honestly | Not cloud contacts, badge ownership/redeeming or global presence |
| Rich chat | Actual history IPC/restart, scope isolation and local KaTeX/Mermaid hydration passed | Synthetic messages, no server traffic; sandbox permissions tested separately |
| Identity related bookmarks | Actual nested/default assignment display and nickname-clearing restart passed without changing UID | The original identity component exposes ordinary nickname, not a separate editable phonetic field |
| Whisper manager and history | Actual hidden UI with synthetic events passed overlay switching, preview, session/recycled-ID cleanup and received-history handling | No live whisper delivery proof; two microphone attempts were refused by the test stub |
| Changelog and licenses | Actual packaged list/detail navigation and focus restoration passed after fixing stringified DOM arrays | Displays this installation's documents, not TeamSpeak service terms |
Strict whole-screen visual parity remains open. The historical pair failures below are not converted
to passes by adding functionality or changing the test wait implementation.
## Historical interoperability baseline ## Historical interoperability baseline
The table below records earlier exercised builds, not automatic proof of the current cutover. **Proven** The table below records earlier exercised builds, not automatic proof of the current cutover. **Proven**
@@ -52,7 +77,7 @@ unless stated. No new live-server mutation or physical media capture is part of
| General file browser / file transfer | Implemented in current cutover, not part of this historical baseline | Legacy TCP transfer and app-wide settings; current native and main/renderer tests below | | General file browser / file transfer | Implemented in current cutover, not part of this historical baseline | Legacy TCP transfer and app-wide settings; current native and main/renderer tests below |
| Other features | No blanket parity claim | The current full feature matrix identifies owners, observed tests and exact remaining prerequisites | | Other features | No blanket parity claim | The current full feature matrix identifies owners, observed tests and exact remaining prerequisites |
## Current account-free acceptance (2026-11-01) ## Earlier account-free acceptance checkpoint (2026-11-01)
Scope is strictly local/server functionality without an account; myTeamSpeak/cloud/Matrix services and Scope is strictly local/server functionality without an account; myTeamSpeak/cloud/Matrix services and
Remote Apps integration are excluded by instruction. No account UI is substituted for a missing local Remote Apps integration are excluded by instruction. No account UI is substituted for a missing local
+8
View File
@@ -14,5 +14,13 @@
- Interface icons are artwork of the official TeamSpeak 6 client (TeamSpeak Systems GmbH), included at the owner's - Interface icons are artwork of the official TeamSpeak 6 client (TeamSpeak Systems GmbH), included at the owner's
direction without an identified redistribution licence; TeamsPeach does not relicense them. Source, hashes and direction without an identified redistribution licence; TeamsPeach does not relicense them. Source, hashes and
transformations are recorded in `teamspeak-client-icons-PROVENANCE.md` in this folder. transformations are recorded in `teamspeak-client-icons-PROVENANCE.md` in this folder.
- The portable microphone noise suppressor uses the WebRTC-derived Sonora implementation, BSD-3-Clause.
See `sonora-NOTICE.txt` for source/version provenance and `denoise-THIRD-PARTY-NOTICES.txt` for the pinned
dependency and Rust standard-library license texts. The same packaged WebAssembly module runs on all targets.
- The local Remote Apps WebSocket transport uses `ws` (MIT); its original license ships with the npm package
and is available through About → Open Source Licenses. Remote-app authorization keys remain local.
- Notification WAV files are copied from the installed official TeamSpeak client at the owner's direction.
No redistribution licence has been identified; source hashes and event mapping are recorded in
`teamspeak-client-sounds-PROVENANCE.md`. They are not relicensed by TeamsPeach.
- TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not - TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not
affiliated with or endorsed by TeamSpeak Systems GmbH. affiliated with or endorsed by TeamSpeak Systems GmbH.
File diff suppressed because it is too large. Load diff
+61
View File
@@ -0,0 +1,61 @@
TeamsPeach noise reduction (app/renderer/assets/audio/denoise.wasm)
===================================================================
The microphone noise reduction module is built from TeamsPeach's dsp/ crate
(scripts/build-denoise.mjs, target wasm32-unknown-unknown) and contains code from
the following crates, compiled in unmodified:
sonora 0.2.0 BSD-3-Clause (three-band 48 kHz filter bank)
sonora-ns 0.2.0 BSD-3-Clause (WebRTC noise suppressor)
sonora-fft 0.2.0 BSD-3-Clause (FFT used by the noise suppressor)
Source: https://github.com/dignifiedquire/sonora
Commit: a024d6ef8351add55be5e8b1d6cc35f555787660 (per the published crates'
.cargo_vcs_info.json)
Registry: crates.io; package checksums (SHA-256 of the .crate files)
sonora 0.2.0 2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250
sonora-ns 0.2.0 d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f
sonora-fft 0.2.0 27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012
sonora is a pure Rust port of the WebRTC Native Code audio processing module
(M145 plus later upstream fixes), via PulseAudio's webrtc-audio-processing
extraction. Only the filter bank and noise suppressor run; sonora's echo
canceller and gain controller are never constructed. TeamsPeach does not claim
bit-identical behaviour with TeamSpeak's own noise reduction.
The module also contains parts of the Rust standard library (core, alloc, std
and its bundled allocator and math routines), licensed MIT OR Apache-2.0.
License of sonora, sonora-ns and sonora-fft (BSD-3-Clause, verbatim):
Copyright (c) 2011, The WebRTC Project Authors. All rights reserved.
Copyright (c) 2016, Arun Raghavan and contributors. All rights reserved.
Copyright (c) 2026, dignifiedquire. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+14 -1
View File
@@ -336,7 +336,20 @@ Aggregate SHA-256: `eebd6910a9077dacaf199ff25fbdc12cf3d50ea35a0b27123e556ca8856c
Input: filename-sorted records `filename + NUL + lowercase_file_sha256 + LF`, UTF-8 encoded. Input: filename-sorted records `filename + NUL + lowercase_file_sha256 + LF`, UTF-8 encoded.
The provenance and redistribution caveats above apply; these copies receive no new licence grant. The provenance and redistribution caveats above apply; these copies receive no new licence grant.
## Expanded bookmark and whisper controls
Additional symbols use the same transformations and redistribution caveats above. Source files are
under the installed client's `images/icons/`; hashes were read on 2026-11-01.
| Product symbol | Source file | SHA-256 |
|---|---|---|
| `i-folder-action` | `folder_action.svg` | `59df74a51ea024d214611b25568dfa53420f706b886ebdf9302e8c0011979d94` |
| `i-connection-whispers` | `connection_whispers.svg` | `50de820d13d6a4f08966448d81b94d59188a2f15fe9de9d730e43e83b34e65ad` |
| `i-chat-contact` | `chat_contact.svg` | `d11e41302a634d8e4f48a38ee8443e095c4c09b8d1fb87d4a4b95190c8d370a3` |
`i-chat-contact` represents a locally received whisper participant, not an account service.
## Not included ## Not included
TeamSpeak logo/label/mono marks, `ts_logo_qr.png`, `brands-*`, room presets and banners, content backgrounds, hex decorations, TeamSpeak logo/label/mono marks, `ts_logo_qr.png`, `brands-*`, room presets and banners, content backgrounds, hex decorations,
contact-status, chat-contact, chat-room, homebase, two-factor and phone-call (myTeamSpeak account) artwork, and the other unused `*_old` files. contact-status, chat-room, homebase, two-factor and phone-call (myTeamSpeak account) artwork, and the other unused `*_old` files.
@@ -0,0 +1,96 @@
# Official TeamSpeak 6 client notification sounds in TeamsPeach — provenance
The 54 files in `app/renderer/assets/sounds/` are notification sounds of the official TeamSpeak 6 client
(TeamSpeak Systems GmbH), copied byte for byte from the client installed on the owner's workstation at the owner's
direction (2026-11-01 brief: the installed client's features and panels, value for value).
**Licence status.** No licence grant for redistributing these sounds has been identified. The installed client is
governed by its own licence agreement (`licenses/en/la_desktop.html` in the client installation). TeamsPeach does not
relicense these sounds and does not claim the right to publish them; they are not covered by TeamsPeach's own terms or
by any open-source licence in this folder.
## Source
- Installation: `%LOCALAPPDATA%/Programs/TeamSpeak/html/client_ui/sound/default/` (the only sound pack the client
ships; 61 files). `main.js` sha256 `9d6bea2ee5333086555c36584621c1b3462a83042ce746d3229d6766a9b82c39`.
- Event → file table: `NotificationSoundManager.soundFiles`, `main.js` webpack module 82164 (first file name at
character offset ≈2267292). Event types and sub types: module 69818 enums `J1` (event type), `l2`, `nA`, `x8`, `rJ`,
`eM`, `T9`, `rt`, `nZ`, `jk`, `KY`, `yc`, `ih` and `r.I3d` (stream). Playback: `playSoundForDefaultEvent` passes the
file name to native `tsclient_internal.playWaveFile(0, name)` (`main.js` ≈2120604). That the native side resolves
the name to `html/client_ui/sound/default/<name>.wav` is inferred from the adjacent `sound`, `client_ui`, `html` and
`.wav` strings in `TeamSpeak.dll` and from `default` being the only installed pack; the native code was not traced.
- Settings rows: coalesced setting table module 69818 `rg`; the row's Listen button (`playPreview`, module 186,
`main.js` ≈4964155) plays the first sub type of the row, an advanced row plays its own sub type, both ignoring the
throttle.
## Transformations
None. Each file is an unchanged copy (RIFF/WAVE PCM, including its original `LIST`/`CDif`/`cue `/`bext` chunks); the
renderer decodes it with Chromium's own decoder at playback time.
## Files
`time` is the official repeat throttle; a repeat within it is skipped.
| File | Official event sub types (`EventType.SubType`) | Format | Bytes | sha256 |
|---|---|---|---|---|
| `away_activated.wav` | ClientUpdate.YouAway (100 ms) | 1×16-bit 44100 Hz, 0.759 s | 67190 | `170fdd2f8fd07ce0b7077a45e9df6cdac8ddf9a8cdaf2e6bc5828944564d5acf` |
| `away_deactivated.wav` | ClientUpdate.YouPresent (100 ms) | 1×16-bit 44100 Hz, 0.758 s | 67034 | `6c00635fad802ebe62543e85fd402f8fcb5957b8d68c4e80a74d721fcab6306f` |
| `channel_created.wav` | ChannelEvent.YouCreated | 1×16-bit 44100 Hz, 1.065 s | 94194 | `9354320217fb8600c9b88a9ec34b19e1f5e242a13570d94ad0ec5811850f7ae2` |
| `channel_deleted.wav` | ChannelEvent.YouDeleted | 1×16-bit 44100 Hz, 1.028 s | 90882 | `25d80e7f1274caa9322bf5f1cd1846e5f4a2be1e978b5edbaf81693ccaf4c5dc` |
| `channel_edited.wav` | ChannelEvent.YouEdited | 1×16-bit 44100 Hz, 1.005 s | 88898 | `33605c5a802efa895ee043bbcc7cd43081c264a9602589355ced95a321c6c562` |
| `channel_moved.wav` | ChannelEvent.YouMoved | 1×16-bit 44100 Hz, 0.918 s | 81144 | `144bfc4a22c578872a998d518833c7b0cc1d60be0d81319506da5d84e3278ffd` |
| `channel_switched.wav` | ClientMove.YouSwitchedChannel | 1×16-bit 44100 Hz, 0.995 s | 87998 | `f38c9e67bbd861319d4eef15454893419285ba6dcdd05566dcb3b2042899f468` |
| `channelgroup_changed.wav` | ClientUpdate.YouChannelGroupChanged (1000 ms) | 1×16-bit 44100 Hz, 1.298 s | 114698 | `4ac60b4c0b4bb7a5784d6ae55412fdc198d89ac8a52c7cf3116cf6620f2a024e` |
| `chat_message_inbound.wav` | TextMessage.FromAnotherClient, TextMessage.FromChannel, TextMessage.FromServer | 1×16-bit 44100 Hz, 1.000 s | 88244 | `51e29bb0284b1c62447a720684dd9628034d0bd5b0c1fab2b1dde5986f457a3c` |
| `chat_message_outbound.wav` | TextMessage.ToAnotherClient | 1×16-bit 44100 Hz, 0.047 s | 4148 | `7fc8296f113485aa7d66b3f1e1e04ea3c7470d9efb238fb692a9504cf8c33ce2` |
| `connected.wav` | ConnectStatus.Connected | 1×16-bit 44100 Hz, 0.624 s | 55262 | `e9bc4136b91bc7d36dc9a561b2b8d4436244f42af65c1d01540f0b8a958c5a10` |
| `connection_lost.wav` | ConnectStatus.ConnectionLost | 1×16-bit 44100 Hz, 0.988 s | 87394 | `5566aa08c4e0f126a586ff50ed41ccbad3c5f942e75c9f924ad6578e8ccf6d45` |
| `disconnected.wav` | ConnectStatus.Disconnected | 1×16-bit 44100 Hz, 0.950 s | 84018 | `58ad23d848d07c37e0b521dadeecedbc268beaad657d4e12d03daf7b9ab16e53` |
| `error.wav` | ConnectStatus.FailedToConnect (1000 ms), LogEvent.LogError (1000 ms) | 1×16-bit 44100 Hz, 0.472 s | 41870 | `3b0589a6349d96198f496861b2be12c825a922b1b59b56d202195208014035e0` |
| `insufficient_permissions.wav` | ServerPermissionErrorEvent.Error (2000 ms) | 1×16-bit 44100 Hz, 1.370 s | 121066 | `4284bf1e85c53cb450b7ae9d488df417a372e0c23ad91bf24fcd2992b28cec1c` |
| `mic_activated.wav` | ClientUpdate.YouCaptureUnmuted (100 ms) | 1×16-bit 44100 Hz, 1.210 s | 106982 | `c44490c0f9ce270d0ee90c5f5fc4004ea39ebbdc8b6ebc5dab75cf175f9f6f83` |
| `mic_muted.wav` | ClientUpdate.YouCaptureMuted (100 ms) | 1×16-bit 44100 Hz, 1.017 s | 89936 | `528ea98a11951d8fa96a5396c12c9e3bceabf0a895e084826f3b1cfca0d4ed8e` |
| `neutral_banned_server_currentchannel.wav` | ClientMove.SomeoneInYourChannelWasBanned | 1×16-bit 44100 Hz, 2.478 s | 218768 | `599e671f50842cee1603a56f7e211686b985abd92a977b5f3c5532393213b67c` |
| `neutral_connection_connected_currentchannel.wav` | ClientMove.SomeoneInYourChannelConnected | 1×16-bit 44100 Hz, 1.446 s | 127760 | `6a4ad2636c93e88cd6247a3105a65d88af8ca3fff05f9debb09726df6074b9e0` |
| `neutral_connection_connectionlost_currentchannel.wav` | ClientMove.SomeoneInYourChannelConnectionLost | 1×16-bit 44100 Hz, 1.829 s | 161498 | `7c39ad53fd3d041fa711c97e6559c5af3ebf7b3b3285f9ae0edb4a42a92a5568` |
| `neutral_connection_disconnected_currentchannel.wav` | ClientMove.SomeoneInYourChannelDisconnected | 1×16-bit 44100 Hz, 1.900 s | 167834 | `cdbb181918c33842ae3572ad3752aabff8b47559e881862fe64ee6e40bddd6f8` |
| `neutral_kicked_channel_awayfromcurrentchannel.wav` | ClientMove.SomeoneInYourChannelWasKickedChannel | 1×16-bit 44100 Hz, 2.020 s | 178416 | `eafadd9b5f7cef69c106803bb0bac94d39880158330a3820995c4a1a897538e4` |
| `neutral_kicked_channel_tocurrentchannel.wav` | ClientMove.SomeoneWasKickedToYourChannel | 1×16-bit 44100 Hz, 1.856 s | 163914 | `29e2bf7ceaadb1d124a9f0ac8c4e1fe8c26697e3072f3d0b8936c4766416ff25` |
| `neutral_kicked_server_currentchannel.wav` | ClientMove.SomeoneInYourChannelWasKickedFromServer | 1×16-bit 44100 Hz, 2.534 s | 223686 | `2d53d3c8a338418e23c8803a8abb8b73349df5befc0af0096ae7a3bb0a376872` |
| `neutral_moved_awayfromcurrentchannel.wav` | ClientMove.SomeoneWasMovedAwayFromYourChannel (100 ms) | 1×16-bit 44100 Hz, 1.764 s | 155802 | `e2b1e2a4336a8af7e8cfcdd239f26138c3a11b045cd952d81aaa671ebd6c6c85` |
| `neutral_moved_tocurrentchannel.wav` | ClientMove.SomeoneWasMovedToYourChannel (100 ms) | 1×16-bit 44100 Hz, 1.741 s | 153818 | `569fd8904a2d6a70529ea36466cc590179ec7c4e40b6b5d40f2643fb0a25ed68` |
| `neutral_recording_active_currentchannel.wav` | ClientMove.YouSwitchedChannelRecording | 1×16-bit 44100 Hz, 1.815 s | 160290 | `7448f91c3ecd901500a954a42276a3459bbc93daa66e1080b3aead80f24cf92d` |
| `neutral_recording_started_currentchannel.wav` | ClientUpdate.SomeoneInYourChannelRecordingStarted | 1×16-bit 44100 Hz, 2.106 s | 185978 | `af5a29f7974591b010044d6a212f4238c4446f66ab27b2429e08b1c07c6a8670` |
| `neutral_recording_stopped_currentchannel.wav` | ClientUpdate.SomeoneInYourChannelRecordingStopped | 1×16-bit 44100 Hz, 2.096 s | 185126 | `3f0ab4f666518055fc05d8b5102bdddcde7b042aee6cd2527529b0753edf4557` |
| `neutral_switched_awayfromcurrentchannel.wav` | ClientMove.SomeoneLeftYourChannel (1000 ms) | 1×16-bit 44100 Hz, 1.326 s | 117182 | `d0c0fb1153a6b28f038c83ccc91bfecb218a0202171f3b2d14266fd290c5d622` |
| `neutral_switched_tocurrentchannel.wav` | ClientMove.SomeoneJoinedYourChannel (1000 ms) | 1×16-bit 44100 Hz, 1.343 s | 118682 | `d334e0e463472dfe389b1bfb2e24d254f99e00744d4f634c6eac76c0bcd6a19b` |
| `no_whisper_target_found.wav` | WhisperErrorEvent.NoSelection | 1×16-bit 44100 Hz, 1.514 s | 133786 | `6c6d1054a9b218f2ae1600c1567eeff9052802254ed1ed888c17a73a7095e5e0` |
| `recording_paused.wav` | LocalRecordingEvent.RecordingPaused (300 ms) | 2×16-bit 48000 Hz, 1.155 s | 221728 | `fee07ad4647998381f1c176c19c51ff88bff9be76c9bb999384cadec181d55ca` |
| `recording_resumed.wav` | LocalRecordingEvent.RecordingResumed (300 ms) | 2×16-bit 48000 Hz, 1.152 s | 221280 | `bbecb5fb7a9f1cf3f60cdb0ab690f8043dcf3fa7fbae69d8b4b93ebc99939d64` |
| `recording_started.wav` | LocalRecordingEvent.RecordingStarted (500 ms) | 2×16-bit 48000 Hz, 1.230 s | 236272 | `1fd58b214c851cd88b53fd61a38d71bc98d8cd407bb4270951360d4dc4e89b23` |
| `recording_stopped.wav` | LocalRecordingEvent.RecordingStopped (500 ms) | 2×16-bit 48000 Hz, 1.263 s | 242484 | `b9261ceccf4828680256b7edfbdd131781d815c30aef019dc624f4d55219967d` |
| `servergroup_assigned.wav` | ClientUpdate.YouServerGroupAssigned (1000 ms) | 1×16-bit 44100 Hz, 1.327 s | 117248 | `8f278ac08f259131eebc6a78ed700a76e036e627cb8a3ef78036f3f570c4501f` |
| `servergroup_revoked.wav` | ClientUpdate.YouServerGroupRevoked (1000 ms) | 1×16-bit 44100 Hz, 1.476 s | 130438 | `8befbc4a4025ed28de7d397ccb718c59417ea553065c50173693678b0e5d4211` |
| `sound_muted.wav` | ClientUpdate.YouPlaybackMuted (100 ms) | 1×16-bit 44100 Hz, 1.011 s | 89424 | `41cf6d43b7115e7e212f4cc75146291f0d847f079268b385fcd053090cd1e36c` |
| `sound_resumed.wav` | ClientUpdate.YouPlaybackUnmuted (100 ms) | 1×16-bit 44100 Hz, 1.018 s | 89978 | `28b0bfabfe904d54779979e652ae99122d1689aa64820e01a82db7d3c2f67cd8` |
| `stop_talking.wav` | TalkStatusChanged.YouTalkingWhileMuted, WhisperErrorEvent.NoInput (2000 ms) | 1×16-bit 48000 Hz, 0.467 s | 45742 | `c734b077fe252640535b7ba4ca607aadbf0884a8734c68cf17522b7f2f3a64bc` |
| `stream_started.wav` | StreamEvent.StreamStarted (100 ms) | 2×16-bit 48000 Hz, 1.300 s | 249812 | `55b922d7d457e0e9c6e86cbbb4bf7aa5edf310934ec673a39bd2f8e45629bf32` |
| `stream_stopped.wav` | StreamEvent.StreamStopped (100 ms) | 2×16-bit 48000 Hz, 1.233 s | 236924 | `8f8138de2d91ccdb0a2a1af112ea9acff58e845f30e79913697e025bf9b5cdba` |
| `talkpower_granted.wav` | ClientUpdate.YouTalkPowerGranted | 1×16-bit 44100 Hz, 1.267 s | 111962 | `3ef9564294f6673e3dbc945ee8b49bc381e674a31c93ab4c0363fa45b5eeadea` |
| `talkpower_requested.wav` | ClientUpdate.SomeoneRequestsTalkPower | 1×16-bit 44100 Hz, 1.720 s | 151946 | `57c1eac582806288b0e055110d265271bb597fd4556ccba01a59f87dd9ca48fc` |
| `talkpower_revoked.wav` | ClientUpdate.YouTalkPowerRevoked | 1×16-bit 44100 Hz, 1.503 s | 132770 | `02af63898cc739ef439afdc5c54420148d030532129f578c84d5e91ccd9e406f` |
| `whisper_received.wav` | WhisperEvent.WhisperReceived (2000 ms) | 1×16-bit 48000 Hz, 0.173 s | 16648 | `6c8e708f35a7025ed096e2c50677f2a2e677ada99d9c3db2546fe22e51d7d83b` |
| `you_edited_server.wav` | ServerEdited.YouEdited | 1×16-bit 44100 Hz, 1.229 s | 108638 | `1dc49aae0f48fd021e27ee642f345756b5c734512d3683bc15328d0f14188d67` |
| `you_kicked_channel.wav` | ClientMove.YouWereKickedFromChannel | 1×16-bit 44100 Hz, 1.431 s | 126418 | `3bf0594419ce06d87df94c8a8f068b882b3ff0b131b76088dfcc24cbbf370e3d` |
| `you_kicked_server.wav` | ClientMove.YouWereKickedFromServer | 1×16-bit 44100 Hz, 1.458 s | 128804 | `6e80de6a0dfcf2ead8163f8988cc664f8b09f046e1fe0337d8d8b4dd40f0afa7` |
| `you_were_banned.wav` | ClientMove.YouWereBanned | 1×16-bit 44100 Hz, 1.501 s | 132570 | `5e07d8d80230e9f663f0945b79180b363636d7dcc54962b82bf7bb20798ce0f7` |
| `you_were_moved.wav` | ClientMove.YouWereMoved | 1×16-bit 44100 Hz, 0.875 s | 77390 | `009f7b61dd7bfbdd3c6a4c4cda8d3d56af23c378d5e43654b69d421fc1b528e8` |
| `you_were_poked.wav` | TextMessage.PokedFromAnotherClient | 1×16-bit 44100 Hz, 0.936 s | 82766 | `ecb415cf29eccebb9d72ac745f7e5ac919cb0d1bcb62dc9c690fc1c0ed560385` |
| `your_channel_was_edited.wav` | ChannelEvent.YourChannelEdited | 1×16-bit 44100 Hz, 1.380 s | 121976 | `02363f9f2285747b78c271edb15dde0f99dffc0d08f07d0220b166dc940f8583` |
## Not included
`call_incoming.wav`, `call_outgoing.wav` (CallEvent, myTeamSpeak calls), `chat_inbound.wav` (MatrixMessageEvent
IncomingFollowupMessage, myTeamSpeak chat), and `chat_outbound.wav`, `client_joined.wav`, `client_left.wav`,
`incoming_call.wav`, which no official event table references. TeamsPeach has no local source for these events.
+2 -1
View File
@@ -62,7 +62,8 @@ the three-slot window (sidebar, server tree, detail pane), menus, settings and c
the installed client's own source values, with extraction offsets in `docs/evidence/official-parity/`. the installed client's own source values, with extraction offsets in `docs/evidence/official-parity/`.
The TeamSpeak application logo and name are not shipped. Non-brand SVG artwork is copied from the The TeamSpeak application logo and name are not shipped. Non-brand SVG artwork is copied from the
installed client for the owner's requested local reproduction; no redistribution licence is claimed. installed client for the owner's requested local reproduction; no redistribution licence is claimed.
Account-bound surfaces (notification bell, contacts, myTeamSpeak presence, Setup Chat) remain omitted. Account-bound surfaces (notification bell, cloud contacts, myTeamSpeak presence, Setup Chat) remain omitted.
Local UID contacts use connected-server presence only and are not a substitute for cloud synchronization.
Remaining visual and functional deviations are listed in DESIGN.md and FEATURE_COMPATIBILITY.md; visual Remaining visual and functional deviations are listed in DESIGN.md and FEATURE_COMPATIBILITY.md; visual
parity is never presented as feature parity. Offline identity onboarding and the independent brand marker parity is never presented as feature parity. Offline identity onboarding and the independent brand marker
are explicit exceptions, not imitations of account functionality. New module controls bind real APIs; are explicit exceptions, not imitations of account functionality. New module controls bind real APIs;
+39 -10
View File
@@ -13,6 +13,8 @@ have not been proven.
``` ```
npm ci npm ci
rustup target add wasm32-unknown-unknown
node scripts/build-denoise.mjs # independent WASM noise reduction
cargo build --release --locked --manifest-path core/Cargo.toml # requires Rust ≥ 1.89, CMake and a C compiler cargo build --release --locked --manifest-path core/Cargo.toml # requires Rust ≥ 1.89, CMake and a C compiler
npm start npm start
``` ```
@@ -63,8 +65,9 @@ attached with a `local` designation and a `*-build-info.txt` provenance file.
2. Enter a server address and, if required, its password, then select Connect. Up to eight simultaneous 2. Enter a server address and, if required, its password, then select Connect. Up to eight simultaneous
native connections are supported. Selecting a server tab changes the viewed server, not automatically native connections are supported. Selecting a server tab changes the viewed server, not automatically
the microphone target; input routing has its own controls and acknowledgement. Bookmarks save a name, the microphone target; input routing has its own controls and acknowledgement. Bookmarks save a name,
address and optional local identity, never a server password. A security-level rejection offers an address, optional local identity and folder, never a server password. The sidebar supports nested
explicit improvement action for that identity rather than starting expensive work automatically. folders, rename, duplicate, moving/reordering and confirmed subtree deletion. A security-level
rejection offers an explicit improvement action rather than starting expensive work automatically.
3. Click a channel (or focus its row and press Enter) to **browse** its heading and available streams. 3. Click a channel (or focus its row and press Enter) to **browse** its heading and available streams.
This does not move your voice or change the channel-chat destination: the chat tab and composer still This does not move your voice or change the channel-chat destination: the chat tab and composer still
name your current voice channel, and a notice explains this while browsing elsewhere. Double-click name your current voice channel, and a notice explains this while browsing elsewhere. Double-click
@@ -76,8 +79,12 @@ attached with a `local` designation and a `*-build-info.txt` provenance file.
use automatic speech detection, a volume gate, or a hybrid; push-to-talk can be combined with activation use automatic speech detection, a volume gate, or a hybrid; push-to-talk can be combined with activation
and an optional release delay. Disabling both gives continuous transmission. Existing profile choices and an optional release delay. Disabling both gives continuous transmission. Existing profile choices
migrate to this model. Notification output has a separate device and dB level. Processing is independent migrate to this model. Notification output has a separate device and dB level. Processing is independent
and is not claimed bit-identical to the official client's private native DSP. Local keyboard bindings and is not claimed bit-identical to the official client's private native DSP. Settings → Key Bindings has
work in-window; global support depends on the OS backend and permissions. named profiles (add/rename/activate/delete; only the active one is live), the official "Require exact key
match" toggle and the full official action list (push-to-talk, push-to-mute, microphone/speaker, away,
whispers, recording, disconnect, talk power, and Go Live, which opens the normal broadcast source chooser).
A binding is an in-window key, a global key (depends on the OS backend and permissions) or an approved
Remote App button. Older whisper-only bindings move unchanged into one active profile.
Local whisper lists/groups, quick whisper and reply use held-target epochs; failed or stale whisper Local whisper lists/groups, quick whisper and reply use held-target epochs; failed or stale whisper
targets suppress sending rather than falling back to ordinary channel voice. Contact-only targets are targets suppress sending rather than falling back to ordinary channel voice. Contact-only targets are
not offered without an account. The microphone test retains at most ten seconds of PCM in memory, not offered without an account. The microphone test retains at most ten seconds of PCM in memory,
@@ -142,7 +149,8 @@ attached with a `local` designation and a `*-build-info.txt` provenance file.
10. Chat history is local and separated by own identity, server and channel/peer identity. Drafts and 10. Chat history is local and separated by own identity, server and channel/peer identity. Drafts and
unread state are connection-local. Rich text, local math/diagrams, emoji and server-file links do not unread state are connection-local. Rich text, local math/diagrams, emoji and server-file links do not
require cloud services. Remote images require explicit consent; trusted external sites can be removed require cloud services. Remote images require explicit consent; trusted external sites can be removed
in settings. Matrix/cloud edits, reactions, read receipts and contacts are outside the account-free scope. in Settings → Privacy. Matrix/cloud edits, reactions, read receipts and cloud contacts are outside
the account-free scope; local UID contacts are separate.
11. Streams support hide/show without unsubscribing, ordering, focus with a secondary strip, pages, 11. Streams support hide/show without unsubscribing, ordering, focus with a secondary strip, pages,
an internal tile overlay and moving the existing stage over the server tree. Publisher admission, an internal tile overlay and moving the existing stage over the server tree. Publisher admission,
kick/ban/unblock, pause and live options keep the original tracks/sessions. Standalone pop-out reuses kick/ban/unblock, pause and live options keep the original tracks/sessions. Standalone pop-out reuses
@@ -150,6 +158,25 @@ attached with a `local` designation and a `*-build-info.txt` provenance file.
Unmodified native pop-out painting and SFU interoperability remain unverified. Unmodified native pop-out painting and SFU interoperability remain unverified.
## Local panels and integrations
- **Privacy:** manage trusted external hosts and reset remembered confirmations. Skipping a confirmation
changes that operation's local preference; reset restores prompts. No analytics service is enabled.
- **Contacts:** save server users locally by identity UID, optionally give them aliases, and show/sort/group
offline entries. Presence comes from the client's connected server snapshots, not a global service.
Public badge display does not redeem badges or claim ownership of them.
- **Remote Apps:** Settings → Extensions → Remote Apps controls the loopback WebSocket listener and
application approvals. A new application must be explicitly allowed. A web application's API key is
bound to the origin approved by the user; renderer status never exposes it. Revoking access, removing
an app or closing its connection releases its held buttons. LAN access is not provided. Compatibility
with the official client's undocumented native event payloads has not been established.
- **Server icons:** the server administration pane lists, uploads, deletes and assigns icons through
legacy TeamSpeak file transfer. The server's permissions remain authoritative. A reconnect invalidates
the panel's mutation grant; HTTPFT/S3 storage is not silently treated as an empty icon collection.
- **Noise reduction:** Settings → Audio has four levels saved per input device. The implementation is
independent DSP; selected settings and generated-media checks do not prove microphone sound quality
or bit-identical behavior with the official client.
## Language ## Language
The interface defaults to English, independently of the operating-system language. Select Russian in The interface defaults to English, independently of the operating-system language. Select Russian in
@@ -190,10 +217,11 @@ Data locations: `%APPDATA%\TeamsPeach` (Windows), `~/.config/TeamsPeach` (Linux)
- P2P screenshare publishing is implemented, but native source capture on every OS/window manager, - P2P screenshare publishing is implemented, but native source capture on every OS/window manager,
macOS selected-application audio and official-client interoperability are not all verified. SFU publishing macOS selected-application audio and official-client interoperability are not all verified. SFU publishing
is unavailable. See the feature matrix for the precise implementation and evidence boundaries. is unavailable. See the feature matrix for the precise implementation and evidence boundaries.
- Push-to-talk only works while the window is focused. A global hold-to-talk shortcut, such as one using - In-window push-to-talk releases on focus loss. Global bindings use the available Windows/Linux
the Wayland GlobalShortcuts portal, is not implemented. backend; actual OS registration and Wayland portal operation were not exercised by the hidden UI
- The official client highlights your own nickname and myTeamSpeak contacts using local relationships, checks. macOS global shortcuts are explicitly unsupported. No platform-wide shortcut guarantee is made.
not server data. Without an account there are no contacts, so TeamsPeach highlights only your own name. - Local contacts are keyed by server identity UID and can be highlighted in the tree. They do not sync
with myTeamSpeak, provide global presence or enable cloud/offline chat.
- Server-stored avatars, icons and banners use TeamSpeak file transfer. myTeamSpeak avatars use public - Server-stored avatars, icons and banners use TeamSpeak file transfer. myTeamSpeak avatars use public
HTTPS URLs announced by the server; downloaded image bytes are checked by signature. A myTeamSpeak HTTPS URLs announced by the server; downloaded image bytes are checked by signature. A myTeamSpeak
avatar was observed in the live run; server-stored avatar support is implemented but was not exercised avatar was observed in the live run; server-stored avatar support is implemented but was not exercised
@@ -220,7 +248,8 @@ and composer. Settings open in the main and detail panes with the official categ
cards (Identity, Servers, Appearance, Audio, Video, Keyboard, Chats, Notifications, OS Specific, cards (Identity, Servers, Appearance, Audio, Video, Keyboard, Chats, Notifications, OS Specific,
Information). Reduced-transparency, reduced-motion and forced-colors preferences have explicit fallbacks. Information). Reduced-transparency, reduced-motion and forced-colors preferences have explicit fallbacks.
New profiles default to dark independently of the OS; Light and System remain selectable. Account-bound New profiles default to dark independently of the OS; Light and System remain selectable. Account-bound
official surfaces (notification bell, contacts, myTeamSpeak presence) are intentionally absent. official surfaces (notification bell, cloud contacts, myTeamSpeak presence) are intentionally absent;
local UID contacts are an independent account-free feature.
Each pane has the official 44 px window bar as its drag surface; the server pane's bar carries the Each pane has the official 44 px window bar as its drag surface; the server pane's bar carries the
microphone/speakers toolbar pill. Startup and error views keep a 44 px drag strip. Electron's hidden microphone/speakers toolbar pill. Startup and error views keep a 44 px drag strip. Electron's hidden
+458
View File
@@ -0,0 +1,458 @@
'use strict';
/**
* Public myTeamSpeak badge catalog for displaying other clients' badges (official tree `ts-badges`, client info
* Badge Showcase). Account-free: this only reads TeamSpeak's public catalog; it never redeems, owns, signs or
* sets badges.
*
* Evidence (installed TS6 6.0.0, read-only):
* - TeamSpeak.dll embeds the catalog URL `https://badges-content.teamspeak.com/list` and the protobuf schema
* `global_badge_list.proto` (package com.teamspeak.myteamspeak.proto.cloud):
* message BadgeList { int32 version = 1; int64 updated = 2; repeated Badge badges = 3; }
* message Badge { string uuid = 1; string name = 2; string url = 3; string description = 4;
* int64 created = 5; int32 version = 6; }
* - The native client caches artwork per badge as `<cache>/badges/96/<uuid>` (small SVG, client_ui `url`) and
* `<uuid>_details` (detailed SVG, client_ui `detailed_url`); on Windows the cache is
* %LOCALAPPDATA%/TeamSpeak/Cache/Default/badges/96. Those files are read here read-only when present.
* - Network artwork for a badge missing from both caches is derived from the catalog entry's own `url` as
* `<url>.svg` / `<url>_details.svg` (TeamSpeak.dll string "_details.svg"). Observed live 2026-11-01: GET /list →
* 200 application/octet-stream, 17245 bytes, a plain BadgeList body (no extra header; version 99, 91 badges);
* badge 0005232e-538e-4cb2-93b6-d7d83e873829 has url `https://badges-content.teamspeak.com/<uuid>/PietSmiet`,
* and `<url>.svg` / `<url>_details.svg` → 200 image/svg+xml, 6880 / 7278 bytes, the same sizes as the TS6 cache
* files. The suffix rule is verified for that sample, not for every catalog entry. Only URLs on the fixed
* catalog origin are ever requested.
*
* Network policy (same as phishing-list.js): anonymous GET, no cookies/credentials/referrer, redirect:'error',
* bounded time and bytes, single-flight, no request until the renderer first needs badge data, failed refreshes
* keep the previous list, the last good list and fetched artwork are cached in the profile with a size bound.
*/
const fs = require('node:fs');
const path = require('node:path');
const BADGE_LIST_URL = 'https://badges-content.teamspeak.com/list';
const BADGE_ORIGIN = 'https://badges-content.teamspeak.com';
const REFRESH_MS = 24 * 60 * 60 * 1000;
const RETRY_MS = 10 * 60 * 1000;
const REQUEST_TIMEOUT_MS = 20000;
const MAX_LIST_BYTES = 4 * 1024 * 1024;
const MAX_BADGES = 10000;
const MAX_ART_BYTES = 512 * 1024;
const MAX_CACHED_ART = 400;
const MAX_REQUEST_UUIDS = 64;
const CACHE_VERSION = 1;
const MAX_NAME = 256;
const MAX_DESCRIPTION = 2048;
const MAX_URL = 1024;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/;
const SVG_START = /^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*(?:<!DOCTYPE[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg[\s>]/i;
class BadgeError extends Error {
constructor(code, message) { super(message); this.code = code; }
}
const validUuid = (v) => typeof v === 'string' && UUID.test(v);
// ---------- protobuf (proto3 wire format, only what BadgeList needs) ----------
function readVarint(buf, state) {
let result = 0;
let scale = 1;
for (let i = 0; i < 10; i += 1) {
if (state.pos >= buf.length) throw new BadgeError('format', 'badge list: truncated varint');
const byte = buf[state.pos++];
result += (byte & 0x7f) * scale;
if ((byte & 0x80) === 0) return result;
scale *= 128;
}
throw new BadgeError('format', 'badge list: varint too long');
}
/** Calls onField(fieldNo, wireType, value) for each field of buf; value is a Number (varint) or a subarray. */
function readFields(buf, onField) {
const state = { pos: 0 };
while (state.pos < buf.length) {
const key = readVarint(buf, state);
const field = Math.floor(key / 8);
const wire = key % 8;
if (field < 1) throw new BadgeError('format', 'badge list: invalid field number');
switch (wire) {
case 0: onField(field, wire, readVarint(buf, state)); break;
case 1:
if (state.pos + 8 > buf.length) throw new BadgeError('format', 'badge list: truncated fixed64');
state.pos += 8;
break;
case 2: {
const length = readVarint(buf, state);
if (length > buf.length - state.pos) throw new BadgeError('format', 'badge list: truncated field');
onField(field, wire, buf.subarray(state.pos, state.pos + length));
state.pos += length;
break;
}
case 5:
if (state.pos + 4 > buf.length) throw new BadgeError('format', 'badge list: truncated fixed32');
state.pos += 4;
break;
default: throw new BadgeError('format', `badge list: unsupported wire type ${wire}`);
}
}
}
const utf8 = new TextDecoder('utf-8', { fatal: true });
function text(bytes) {
try { return utf8.decode(bytes); } catch { throw new BadgeError('format', 'badge list: invalid UTF-8'); }
}
/** Only https URLs on the fixed catalog origin, without credentials, query or fragment. */
function catalogUrl(value) {
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_URL) return null;
let url;
try { url = new URL(value); } catch { return null; }
if (url.origin !== BADGE_ORIGIN || url.username || url.password || url.search || url.hash || url.pathname.length < 2) return null;
return url.href;
}
function cleanBadge(raw) {
const uuid = typeof raw.uuid === 'string' ? raw.uuid.toLowerCase() : '';
if (!validUuid(uuid)) return null;
const name = raw.name ?? '';
const description = raw.description ?? '';
if (name.length > MAX_NAME || CONTROL.test(name) || description.length > MAX_DESCRIPTION || CONTROL.test(description)) return null;
return { uuid, name, description, url: catalogUrl(raw.url) };
}
/**
* Bytes → { version, updated, badges }. Structural errors reject the whole body; individual badges with an invalid
* UUID or text are dropped, duplicates keep the first entry. A body without any valid badge is rejected.
*/
function parseBadgeList(bytes) {
const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
if (buf.length === 0 || buf.length > MAX_LIST_BYTES) throw new BadgeError('format', 'badge list: empty or too large');
let version = 0;
let updated = 0;
const raws = [];
readFields(buf, (field, wire, value) => {
if (field === 1 && wire === 0) version = value;
else if (field === 2 && wire === 0) updated = value;
else if (field === 3 && wire === 2) {
if (raws.length >= MAX_BADGES) throw new BadgeError('format', 'badge list: too many badges');
const badge = {};
readFields(value, (f, w, v) => {
if (w !== 2) return;
if (f === 1) badge.uuid = text(v);
else if (f === 2) badge.name = text(v);
else if (f === 3) badge.url = text(v);
else if (f === 4) badge.description = text(v);
});
raws.push(badge);
}
});
const seen = new Set();
const badges = [];
for (const raw of raws) {
const badge = cleanBadge(raw);
if (!badge || seen.has(badge.uuid)) continue;
seen.add(badge.uuid);
badges.push(badge);
}
if (badges.length === 0) throw new BadgeError('format', 'badge list: no valid badges');
return { version, updated, badges };
}
/** Network artwork URL for a catalog entry; null unless it stays on the fixed origin. */
function artworkUrl(badge, detailed) {
if (!badge?.url) return null;
const base = badge.url.endsWith('.svg') ? badge.url.slice(0, -4) : badge.url;
return catalogUrl(`${base}${detailed ? '_details' : ''}.svg`);
}
function validSvg(value) {
return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= MAX_ART_BYTES && SVG_START.test(value.replace(/^\uFEFF/, ''));
}
async function readBounded(res, max, signal) {
const declared = Number(res.headers?.get?.('content-length'));
if (Number.isFinite(declared) && declared > max) throw new BadgeError('too-large', 'badge response too large');
if (!res.body || typeof res.body.getReader !== 'function') {
const buf = Buffer.from(await res.arrayBuffer());
if (signal.aborted) throw signal.reason;
if (buf.length > max) throw new BadgeError('too-large', 'badge response too large');
return buf;
}
const reader = res.body.getReader();
const chunks = [];
let total = 0;
const onAbort = () => { reader.cancel(signal.reason).catch(() => {}); };
signal.addEventListener('abort', onAbort, { once: true });
try {
for (;;) {
if (signal.aborted) throw signal.reason;
const { done, value } = await reader.read();
if (signal.aborted) throw signal.reason;
if (done) break;
total += value.byteLength;
if (total > max) {
await reader.cancel().catch(() => {});
throw new BadgeError('too-large', 'badge response too large');
}
chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
}
} finally {
signal.removeEventListener('abort', onAbort);
}
return Buffer.concat(chunks, total);
}
/** The installed official client's artwork cache directory (observed on Windows only; read-only use). */
function officialBadgeCacheDirs(env = process.env, platform = process.platform) {
if (platform !== 'win32' || typeof env.LOCALAPPDATA !== 'string' || !path.win32.isAbsolute(env.LOCALAPPDATA)) return [];
return [path.win32.join(env.LOCALAPPDATA, 'TeamSpeak', 'Cache', 'Default', 'badges', '96')];
}
class BadgeCatalog {
/**
* @param {object} o
* @param {string} o.cacheDir profile directory for list.json and fetched artwork
* @param {(url: string, init: object) => Promise<Response>} o.fetchImpl Electron net.fetch in the app
* @param {string[]} [o.officialCacheDirs] read-only artwork directories of an installed TS6 client
* @param {boolean} [o.enabled] false: no network (offscreen tests); caches are still read
*/
constructor({ cacheDir, fetchImpl, officialCacheDirs = [], enabled = true, now = Date.now, log = () => {} }) {
Object.assign(this, { cacheDir, fetchImpl, officialCacheDirs, enabled, now, log });
this.badges = new Map();
this.fetchedAt = null;
this.checkedAt = null;
this.fromCache = false;
this.error = null;
this.cacheLoaded = false;
this.pending = null;
this.artPending = new Map();
this.artFailures = new Map();
this.controllers = new Set();
this.generation = 0;
}
status() {
return {
enabled: this.enabled, source: BADGE_LIST_URL, loaded: this.fetchedAt !== null, count: this.badges.size,
fetchedAt: this.fetchedAt, checkedAt: this.checkedAt, fromCache: this.fromCache, error: this.error,
};
}
get listFile() { return path.join(this.cacheDir, 'list.json'); }
get artDir() { return path.join(this.cacheDir, 'art'); }
loadCache() {
if (this.cacheLoaded) return;
this.cacheLoaded = true;
try {
const stat = fs.statSync(this.listFile);
if (!stat.isFile() || stat.size > MAX_LIST_BYTES * 2) return;
const data = JSON.parse(fs.readFileSync(this.listFile, 'utf8'));
if (data?.version !== CACHE_VERSION || data.source !== BADGE_LIST_URL || !Number.isFinite(data.fetchedAt)
|| !Array.isArray(data.badges) || data.badges.length > MAX_BADGES) return;
const badges = new Map();
for (const entry of data.badges) {
const badge = entry && typeof entry === 'object' ? cleanBadge(entry) : null;
if (badge && !badges.has(badge.uuid)) badges.set(badge.uuid, badge);
}
if (badges.size === 0 || (this.fetchedAt !== null && this.fetchedAt >= data.fetchedAt)) return;
this.badges = badges;
this.fetchedAt = data.fetchedAt;
this.fromCache = true;
} catch {
// no cache yet or unreadable
}
}
/** Loads the cache and starts a refresh when the list is missing or older than REFRESH_MS (RETRY_MS after a failure). */
ensureFresh() {
this.loadCache();
if (!this.enabled) return Promise.resolve(this.status());
const now = this.now();
const stale = this.fetchedAt === null || now - this.fetchedAt >= REFRESH_MS;
const recentlyTried = this.checkedAt !== null && now - this.checkedAt < (this.error ? RETRY_MS : REFRESH_MS);
if (stale && !recentlyTried) return this.refresh();
return this.pending ?? Promise.resolve(this.status());
}
refresh() {
if (!this.enabled) return Promise.resolve(this.status());
if (!this.pending) {
const pending = this.fetchList().finally(() => { if (this.pending === pending) this.pending = null; });
this.pending = pending;
}
return this.pending;
}
stop() {
this.generation += 1;
for (const controller of this.controllers) controller.abort(new BadgeError('stopped', 'badge catalog stopped'));
this.controllers.clear();
this.pending = null;
this.artPending.clear();
}
async request(url, accept) {
const generation = this.generation;
const controller = new AbortController();
this.controllers.add(controller);
const timer = setTimeout(() => controller.abort(new BadgeError('timeout', `badges: no answer in ${REQUEST_TIMEOUT_MS / 1000} s`)), REQUEST_TIMEOUT_MS);
timer.unref?.();
try {
const res = await this.fetchImpl(url, {
method: 'GET', signal: controller.signal, redirect: 'error', cache: 'no-store',
credentials: 'omit', referrerPolicy: 'no-referrer', headers: { Accept: accept },
});
if (generation !== this.generation) throw new BadgeError('stopped', 'badge catalog stopped');
if (res.redirected || (res.url && res.url !== url)) throw new BadgeError('redirect', 'badge response did not come from the fixed endpoint');
if (!res.ok) throw new BadgeError('http', `badges: HTTP ${res.status}`);
const body = await readBounded(res, accept === 'image/svg+xml' ? MAX_ART_BYTES : MAX_LIST_BYTES, controller.signal);
if (generation !== this.generation) throw new BadgeError('stopped', 'badge catalog stopped');
return body;
} catch (err) {
const reason = controller.signal.aborted ? controller.signal.reason : null;
throw reason instanceof BadgeError ? reason : err;
} finally {
clearTimeout(timer);
this.controllers.delete(controller);
}
}
async fetchList() {
const generation = this.generation;
this.checkedAt = this.now();
try {
const body = await this.request(BADGE_LIST_URL, 'application/octet-stream');
const { badges } = parseBadgeList(body);
if (generation !== this.generation) return this.status();
this.badges = new Map(badges.map((badge) => [badge.uuid, badge]));
this.fetchedAt = this.now();
this.fromCache = false;
this.error = null;
this.writeList();
this.log('info', `badge catalog: ${badges.length} badges`);
} catch (err) {
if (generation !== this.generation) return this.status();
this.error = { code: err instanceof BadgeError ? err.code : 'network', message: String(err?.message ?? err) };
this.log('warn', `badge catalog: ${this.error.message} (keeping ${this.badges.size} known badges)`);
}
return this.status();
}
writeList() {
try {
fs.mkdirSync(this.cacheDir, { recursive: true });
const tmp = `${this.listFile}.tmp`;
fs.writeFileSync(tmp, JSON.stringify({ version: CACHE_VERSION, source: BADGE_LIST_URL, fetchedAt: this.fetchedAt, badges: [...this.badges.values()] }));
fs.renameSync(tmp, this.listFile);
} catch (err) {
this.log('warn', `badge catalog cache not written: ${err.message}`);
}
}
/** Catalog entries for the requested UUIDs (unknown ones flagged), plus the source status. */
async info(uuids) {
await this.ensureFresh();
return {
status: this.status(),
badges: uuids.map((uuid) => {
const badge = this.badges.get(uuid);
return badge ? { uuid, known: true, name: badge.name, description: badge.description } : { uuid, known: false, name: '', description: '' };
}),
};
}
readArtFile(file) {
try {
const stat = fs.statSync(file);
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_ART_BYTES) return null;
const svg = fs.readFileSync(file, 'utf8');
return validSvg(svg) ? svg : null;
} catch {
return null;
}
}
/** SVG text for a badge: profile cache, then the installed TS6 cache, then the fixed catalog origin. */
async artwork(uuid, detailed) {
if (!validUuid(uuid)) throw new BadgeError('bad_request', 'invalid badge id');
const name = `${uuid}${detailed ? '_details' : ''}`;
const own = this.readArtFile(path.join(this.artDir, `${name}.svg`));
if (own) return { svg: own, source: 'cache' };
for (const dir of this.officialCacheDirs) {
const svg = this.readArtFile(path.join(dir, name));
if (svg) return { svg, source: 'teamspeak-cache' };
}
if (!this.enabled) throw new BadgeError('unavailable', 'badge artwork is not cached and network access is disabled');
const failedAt = this.artFailures.get(name);
if (failedAt !== undefined && this.now() - failedAt < RETRY_MS) throw new BadgeError('unavailable', 'badge artwork recently failed');
let pending = this.artPending.get(name);
if (!pending) {
pending = this.fetchArt(uuid, detailed, name).finally(() => { if (this.artPending.get(name) === pending) this.artPending.delete(name); });
this.artPending.set(name, pending);
}
return pending;
}
async fetchArt(uuid, detailed, name) {
await this.ensureFresh();
const url = artworkUrl(this.badges.get(uuid), detailed);
if (!url) throw new BadgeError('unavailable', 'badge is not in the public catalog');
try {
const svg = (await this.request(url, 'image/svg+xml')).toString('utf8');
if (!validSvg(svg)) throw new BadgeError('format', 'badge artwork is not an SVG image');
this.artFailures.delete(name);
this.writeArt(name, svg);
return { svg, source: 'network' };
} catch (err) {
this.artFailures.set(name, this.now());
throw err instanceof BadgeError ? err : new BadgeError('network', String(err?.message ?? err));
}
}
/** Atomic write; the oldest files beyond MAX_CACHED_ART are evicted. */
writeArt(name, svg) {
try {
fs.mkdirSync(this.artDir, { recursive: true });
const entries = fs.readdirSync(this.artDir).filter((file) => file.endsWith('.svg'));
if (entries.length >= MAX_CACHED_ART) {
const aged = entries.map((file) => {
try { return { file, at: fs.statSync(path.join(this.artDir, file)).mtimeMs }; } catch { return { file, at: 0 }; }
}).sort((a, b) => a.at - b.at);
for (const { file } of aged.slice(0, entries.length - MAX_CACHED_ART + 1)) fs.rmSync(path.join(this.artDir, file), { force: true });
}
const file = path.join(this.artDir, `${name}.svg`);
fs.writeFileSync(`${file}.tmp`, svg);
fs.renameSync(`${file}.tmp`, file);
} catch (err) {
this.log('warn', `badge artwork not cached: ${err.message}`);
}
}
}
const FORBIDDEN = Object.freeze({ ok: false, error: { code: 'forbidden', message: 'forbidden' } });
const failure = (err) => ({ ok: false, error: { code: err instanceof BadgeError ? err.code : 'internal', message: String(err?.message ?? err) } });
/** badges:info(uuids[]) and badges:art(uuid, detailed): the renderer never supplies a URL or a path. */
function registerBadgesIpc({ ipcMain, trustedSender, catalog }) {
ipcMain.handle('badges:info', async (event, uuids) => {
if (!trustedSender(event)) return FORBIDDEN;
if (!Array.isArray(uuids) || uuids.length > MAX_REQUEST_UUIDS || !uuids.every(validUuid)) {
return { ok: false, error: { code: 'bad_request', message: 'Invalid badge ids' } };
}
try { return { ok: true, ...(await catalog.info([...new Set(uuids)])) }; } catch (err) { return failure(err); }
});
ipcMain.handle('badges:art', async (event, uuid, detailed) => {
if (!trustedSender(event)) return FORBIDDEN;
if (!validUuid(uuid) || typeof detailed !== 'boolean') return { ok: false, error: { code: 'bad_request', message: 'Invalid badge request' } };
try { return { ok: true, ...(await catalog.artwork(uuid, detailed)) }; } catch (err) { return failure(err); }
});
}
module.exports = {
BadgeCatalog, registerBadgesIpc, parseBadgeList, artworkUrl, validSvg, officialBadgeCacheDirs,
BADGE_LIST_URL, BADGE_ORIGIN, MAX_LIST_BYTES, MAX_BADGES, MAX_ART_BYTES, MAX_CACHED_ART, MAX_REQUEST_UUIDS, REFRESH_MS,
};
+60
View File
@@ -0,0 +1,60 @@
'use strict';
/**
* Chat preferences that follow the official TS6 Settings > Chats page (client_ui/main.js settings component
* near offset 4873300; defaults from workflowSettings class `Xe` and appearanceSettings class `qe`).
*
* Official key → TeamsPeach key default
* appearanceSettings.chat_input_toolbar_visibility → chatToolbarVisibility 'always-visible'
* appearanceSettings.chat_mermaid_autoload_mode → chatMermaidAutoload 'only-simple'
* workflowSettings.openIncomingChats → chatOpenIncoming true
* appearanceSettings.chat_show_system_messages → chatShowModerationEvents true
* workflowSettings.use24hrTime → chatUse24hTime true
* workflowSettings.autoDownloadImages → autoDownloadImages false
* chat-server ignore list (per myTeamSpeak chat connection) → chatIgnoredUsers [] (local, keyed by client UID)
*
* Not modelled because TeamsPeach has no backing feature: useRichTextEditor (the composer is a plain
* textarea), autoAcceptIncomingDirectChats (TS6-server decentral chat invitations), useChatsHistory and
* sort_contacts_alphabetically / show_offline_contacts / group_offline_contacts (myTeamSpeak contacts and
* group chats).
*/
const MAX_IGNORED_USERS = 1000;
const MAX_NAME_LENGTH = 128;
// TeamSpeak client UIDs are base64 SHA-1 digests; ServerQuery clients use short ASCII ids such as "serveradmin".
const UID = /^[A-Za-z0-9+/]{1,126}={0,2}$/;
const CONTROL = /[\u0000-\u001f\u007f]/;
const isBool = (v) => typeof v === 'boolean';
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
function validUid(uid) {
return typeof uid === 'string' && uid.length <= 128 && UID.test(uid);
}
/** [{ uid, name }]: unique UIDs; `name` is the nickname seen when the user was ignored (display only). */
function validIgnoredUsers(list) {
if (!Array.isArray(list) || list.length > MAX_IGNORED_USERS) return false;
const seen = new Set();
for (const entry of list) {
if (!isPlainObject(entry)) return false;
const keys = Object.keys(entry);
if (keys.length !== 2 || !keys.includes('uid') || !keys.includes('name')) return false;
if (!validUid(entry.uid) || seen.has(entry.uid)) return false;
if (typeof entry.name !== 'string' || entry.name.length > MAX_NAME_LENGTH || CONTROL.test(entry.name)) return false;
seen.add(entry.uid);
}
return true;
}
const CHAT_SCHEMA = {
chatToolbarVisibility: { default: 'always-visible', check: (v) => v === 'inactive' || v === 'dynamic' || v === 'always-visible' },
chatMermaidAutoload: { default: 'only-simple', check: (v) => v === 'never' || v === 'only-simple' },
chatOpenIncoming: { default: true, check: isBool },
chatShowModerationEvents: { default: true, check: isBool },
chatUse24hTime: { default: true, check: isBool },
autoDownloadImages: { default: false, check: isBool },
chatIgnoredUsers: { default: [], check: validIgnoredUsers },
};
module.exports = { CHAT_SCHEMA, MAX_IGNORED_USERS, validUid };
+61
View File
@@ -0,0 +1,61 @@
'use strict';
/**
* Local contacts and the related server-tree options.
*
* The official TS6 contact list is a myTeamSpeak/Matrix service (direct rooms keyed by myTeamSpeak id, cloud
* presence, invites, categories, favourites). TeamsPeach has no account, so it keeps an account-free
* replacement on this computer only:
* - a contact is a TeamSpeak identity UID (the stable key the server reports for every client) with an optional
* local display alias and the nickname seen when it was added; nothing is sent to anyone when a contact is
* added, renamed or removed (no invite, no request, no acceptance by the other side);
* - presence is derived only from the snapshots of servers this client is connected to: "offline" means "not on
* any connected server", never a cloud status.
* Blocking reuses the existing chatIgnoredUsers list (chat-prefs.js) rather than a second list.
*
* Official appearanceSettings key (client_ui/main.js class qe) → TeamsPeach key default
* sort_contacts_alphabetically → contactsSortAlphabetically true
* show_offline_contacts → contactsShowOffline true
* group_offline_contacts → contactsGroupOffline true
* contact_grouping.state.online_is_expanded / offline_is_expanded (class T defaults)
* → contactsOnlineExpanded true / contactsOfflineExpanded false
* show_server_badges → showBadges true
* should_highlight_contacts → highlightContacts true
*/
const { validUid } = require('./chat-prefs');
const MAX_CONTACTS = 1000;
const MAX_TEXT = 128;
const CONTROL = /[\u0000-\u001f\u007f]/;
const isBool = (v) => typeof v === 'boolean';
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
const validText = (v) => typeof v === 'string' && v.length <= MAX_TEXT && !CONTROL.test(v);
/** [{ uid, alias, name }]: unique UIDs; alias '' = no local rename; name = nickname seen when added (display fallback). */
function validContacts(list) {
if (!Array.isArray(list) || list.length > MAX_CONTACTS) return false;
const seen = new Set();
for (const entry of list) {
if (!isPlainObject(entry)) return false;
const keys = Object.keys(entry);
if (keys.length !== 3 || !keys.includes('uid') || !keys.includes('alias') || !keys.includes('name')) return false;
if (!validUid(entry.uid) || seen.has(entry.uid) || !validText(entry.alias) || !validText(entry.name)) return false;
seen.add(entry.uid);
}
return true;
}
const CONTACT_SCHEMA = {
contacts: { default: [], check: validContacts },
contactsSortAlphabetically: { default: true, check: isBool },
contactsShowOffline: { default: true, check: isBool },
contactsGroupOffline: { default: true, check: isBool },
contactsOnlineExpanded: { default: true, check: isBool },
contactsOfflineExpanded: { default: false, check: isBool },
showBadges: { default: true, check: isBool },
highlightContacts: { default: true, check: isBool },
};
module.exports = { CONTACT_SCHEMA, MAX_CONTACTS, validContacts };
+515
View File
@@ -0,0 +1,515 @@
'use strict';
// Settings > About data (installed client_ui/main.js: ChangelogEntry render@1810599, changelog view
// render@1814959, Open Source Licenses list render@1822582, license detail render@1821111).
//
// The official client reads a changelog feed and fetches tsui://default/licenses/licenses.json
// ({ name: { icon, repository, licenseText } }). TeamsPeach serves the same three views from files that are
// actually part of this installation, chosen here in main only; the renderer passes nothing but an opaque
// license id that must exist in the index built below:
// - CHANGELOG.md (repository root; packaged as resources/CHANGELOG.md),
// - the licenses folder (repository LICENSES/; packaged as resources/licenses/) with the TeamsPeach notice,
// bundled font/noise-reduction notices and the native core's generated THIRD_PARTY_NOTICES.md,
// - Electron's own LICENSE and Chromium's LICENSES.chromium.html next to the executable,
// - license files of the production npm dependency tree inside the application directory,
// - the chat renderer vendor notices (app/renderer/vendor/THIRD_PARTY_NOTICES.txt).
// Nothing is fetched from the network. A source that is missing in this installation is reported as missing.
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const path = require('node:path');
const MAX_CHANGELOG_BYTES = 2 * 1024 * 1024;
const MAX_NOTICE_BYTES = 64 * 1024 * 1024;
const LICENSE_FILE = /^(licen[cs]e|copying|notice|unlicense)([-._].*)?$/i;
const GROUP_ORDER = ['teamspeach', 'electron', 'chromium', 'npm', 'core', 'renderer'];
// ---------- CHANGELOG.md ----------
const RELEASE_HEADING = /^##\s+(.+?)\s*$/;
const DATED = /^(.+?)\s+[—–-]\s+(\d{4}-\d{2}-\d{2})(?:\s+(.*))?$/;
/**
* Keep-a-changelog style CHANGELOG.md → official changelog entries (old format: notes + changes).
* `## <version> — <YYYY-MM-DD> [qualifier]` or `## Unreleased`; paragraphs become notes, `- ` items changes
* (indented continuation lines are joined with a space).
*/
function parseChangelog(markdown) {
const entries = [];
let entry = null;
let block = null; // { kind: 'note' | 'change', lines: [] }
const flush = () => {
if (!entry || !block) { block = null; return; }
const text = block.lines.join(' ').replace(/\s+/g, ' ').trim();
if (text) (block.kind === 'change' ? entry.changes : entry.notes).push(text);
block = null;
};
for (const raw of String(markdown).split(/\r?\n/)) {
const heading = RELEASE_HEADING.exec(raw);
if (heading && !raw.startsWith('###')) {
flush();
const title = heading[1];
const dated = DATED.exec(title);
entry = {
version: dated ? dated[1].trim() : title,
date: dated ? dated[2] : null,
qualifier: dated && dated[3] ? dated[3].trim() : null,
unreleased: !dated && /^unreleased$/i.test(title),
notes: [],
changes: [],
};
entries.push(entry);
continue;
}
if (!entry) continue;
if (/^#/.test(raw)) { flush(); continue; }
if (!raw.trim()) { flush(); continue; }
const item = /^[-*]\s+(.*)$/.exec(raw);
if (item) {
flush();
block = { kind: 'change', lines: [item[1]] };
} else if (block) {
block.lines.push(raw.trim());
} else {
block = { kind: 'note', lines: [raw.trim()] };
}
}
flush();
return entries;
}
// ---------- core THIRD_PARTY_NOTICES.md (core/tools/third_party_notices.py) ----------
const CRATES_IO_INDEX = 'registry+https://github.com/rust-lang/crates.io-index';
function crateRepository(name, version, source) {
if (source === CRATES_IO_INDEX) return `https://crates.io/crates/${encodeURIComponent(name)}/${encodeURIComponent(version)}`;
const git = /^git\+(https:\/\/[^?#\s]+)/.exec(source);
return git ? git[1].replace(/\.git$/, '') : null;
}
/** Fenced text blocks following a `### a 1.0 (FILE); b 2.0 (FILE)` header, keyed by "name version". */
function parseCoreNotices(markdown) {
const lines = String(markdown).split(/\r?\n/);
const crates = [];
let intro = '';
let i = 0;
for (; i < lines.length && !lines[i].startsWith('| '); i++) {
if (!lines[i].startsWith('#') && lines[i].trim()) intro += `${intro ? ' ' : ''}${lines[i].trim()}`;
}
for (; i < lines.length && lines[i].startsWith('|'); i++) {
const cells = lines[i].split('|').slice(1, -1).map((cell) => cell.trim());
if (cells.length !== 4 || cells[0] === 'Crate' || /^-+$/.test(cells[0])) continue;
const [name, version, license, source] = cells;
crates.push({ name, version, license, repository: crateRepository(name, version, source), texts: [] });
}
const byKey = new Map(crates.map((crate) => [`${crate.name} ${crate.version}`, crate]));
const extra = [];
let header = null;
let fence = null;
for (; i < lines.length; i++) {
const line = lines[i];
if (fence) {
if (line.startsWith('```')) {
const text = fence.join('\n');
if (header.kind === 'section') extra.push({ name: header.title, version: null, license: null, repository: null, texts: [{ label: null, text }] });
else {
for (const { key, label } of header.owners) byKey.get(key)?.texts.push({ label, text });
}
fence = null;
header = null;
} else fence.push(line);
continue;
}
if (line.startsWith('### ')) {
const owners = [];
// "a 1.0 (LICENSE-MIT); b 2.0 (LICENSE)"; a label may itself contain "; " (crates without a license file).
for (const m of line.slice(4).matchAll(/(?:^|; )([^\s;()]+) ([^\s;()]+) \(([^)]*)\)/g)) {
owners.push({ key: `${m[1]} ${m[2]}`, label: m[3] });
}
header = { kind: 'texts', owners };
} else if (line.startsWith('## ') && line.trim() !== '## License texts') {
// e.g. "## libopus (bundled in audiopus_sys, statically linked)"
header = { kind: 'section', title: line.slice(3).trim() };
} else if (line.startsWith('```') && header) {
fence = [];
}
}
return { intro, entries: [...extra, ...crates] };
}
// ---------- app/renderer/vendor/THIRD_PARTY_NOTICES.txt (scripts/vendor-chat-notices.mjs) ----------
const VENDOR_HEADER = /^===== (.+)@([^@\s]+) \((.*)\) =====$/;
function parseVendorNotices(text) {
const lines = String(text).split(/\r?\n/);
const preface = [];
const entries = [];
let current = null;
for (const line of lines) {
const header = VENDOR_HEADER.exec(line);
if (header) {
if (current) entries.push(current);
current = { name: header[1], version: header[2], license: header[3].replace(/^\((.*)\)$/, '$1'), lines: [] };
} else if (current) current.lines.push(line);
else if (line.trim()) preface.push(line.trim());
}
if (current) entries.push(current);
return {
// The first line is the file title; the rest states the inventory's scope.
intro: preface.slice(1).join(' '),
entries: entries.map(({ lines: body, ...entry }) => ({ ...entry, text: body.join('\n').trim() })),
};
}
// ---------- Electron LICENSES.chromium.html ----------
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0' };
function decodeEntities(text) {
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (all, code) => {
if (code[0] === '#') {
const n = code[1] === 'x' || code[1] === 'X' ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10);
return Number.isInteger(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : all;
}
return ENTITIES[code.toLowerCase()] ?? all;
});
}
const PRODUCT_TITLE = /^\s*<span class="title">([\s\S]*?)<\/span>/;
const PRODUCT_HOMEPAGE = /<span class="homepage"><a href="([^"]*)">/;
const PRODUCT_LICENSE = /<pre>([\s\S]*?)<\/pre>/;
/** Chromium credits page (tools/licenses/licenses.py): one product per <div class="product">. */
function parseChromiumCredits(html) {
const products = [];
for (const chunk of String(html).split('<div class="product">').slice(1)) {
const title = PRODUCT_TITLE.exec(chunk);
const license = PRODUCT_LICENSE.exec(chunk);
if (!title || !license) continue;
const homepage = PRODUCT_HOMEPAGE.exec(chunk);
const url = homepage ? decodeEntities(homepage[1]) : null;
products.push({
name: decodeEntities(title[1]).trim(),
repository: url && /^https?:\/\//i.test(url) ? url : null,
text: decodeEntities(license[1]),
});
}
return products;
}
// ---------- production npm dependencies ----------
/** package.json "repository" → https URL, or null when it is not a recognisable public URL. */
function npmRepository(repository) {
let url = typeof repository === 'string' ? repository : repository && typeof repository.url === 'string' ? repository.url : null;
if (!url) return null;
url = url.trim();
// npm shorthand: "user/repo" and "github:user/repo" denote GitHub.
const shorthand = /^(?:github:)?([\w.-]+)\/([\w.-]+)$/.exec(url);
if (shorthand) return `https://github.com/${shorthand[1]}/${shorthand[2].replace(/\.git$/, '')}`;
url = url.replace(/^git\+/, '')
.replace(/^git@([^:]+):/, 'https://$1/')
.replace(/^ssh:\/\/git@/, 'https://')
.replace(/^git:\/\//, 'https://')
.replace(/\.git$/, '');
return /^https:\/\/[^\s/]+\/\S+$/.test(url) ? url : null;
}
/** Node resolution of `name` required from `fromDir`, staying inside `rootDir`. */
function resolvePackage(fromDir, name, rootDir) {
let dir = fromDir;
for (;;) {
const candidate = path.join(dir, 'node_modules', name);
if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate;
if (path.resolve(dir) === path.resolve(rootDir)) return null;
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
/** Runtime `dependencies` (plus installed optional ones) reachable from the application's package.json. */
function collectProductionPackages(appDir) {
const found = new Map();
const missing = [];
const visit = (dir, manifest) => {
const names = new Set([...Object.keys(manifest.dependencies ?? {}), ...Object.keys(manifest.optionalDependencies ?? {})]);
for (const name of names) {
const location = resolvePackage(dir, name, appDir);
if (!location) {
if (!manifest.optionalDependencies?.[name]) missing.push(name);
continue;
}
if (found.has(location)) continue;
let pkg;
try { pkg = JSON.parse(fs.readFileSync(path.join(location, 'package.json'), 'utf8')); } catch { missing.push(name); continue; }
let files = [];
try { files = fs.readdirSync(location).filter((file) => LICENSE_FILE.test(file)).sort(); } catch { /* unreadable */ }
const license = typeof pkg.license === 'string' ? pkg.license
: Array.isArray(pkg.licenses) ? pkg.licenses.map((l) => l?.type ?? l).filter((l) => typeof l === 'string').join(' OR ') || null
: pkg.license?.type ?? null;
found.set(location, { name: pkg.name ?? name, version: pkg.version ?? null, license, repository: npmRepository(pkg.repository), location, files });
visit(location, pkg);
}
};
const root = JSON.parse(fs.readFileSync(path.join(appDir, 'package.json'), 'utf8'));
visit(appDir, root);
const packages = [...found.values()].sort((a, b) => a.name.localeCompare(b.name) || String(a.version).localeCompare(String(b.version)));
return { packages, missing: [...new Set(missing)].sort() };
}
// ---------- service ----------
const OS_DIR = { win32: 'win', darwin: 'mac', linux: 'linux' };
/** Fixed file locations for this installation; only main decides them. */
function informationPaths({ isPackaged, appRoot, appPath, resourcesPath, execPath, rendererDir, platform, arch }) {
const exeDir = path.dirname(execPath);
// Packaged: electron-builder renames Electron's LICENSE to LICENSE.electron.txt beside the executable
// (macOS: inside Contents/Resources). Development: node_modules/electron/dist (macOS: beside Electron.app).
const electronLicenses = isPackaged
? [path.join(exeDir, 'LICENSE.electron.txt'), path.join(resourcesPath, 'LICENSE.electron.txt')]
: [path.join(exeDir, 'LICENSE'), ...(platform === 'darwin' ? [path.resolve(exeDir, '..', '..', '..', 'LICENSE')] : [])];
const chromiumCredits = [path.join(exeDir, 'LICENSES.chromium.html'),
...(platform === 'darwin' ? [isPackaged ? path.join(resourcesPath, 'LICENSES.chromium.html') : path.resolve(exeDir, '..', '..', '..', 'LICENSES.chromium.html')] : [])];
const electronFiles = { electronLicenses, chromiumCredits };
if (isPackaged) {
return {
changelog: [path.join(resourcesPath, 'CHANGELOG.md')],
licensesDir: path.join(resourcesPath, 'licenses'),
coreNotices: [path.join(resourcesPath, 'licenses', 'teamspeach-core-THIRD_PARTY_NOTICES.md')],
appDir: appPath,
vendorDir: path.join(rendererDir, 'vendor'),
...electronFiles,
};
}
return {
changelog: [path.join(appRoot, 'CHANGELOG.md')],
licensesDir: path.join(appRoot, 'LICENSES'),
coreNotices: [
path.join(appRoot, 'core-bin', `${OS_DIR[platform] ?? platform}-${arch}`, 'THIRD_PARTY_NOTICES.md'),
path.join(appRoot, 'core', 'THIRD_PARTY_NOTICES.md'),
],
appDir: appRoot,
vendorDir: path.join(rendererDir, 'vendor'),
...electronFiles,
};
}
// Known files of the licenses folder (LICENSES/NOTICE.md describes each); others are listed by file name.
const LICENSE_DIR_NAMES = {
'NOTICE.md': { name: 'TeamsPeach', order: 0 },
'NotoSans-OFL.txt': { name: 'Noto Sans', license: 'OFL-1.1', order: 1 },
'sonora-NOTICE.txt': { name: 'sonora', license: 'BSD-3-Clause', order: 2 },
'teamspeak-client-icons-PROVENANCE.md': { name: 'TeamSpeak 6 client icons', order: 3 },
};
const CORE_NOTICES_FILE = 'teamspeach-core-THIRD_PARTY_NOTICES.md';
async function readFirst(candidates, maxBytes) {
for (const file of candidates) {
try {
const stat = await fsp.stat(file);
if (!stat.isFile()) continue;
if (stat.size > maxBytes) throw Object.assign(new Error(`${path.basename(file)} is too large`), { code: 'too_large' });
return { file, text: await fsp.readFile(file, 'utf8') };
} catch (err) {
if (err.code === 'too_large') throw err;
}
}
return null;
}
function missingError(candidates) {
return { code: 'missing', file: path.basename(candidates[0]) };
}
function createInformationService(options) {
const paths = informationPaths(options);
const electronVersion = options.electronVersion ?? null;
let changelog = null;
let index = null;
async function getChangelog() {
if (!changelog) {
changelog = (async () => {
const found = await readFirst(paths.changelog, MAX_CHANGELOG_BYTES);
if (!found) return { ok: false, error: missingError(paths.changelog) };
return { ok: true, entries: parseChangelog(found.text) };
})().catch((err) => { changelog = null; return { ok: false, error: { code: err.code === 'too_large' ? 'too_large' : 'unreadable', file: 'CHANGELOG.md' } }; });
}
return changelog;
}
// Each group: { id, note, error, entries: [{ name, version, license, repository, load: () => Promise<string> }] }
async function teamspeachGroup() {
let files;
try { files = await fsp.readdir(paths.licensesDir); } catch { return { id: 'teamspeach', error: missingError([paths.licensesDir]), entries: [] }; }
const entries = files
.filter((file) => file !== CORE_NOTICES_FILE && /\.(md|txt)$/i.test(file))
.map((file) => ({ file, known: LICENSE_DIR_NAMES[file] }))
.sort((a, b) => (a.known?.order ?? 99) - (b.known?.order ?? 99) || a.file.localeCompare(b.file))
.map(({ file, known }) => ({
name: known?.name ?? file,
version: null,
license: known?.license ?? null,
repository: null,
load: () => fsp.readFile(path.join(paths.licensesDir, file), 'utf8'),
}));
return { id: 'teamspeach', entries };
}
async function electronGroups() {
const { electronLicenses: electronLicense, chromiumCredits } = paths;
const electron = await readFirst(electronLicense, MAX_NOTICE_BYTES);
const electronGroup = electron
? { id: 'electron', entries: [{ name: 'Electron', version: electronVersion, license: 'MIT', repository: null, load: async () => electron.text }] }
: { id: 'electron', error: missingError(['LICENSE.electron.txt']), entries: [] };
const chromium = await readFirst(chromiumCredits, MAX_NOTICE_BYTES);
if (!chromium) return [electronGroup, { id: 'chromium', error: missingError(chromiumCredits), entries: [] }];
const products = parseChromiumCredits(chromium.text);
const chromiumGroup = {
id: 'chromium',
entries: products.map(({ name, repository, text }) => ({ name, version: null, license: null, repository, load: async () => text })),
};
if (!products.length) chromiumGroup.error = { code: 'unparsed', file: 'LICENSES.chromium.html' };
return [electronGroup, chromiumGroup];
}
function npmGroup() {
let result;
try { result = collectProductionPackages(paths.appDir); } catch { return { id: 'npm', error: missingError([path.join(paths.appDir, 'package.json')]), entries: [] }; }
const group = {
id: 'npm',
entries: result.packages.map((pkg) => ({
name: pkg.name,
version: pkg.version,
license: pkg.license,
repository: pkg.repository,
noLicenseFile: pkg.files.length === 0,
load: async () => {
const parts = [];
for (const file of pkg.files) parts.push(`--- ${file} ---\n${(await fsp.readFile(path.join(pkg.location, file), 'utf8')).trim()}`);
return parts.join('\n\n');
},
})),
};
if (result.missing.length) group.error = { code: 'missing_packages', file: result.missing.join(', ') };
return group;
}
async function coreGroup() {
const found = await readFirst(paths.coreNotices, MAX_NOTICE_BYTES);
if (!found) return { id: 'core', error: missingError(paths.coreNotices), entries: [] };
const parsed = parseCoreNotices(found.text);
return {
id: 'core',
note: parsed.intro,
entries: parsed.entries.map((crate) => ({
name: crate.name,
version: crate.version,
license: crate.license,
repository: crate.repository,
noLicenseFile: crate.texts.length === 0,
load: async () => crate.texts.map(({ label, text }) => (label ? `--- ${label} ---\n${text}` : text)).join('\n\n'),
})),
};
}
async function rendererGroup() {
const file = path.join(paths.vendorDir, 'THIRD_PARTY_NOTICES.txt');
let text;
try { text = await fsp.readFile(file, 'utf8'); } catch { return { id: 'renderer', error: missingError([file]), entries: [] }; }
const parsed = parseVendorNotices(text);
let fromRegistry = new Set();
try {
const deps = JSON.parse(await fsp.readFile(path.join(paths.vendorDir, 'DEPENDENCIES.json'), 'utf8'));
fromRegistry = new Set((deps.packages ?? []).filter((p) => typeof p.resolved === 'string' && p.resolved.startsWith('https://registry.npmjs.org/')).map((p) => `${p.name}@${p.version}`));
} catch { /* inventory without registry provenance: no links */ }
return {
id: 'renderer',
note: parsed.intro,
entries: parsed.entries.map((entry) => ({
name: entry.name,
version: entry.version,
license: entry.license,
repository: fromRegistry.has(`${entry.name}@${entry.version}`) ? `https://www.npmjs.com/package/${entry.name}/v/${entry.version}` : null,
load: async () => entry.text,
})),
};
}
async function buildIndex() {
const settle = (promise, id) => Promise.resolve().then(promise).catch(() => ({ id, error: { code: 'unreadable', file: id }, entries: [] }));
const results = await Promise.all([
settle(teamspeachGroup, 'teamspeach'),
settle(electronGroups, 'electron'),
settle(npmGroup, 'npm'),
settle(coreGroup, 'core'),
settle(rendererGroup, 'renderer'),
]);
const groups = results.flat().sort((a, b) => GROUP_ORDER.indexOf(a.id) - GROUP_ORDER.indexOf(b.id));
const byId = new Map();
for (const group of groups) {
group.entries.forEach((entry, i) => {
entry.id = `${group.id}:${i}`;
byId.set(entry.id, entry);
});
}
return { groups, byId };
}
async function ensureIndex() {
if (!index) index = buildIndex().catch((err) => { index = null; throw err; });
return index;
}
async function getLicenses() {
try {
const { groups } = await ensureIndex();
return {
ok: true,
groups: groups.map((group) => ({
id: group.id,
note: group.note ?? null,
error: group.error ?? null,
entries: group.entries.map(({ id, name, version, license, repository, noLicenseFile }) => ({ id, name, version, license, repository, noLicenseFile: noLicenseFile === true })),
})),
};
} catch {
return { ok: false, error: { code: 'unreadable', file: null } };
}
}
async function getLicenseText(id) {
if (typeof id !== 'string' || id.length > 64 || !/^[a-z]+:\d+$/.test(id)) return { ok: false, error: { code: 'bad_request', file: null } };
let entry;
try { entry = (await ensureIndex()).byId.get(id); } catch { entry = null; }
if (!entry) return { ok: false, error: { code: 'not_found', file: null } };
try {
return { ok: true, id, name: entry.name, version: entry.version, license: entry.license, text: await entry.load() };
} catch {
return { ok: false, error: { code: 'unreadable', file: null } };
}
}
return { getChangelog, getLicenses, getLicenseText, paths };
}
function registerInformationIpc({ ipcMain, trustedSender, service }) {
const forbidden = { ok: false, error: { code: 'forbidden', file: null } };
ipcMain.handle('about:changelog', (event) => (trustedSender(event) ? service.getChangelog() : forbidden));
ipcMain.handle('about:licenses', (event) => (trustedSender(event) ? service.getLicenses() : forbidden));
ipcMain.handle('about:license-text', (event, id) => (trustedSender(event) ? service.getLicenseText(id) : forbidden));
}
module.exports = {
parseChangelog,
parseCoreNotices,
parseVendorNotices,
parseChromiumCredits,
collectProductionPackages,
npmRepository,
informationPaths,
createInformationService,
registerInformationIpc,
};
+255
View File
@@ -0,0 +1,255 @@
'use strict';
/**
* Key binding schema (keybinds.json version 2): profiles, actions, binding sources, conflicts and the
* version 1 → 2 migration. Pure: no file system and no Electron, so it is unit-testable.
*
* Actions follow the official hotkey action enum (main.js 6.0.0 @2287523): every enum entry except
* "Unassigned" has an id here. `kind` is when it runs:
* hold – down starts, up ends (official up/down pair: Push-To-Talk, Push-To-Mute, the three whispers);
* press – runs on down only (official GoLiveCurrentFullscreen: down Activate, up Deactivate = no-op);
* trigger – runs once on release (official single-mode actions store only the `up` event).
* `group` is the official settings group (get_all @2290500); a group holds at most MAX_PER_GROUP bindings.
*
* A binding has exactly one source:
* physical – { code, ctrl, alt, shift, meta, global }: KeyboardEvent.code plus modifiers; global ones are
* registered with the `teamspeach-core hotkeys` helper, local ones work only in the focused window;
* remote – { remote: { remoteApp, remoteButton } }: an approved Remote App keyPress button.
*/
const { randomUUID } = require('node:crypto');
const KEYBINDS_VERSION = 2;
const MAX_BINDINGS = 64; // per profile; also the helper's registration limit
const MAX_PROFILES = 32;
const MAX_PER_GROUP = 6; // official max_hotkeys_for_action (c3V = 6)
const PROFILE_NAME_MAX = 64;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const CONTROL = /[\u0000-\u001f\u007f]/;
const KEY_CODE = /^[A-Za-z0-9]{1,32}$/;
const REMOTE_APP = /^[a-z.]{1,128}$/; // docs/Remote Apps.md: identifier is [a-z.]
const MODIFIER_CODES = new Set(['ControlLeft', 'ControlRight', 'AltLeft', 'AltRight', 'ShiftLeft', 'ShiftRight', 'MetaLeft', 'MetaRight', 'OSLeft', 'OSRight']);
/** id → { kind, group, official }. Group order below is the settings order. */
const ACTIONS = Object.freeze({
push_to_talk: { kind: 'hold', group: 'push_to_talk', official: 'Push-To-Talk' },
push_to_mute: { kind: 'hold', group: 'push_to_mute', official: 'Push-To-Mute' },
microphone_toggle: { kind: 'trigger', group: 'microphone', official: 'Toggle Microphone Mute' },
microphone_mute: { kind: 'trigger', group: 'microphone', official: 'Microphone Mute' },
microphone_unmute: { kind: 'trigger', group: 'microphone', official: 'Microphone Unmute' },
speaker_toggle: { kind: 'trigger', group: 'speaker', official: 'Toggle Speaker Mute' },
speaker_mute: { kind: 'trigger', group: 'speaker', official: 'Speaker Mute' },
speaker_unmute: { kind: 'trigger', group: 'speaker', official: 'Speaker Unmute' },
away_toggle: { kind: 'trigger', group: 'away', official: 'Toggle Away Status' },
away_online: { kind: 'trigger', group: 'away', official: 'Set Online' },
away_set: { kind: 'trigger', group: 'away', official: 'Set Away' },
away_toggle_message: { kind: 'trigger', group: 'away', official: 'Toggle Away Status with Message' },
reply_whisper: { kind: 'hold', group: 'reply_whisper', official: 'Reply to the last user that whispered you' },
quick_whisper: { kind: 'hold', group: 'quick_whisper', official: 'Whisper to the currently selected items in the servertree' },
whisper_list: { kind: 'hold', group: 'whisper_list', official: 'Whisper to a set list', target: 'whisper_list' },
go_live_current: { kind: 'press', group: 'go_live_current', official: 'Go Live with current Fullscreen App' },
recording_start: { kind: 'trigger', group: 'recording_start', official: 'Start Recording' },
recording_stop: { kind: 'trigger', group: 'recording_stop', official: 'Stop Recording' },
recording_toggle_pause: { kind: 'trigger', group: 'recording_toggle_pause', official: 'Pause or Resume Recording' },
disconnect_current: { kind: 'trigger', group: 'disconnect', official: 'Disconnect from Current Server' },
disconnect_all: { kind: 'trigger', group: 'disconnect', official: 'Disconnect from All Servers' },
talk_power_request: { kind: 'trigger', group: 'talk_power', official: 'Request Talk Power' },
talk_power_grant_next: { kind: 'trigger', group: 'talk_power', official: 'Grant Next User Talk Power' },
});
const fail = (message) => { throw new Error(message); };
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
const onlyKeys = (v, keys) => Object.keys(v).every((k) => keys.includes(k));
const text = (v, min, max) => typeof v === 'string' && v.length >= min && v.length <= max && !CONTROL.test(v);
function normalizeId(id) {
const value = id === undefined || id === '' ? randomUUID() : id;
if (typeof value !== 'string' || !UUID.test(value)) fail('id: expected a UUID');
return value.toLowerCase();
}
/**
* Returns a normalized binding or throws naming the bad field. A whisper_list target may be '' or a list
* that no longer exists: like the official resolveTarget the row then asks for a list and does nothing.
*/
function normalizeBinding(b) {
if (!isObject(b) || !onlyKeys(b, ['id', 'action', 'target', 'code', 'ctrl', 'alt', 'shift', 'meta', 'global', 'remote'])) fail('binding: unknown field');
const id = normalizeId(b.id);
const spec = ACTIONS[b.action];
if (!spec) fail('action: unknown');
const target = b.target ?? '';
if (spec.target === 'whisper_list') {
if (typeof target !== 'string' || (target !== '' && !UUID.test(target))) fail('target: expected a whisper list UUID');
} else if (target !== '') fail('target: only whisper_list has a target');
const base = { id, action: b.action, target: target.toLowerCase() };
if (b.remote !== undefined) {
if (['code', 'ctrl', 'alt', 'shift', 'meta', 'global'].some((k) => b[k] !== undefined)) fail('remote: a remote binding has no physical key fields');
const r = b.remote;
if (!isObject(r) || !onlyKeys(r, ['remoteApp', 'remoteButton'])) fail('remote: unknown field');
if (typeof r.remoteApp !== 'string' || !REMOTE_APP.test(r.remoteApp)) fail('remote.remoteApp: invalid identifier');
if (!text(r.remoteButton, 1, 128)) fail('remote.remoteButton: 1-128 characters');
return { ...base, remote: { remoteApp: r.remoteApp, remoteButton: r.remoteButton } };
}
if (typeof b.code !== 'string' || !KEY_CODE.test(b.code) || MODIFIER_CODES.has(b.code)) fail('code: invalid key');
for (const m of ['ctrl', 'alt', 'shift', 'meta', 'global']) {
if (typeof (b[m] ?? false) !== 'boolean') fail(`${m}: expected true/false`);
}
return { ...base, code: b.code, ctrl: Boolean(b.ctrl), alt: Boolean(b.alt), shift: Boolean(b.shift), meta: Boolean(b.meta), global: b.global !== false };
}
function normalizeProfileName(name) {
if (typeof name !== 'string') fail('name: expected text');
const trimmed = name.trim();
if (!text(trimmed, 1, PROFILE_NAME_MAX)) fail(`name: 1-${PROFILE_NAME_MAX} characters`);
return trimmed;
}
/** Bindings of one profile; `previous` (same profile before the change) lets migrated groups keep >6 rows. */
function normalizeBindings(raw, previous = []) {
if (!Array.isArray(raw) || raw.length > MAX_BINDINGS) fail(`bindings: at most ${MAX_BINDINGS}`);
const next = raw.map(normalizeBinding);
if (new Set(next.map((b) => b.id)).size !== next.length) fail('bindings: duplicate id');
const count = (list) => list.reduce((m, b) => m.set(ACTIONS[b.action].group, (m.get(ACTIONS[b.action].group) ?? 0) + 1), new Map());
const before = count(previous);
for (const [group, n] of count(next)) {
if (n > Math.max(MAX_PER_GROUP, before.get(group) ?? 0)) fail(`bindings: at most ${MAX_PER_GROUP} per action`);
}
return next;
}
function normalizeProfile(p) {
if (!isObject(p) || !onlyKeys(p, ['id', 'name', 'bindings'])) fail('profile: unknown field');
const id = normalizeId(p.id);
const name = normalizeProfileName(p.name);
const bindings = [];
let dropped = 0;
for (const raw of Array.isArray(p.bindings) ? p.bindings.slice(0, MAX_BINDINGS) : []) {
try {
const b = normalizeBinding(raw);
if (!bindings.some((x) => x.id === b.id)) bindings.push(b);
} catch {
dropped += 1;
}
}
return { profile: { id, name, bindings }, dropped };
}
/**
* Loads a parsed store (version 1 or 2) into the v2 shape. Version 1 `{ bindings }` becomes one active
* profile named `defaultProfileName` holding every valid binding unchanged (ids, chords, global flag,
* targets); `requireExactMatch` is true because version 1 always matched exactly. A version 1 file without
* valid bindings becomes "No Profile" (the official first-run state). Fresh stores default to the official
* unchecked toggle (captured settings-keybinds: "Hotkeys will trigger even when other keys are pressed.").
*/
function loadStore(data, { defaultProfileName = 'Default' } = {}) {
const empty = { requireExactMatch: false, activeProfile: null, profiles: [] };
if (!data) return { state: empty, dropped: 0, migrated: false };
if (data.version === 1) {
const { profile, dropped } = normalizeProfile({ id: '', name: defaultProfileName, bindings: data.bindings });
if (profile.bindings.length === 0) return { state: { ...empty, requireExactMatch: true }, dropped, migrated: true };
return { state: { requireExactMatch: true, activeProfile: profile.id, profiles: [profile] }, dropped, migrated: true };
}
let dropped = 0;
const profiles = [];
for (const raw of Array.isArray(data.profiles) ? data.profiles.slice(0, MAX_PROFILES) : []) {
try {
const r = normalizeProfile(raw);
dropped += r.dropped;
if (!profiles.some((p) => p.id === r.profile.id)) profiles.push(r.profile);
} catch {
dropped += 1;
}
}
const active = typeof data.activeProfile === 'string' ? data.activeProfile.toLowerCase() : null;
return {
state: {
requireExactMatch: data.requireExactMatch === true,
activeProfile: profiles.some((p) => p.id === active) ? active : (profiles[0]?.id ?? null),
profiles,
},
dropped,
migrated: false,
};
}
const chordKey = (b) => `${b.ctrl ? 'C' : ''}${b.alt ? 'A' : ''}${b.shift ? 'S' : ''}${b.meta ? 'M' : ''}+${b.code}`;
const sourceKey = (b) => (b.remote ? `remote:${b.remote.remoteApp}:${b.remote.remoteButton}` : `key:${chordKey(b)}`);
/**
* Bindings that cannot work as stored: the same chord or remote button twice, a plain chord on the Audio
* push-to-talk key (voice.js handles that key itself), or a whisper_list row without an existing list.
*/
function conflicts(bindings, pttCode, listIds = null) {
const out = [];
const bySource = new Map();
for (const b of bindings) {
const key = sourceKey(b);
const other = bySource.get(key);
if (other) {
out.push({ id: b.id, reason: 'duplicate', with: other.id });
if (!out.some((c) => c.id === other.id && c.reason === 'duplicate')) out.push({ id: other.id, reason: 'duplicate', with: b.id });
} else bySource.set(key, b);
if (!b.remote && pttCode && b.action !== 'push_to_talk' && b.code === pttCode && !b.ctrl && !b.alt && !b.shift && !b.meta) out.push({ id: b.id, reason: 'ptt' });
if (listIds && ACTIONS[b.action]?.target === 'whisper_list' && !listIds.has(b.target)) out.push({ id: b.id, reason: 'select_list' });
}
return out;
}
const MODIFIER_BITS = [['ctrl', 1], ['alt', 2], ['shift', 4], ['meta', 8]];
const maskOf = (b) => MODIFIER_BITS.reduce((m, [k, bit]) => (b[k] ? m | bit : m), 0);
const popcount = (m) => (m & 1) + ((m >> 1) & 1) + ((m >> 2) & 1) + ((m >> 3) & 1);
/**
* Registrations for the global helper. Windows RegisterHotKey and X11 XGrabKey only fire on the exact
* modifier set, so "Require exact key match" off is realised by also registering the chord with extra
* modifiers. Every binding's own chord comes first; extra-modifier variants follow by fewest added
* modifiers while the helper limit allows, never taking a chord another binding uses exactly. Variant
* ids are `<id>~<mask>`; `variantOf` maps each registered id back to its binding id.
*/
function expandRegistrations(bindings, { exact, limit = MAX_BINDINGS } = {}) {
const regs = [];
const variantOf = new Map();
const taken = new Set();
for (const b of bindings.slice(0, limit)) {
regs.push(b);
variantOf.set(b.id, b.id);
taken.add(chordKey(b));
}
let wanted = 0;
if (!exact) {
const extras = [];
for (let mask = 1; mask < 16; mask += 1) extras.push(mask);
extras.sort((a, b) => popcount(a) - popcount(b) || a - b);
for (const extra of extras) {
for (const b of bindings) {
if (maskOf(b) & extra) continue;
const variant = { ...b, id: `${b.id}~${extra}` };
for (const [k, bit] of MODIFIER_BITS) if (extra & bit) variant[k] = true;
const key = chordKey(variant);
if (taken.has(key)) continue;
wanted += 1;
if (regs.length >= limit) continue;
taken.add(key);
regs.push(variant);
variantOf.set(variant.id, b.id);
}
}
}
return { registrations: regs, variantOf, variants: { wanted, registered: regs.length - Math.min(bindings.length, limit) } };
}
module.exports = {
KEYBINDS_VERSION,
MAX_BINDINGS,
MAX_PROFILES,
MAX_PER_GROUP,
ACTIONS,
UUID,
normalizeBinding,
normalizeBindings,
normalizeProfileName,
loadStore,
conflicts,
chordKey,
expandRegistrations,
};
+59 -9
View File
@@ -3,7 +3,7 @@
const path = require('node:path'); const path = require('node:path');
const fs = require('node:fs'); const fs = require('node:fs');
const { const {
app, BrowserWindow, ipcMain, protocol, session, nativeTheme, dialog, Menu, shell, clipboard, desktopCapturer, nativeImage, app, BrowserWindow, ipcMain, protocol, session, nativeTheme, dialog, Menu, shell, clipboard, desktopCapturer, nativeImage, net,
} = require('electron'); } = require('electron');
// A disposable profile directory for tests/second instances. Set by whoever launches the app, never by the renderer. // A disposable profile directory for tests/second instances. Set by whoever launches the app, never by the renderer.
@@ -27,7 +27,7 @@ if (testOffscreen) {
for (const name of ['showOpenDialog', 'showSaveDialog', 'showMessageBox']) dialog[name] = async () => { throw new Error('Native dialogs are disabled in offscreen tests'); }; for (const name of ['showOpenDialog', 'showSaveDialog', 'showMessageBox']) dialog[name] = async () => { throw new Error('Native dialogs are disabled in offscreen tests'); };
} }
const { RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths'); const { APP_ROOT, RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths');
const { ConnectionManager } = require('./connections'); const { ConnectionManager } = require('./connections');
const { validateRequest } = require('./ipc-validate'); const { validateRequest } = require('./ipc-validate');
const { permissionCheckAllowed, permissionRequestAllowed } = require('./permissions'); const { permissionCheckAllowed, permissionRequestAllowed } = require('./permissions');
@@ -49,23 +49,38 @@ const { registerClientVolumesIpc } = require('./client-volumes');
const { registerWhisperIpc } = require('./whisper-main'); const { registerWhisperIpc } = require('./whisper-main');
const { registerServerSnapshotsIpc } = require('./server-snapshots'); const { registerServerSnapshotsIpc } = require('./server-snapshots');
const { registerStreamPopout } = require('./stream-popout-main'); const { registerStreamPopout } = require('./stream-popout-main');
const { registerRemoteAppsIpc } = require('./remote-apps');
const { PhishingList, registerPhishingIpc } = require('./phishing-list');
const { trustedHostsUpdateError } = require('./privacy-prefs');
const { createInformationService, registerInformationIpc } = require('./information-panels');
const { BadgeCatalog, registerBadgesIpc, officialBadgeCacheDirs } = require('./badges');
const { registerServerIconsIpc } = require('./server-icons');
const APP_SCHEME = 'app'; const APP_SCHEME = 'app';
const APP_HOST = 'teamspeach'; const APP_HOST = 'teamspeach';
const APP_ORIGIN = `${APP_SCHEME}://${APP_HOST}`; const APP_ORIGIN = `${APP_SCHEME}://${APP_HOST}`;
const MERMAID_FRAME_PATH = '/mermaid-frame.html';
const MERMAID_FRAME_CSP = [
"default-src 'none'",
`script-src ${APP_ORIGIN}/vendor/mermaid/mermaid.min.js ${APP_ORIGIN}/js/markdown/mermaid-frame.js`,
"style-src 'unsafe-inline'", 'img-src data: blob:', "connect-src 'none'",
"base-uri 'none'", "form-action 'none'", "frame-src 'none'", "object-src 'none'",
`frame-ancestors ${APP_ORIGIN}`, 'sandbox allow-scripts',
].join('; ');
const MERMAID_FRAME_PERMISSIONS = 'camera=(), microphone=(), display-capture=(), geolocation=(), fullscreen=(), clipboard-read=(), clipboard-write=(), autoplay=(), usb=(), serial=(), hid=(), midi=(), screen-wake-lock=(), encrypted-media=(), picture-in-picture=(), publickey-credentials-get=()';
const CSP = [ const CSP = [
"default-src 'none'", "default-src 'none'",
"script-src 'self'", "script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' tsext:", "style-src 'self' tsext:",
"img-src 'self' data: blob: tsext:", "img-src 'self' data: blob: tsext:",
"media-src 'self' blob: mediastream:", "media-src 'self' blob: mediastream:",
"font-src 'self' tsext:", "font-src 'self' tsext:",
"connect-src 'none'", "connect-src 'self'",
"worker-src 'self'", "worker-src 'self'",
"base-uri 'none'", "base-uri 'none'",
"form-action 'none'", "form-action 'none'",
"frame-src 'none'", `frame-src ${APP_ORIGIN}${MERMAID_FRAME_PATH}`,
"frame-ancestors 'none'", "frame-ancestors 'none'",
"object-src 'none'", "object-src 'none'",
].join('; '); ].join('; ');
@@ -79,6 +94,8 @@ const MIME = {
'.woff2': 'font/woff2', '.woff2': 'font/woff2',
'.ttf': 'font/ttf', '.ttf': 'font/ttf',
'.json': 'application/json', '.json': 'application/json',
'.wasm': 'application/wasm',
'.wav': 'audio/wav',
}; };
// Chromium hides host candidates behind mDNS names when the page has no capture permission. // Chromium hides host candidates behind mDNS names when the page has no capture permission.
@@ -106,6 +123,9 @@ let identities = null;
let whisperIpc = null; let whisperIpc = null;
let filesController = null; let filesController = null;
let streamPopout = null; let streamPopout = null;
let remoteApps = null;
let phishingList = null;
let badgeCatalog = null;
const gotInstanceLock = app.requestSingleInstanceLock(); const gotInstanceLock = app.requestSingleInstanceLock();
if (!gotInstanceLock) { if (!gotInstanceLock) {
@@ -129,7 +149,7 @@ function isAppUrl(url) {
} }
function trustedSender(event) { function trustedSender(event) {
return Boolean(mainWindow && event.sender === mainWindow.webContents && event.senderFrame && isAppUrl(event.senderFrame.url)); return Boolean(mainWindow && event.sender === mainWindow.webContents && event.senderFrame && event.senderFrame === mainWindow.webContents.mainFrame && isAppUrl(event.senderFrame.url));
} }
function sendToRenderer(channel, payload) { function sendToRenderer(channel, payload) {
@@ -139,6 +159,7 @@ function sendToRenderer(channel, payload) {
// ---------- server connections (one core process each) ---------- // ---------- server connections (one core process each) ----------
function sendConnections(list) { function sendConnections(list) {
remoteApps?.updateConnectionList(list);
sendToRenderer('connections:changed', { connections: list, input: connections.inputId }); sendToRenderer('connections:changed', { connections: list, input: connections.inputId });
} }
@@ -146,6 +167,7 @@ function startConnections() {
fs.mkdirSync(logsDir(), { recursive: true }); fs.mkdirSync(logsDir(), { recursive: true });
connections = new ConnectionManager({ resolveBinary: resolveCoreBinary, dataDir: dataDir(), logsDir: logsDir() }); connections = new ConnectionManager({ resolveBinary: resolveCoreBinary, dataDir: dataDir(), logsDir: logsDir() });
connections.on('status', (id, status) => { connections.on('status', (id, status) => {
remoteApps?.handleCoreStatus(id, status);
if (status.status !== 'ready') onConnectionInactive(id); if (status.status !== 'ready') onConnectionInactive(id);
sendToRenderer('core:status', { ...status, connectionId: id }); sendToRenderer('core:status', { ...status, connectionId: id });
}); });
@@ -167,6 +189,7 @@ function onConnectionInactive(id) {
} }
function onCoreEvent(id, evt) { function onCoreEvent(id, evt) {
remoteApps?.handleCoreEvent(id, evt);
filesController?.onEvent(id, evt); filesController?.onEvent(id, evt);
if (evt.event === 'audio') { if (evt.event === 'audio') {
if (typeof evt.pcm !== 'string') return; if (typeof evt.pcm !== 'string') return;
@@ -401,7 +424,8 @@ function registerProtocol() {
status: 200, status: 200,
headers: { headers: {
'Content-Type': type, 'Content-Type': type,
'Content-Security-Policy': CSP, 'Content-Security-Policy': rel === MERMAID_FRAME_PATH ? MERMAID_FRAME_CSP : CSP,
...(rel === MERMAID_FRAME_PATH ? { 'Permissions-Policy': MERMAID_FRAME_PERMISSIONS } : {}),
'X-Content-Type-Options': 'nosniff', 'X-Content-Type-Options': 'nosniff',
'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Opener-Policy': 'same-origin',
'Referrer-Policy': 'no-referrer', 'Referrer-Policy': 'no-referrer',
@@ -417,7 +441,7 @@ function hardenSession() {
const ses = session.defaultSession; const ses = session.defaultSession;
// Electron passes origins as "app://teamspeach/"; the policy normalises them (see permissions.js). // Electron passes origins as "app://teamspeach/"; the policy normalises them (see permissions.js).
ses.setPermissionRequestHandler((_wc, permission, callback, details) => { ses.setPermissionRequestHandler((_wc, permission, callback, details) => {
callback(!testOffscreen && (permissionRequestAllowed(permission, details, APP_ORIGIN) || capture.permissionRequestAllowed(_wc, permission, details))); callback(!testOffscreen && details?.isMainFrame !== false && (permissionRequestAllowed(permission, details, APP_ORIGIN) || capture.permissionRequestAllowed(_wc, permission, details)));
}); });
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin, details) => { ses.setPermissionCheckHandler((_wc, permission, requestingOrigin, details) => {
return !testOffscreen && permissionCheckAllowed(permission, requestingOrigin, details, APP_ORIGIN); return !testOffscreen && permissionCheckAllowed(permission, requestingOrigin, details, APP_ORIGIN);
@@ -440,6 +464,9 @@ app.on('web-contents-created', (_event, contents) => {
// ---------- IPC ---------- // ---------- IPC ----------
function registerIpc() { function registerIpc() {
registerInformationIpc({ ipcMain, trustedSender, service: createInformationService({ isPackaged: app.isPackaged,
appRoot: APP_ROOT, appPath: app.getAppPath(), resourcesPath: process.resourcesPath, execPath: process.execPath,
rendererDir: RENDERER_DIR, platform: process.platform, arch: process.arch, electronVersion: process.versions.electron }) });
registerTitlebarIpc(ipcMain, () => mainWindow, APP_ORIGIN); registerTitlebarIpc(ipcMain, () => mainWindow, APP_ORIGIN);
capture.registerIpc(ipcMain, (event) => !testOffscreen && trustedSender(event)); capture.registerIpc(ipcMain, (event) => !testOffscreen && trustedSender(event));
appAudio.registerIpc(ipcMain, (event) => !testOffscreen && trustedSender(event)); appAudio.registerIpc(ipcMain, (event) => !testOffscreen && trustedSender(event));
@@ -450,7 +477,25 @@ function registerIpc() {
osSettings = registerOsSettings({ ipcMain, trustedSender, getWindow: () => mainWindow, testOffscreen, prefs, translate: (k) => i18n.t(k, {}, prefs.get().language), iconPath: defaultIconPath() }); osSettings = registerOsSettings({ ipcMain, trustedSender, getWindow: () => mainWindow, testOffscreen, prefs, translate: (k) => i18n.t(k, {}, prefs.get().language), iconPath: defaultIconPath() });
registerClientVolumesIpc({ ipcMain, trustedSender, connections, file: path.join(path.dirname(prefsFile()), 'client-volumes.json'), log: (level, message) => appendLog('main.log', `${level}: ${message}`) }); registerClientVolumesIpc({ ipcMain, trustedSender, connections, file: path.join(path.dirname(prefsFile()), 'client-volumes.json'), log: (level, message) => appendLog('main.log', `${level}: ${message}`) });
identities = registerIdentityIpc({ ipcMain, trustedSender, getWindow: () => mainWindow, resolveCoreBinary, dataDir, dialog, tr, sendToRenderer, onChanged: onIdentityChanged }); identities = registerIdentityIpc({ ipcMain, trustedSender, getWindow: () => mainWindow, resolveCoreBinary, dataDir, dialog, tr, sendToRenderer, onChanged: onIdentityChanged });
whisperIpc = registerWhisperIpc({ ipcMain, trustedSender, getWindow: () => mainWindow, userDataDir: app.getPath('userData'), resolveBinary: () => resolveCoreBinary().path, testOffscreen, getPttCode: () => prefs.get().pttCode }); whisperIpc = registerWhisperIpc({ ipcMain, trustedSender, getWindow: () => mainWindow, userDataDir: app.getPath('userData'), resolveBinary: () => resolveCoreBinary().path, testOffscreen, getPttCode: () => prefs.get().pttCode, defaultProfileName: tr('keybind.profile.default') });
remoteApps = registerRemoteAppsIpc({ ipcMain, trustedSender, file: path.join(app.getPath('userData'), 'remote-apps.json'),
listen: !testOffscreen || process.env.TEAMSPEACH_TEST_REMOTE_APPS === '1', sendToRenderer,
log: (level, message) => appendLog('main.log', `${level}: ${message}`) });
remoteApps.updateConnectionList(connections.list());
phishingList = new PhishingList({ cacheFile: path.join(app.getPath('userData'), 'phishing-domains.json'),
fetchImpl: (url, init) => net.fetch(url, init), enabled: !testOffscreen,
log: (level, message) => appendLog('main.log', `${level}: ${message}`) });
registerPhishingIpc({ ipcMain, trustedSender, list: phishingList });
phishingList.start();
badgeCatalog = new BadgeCatalog({ cacheDir: path.join(app.getPath('userData'), 'badges'),
fetchImpl: (url, init) => net.fetch(url, init), enabled: !testOffscreen,
officialCacheDirs: testOffscreen ? [] : officialBadgeCacheDirs(),
log: (level, message) => appendLog('main.log', `${level}: ${message}`) });
registerBadgesIpc({ ipcMain, trustedSender, catalog: badgeCatalog });
registerServerIconsIpc({ ipcMain, trustedSender, dialog, nativeImage, getWindow: () => mainWindow,
request: (id, cmd, args) => ['file_upload', 'file_download'].includes(cmd) ? filesController.requestTransfer(id, cmd, args) : connections.request(id, cmd, args),
validConnectionId: (id) => ConnectionManager.validId(id), getConnection: (id) => connections.get(id),
subscribeCore: (listener) => { connections.on('event', listener); return () => connections.off('event', listener); }, testOffscreen, tr });
registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow: () => mainWindow, request: (id, cmd, args) => ['file_upload', 'file_download'].includes(cmd) ? filesController.requestTransfer(id, cmd, args) : connections.request(id, cmd, args), validConnectionId: (id) => ConnectionManager.validId(id), getConnection: (id) => connections.get(id), subscribeCore: (listener) => { connections.on('event', listener); return () => connections.off('event', listener); }, testOffscreen, tr }); registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow: () => mainWindow, request: (id, cmd, args) => ['file_upload', 'file_download'].includes(cmd) ? filesController.requestTransfer(id, cmd, args) : connections.request(id, cmd, args), validConnectionId: (id) => ConnectionManager.validId(id), getConnection: (id) => connections.get(id), subscribeCore: (listener) => { connections.on('event', listener); return () => connections.off('event', listener); }, testOffscreen, tr });
streamPopout = registerStreamPopout({ ipcMain, BrowserWindow, getWindow: () => mainWindow, trustedSender, appOrigin: APP_ORIGIN, getConnection: (id) => connections.get(id), testOffscreen }); streamPopout = registerStreamPopout({ ipcMain, BrowserWindow, getWindow: () => mainWindow, trustedSender, appOrigin: APP_ORIGIN, getConnection: (id) => connections.get(id), testOffscreen });
ipcMain.handle('core:request', async (event, connectionId, cmd, args) => { ipcMain.handle('core:request', async (event, connectionId, cmd, args) => {
@@ -545,6 +590,8 @@ function registerIpc() {
if (!trustedSender(event)) return { ok: false }; if (!trustedSender(event)) return { ok: false };
// Main-only: set by the recording folder dialog (recording-main.js), never by the renderer. // Main-only: set by the recording folder dialog (recording-main.js), never by the renderer.
if (partial && typeof partial === 'object' && Object.hasOwn(partial, 'recordingFolder')) return { ok: false, message: 'prefs: recordingFolder is chosen in the folder dialog' }; if (partial && typeof partial === 'object' && Object.hasOwn(partial, 'recordingFolder')) return { ok: false, message: 'prefs: recordingFolder is chosen in the folder dialog' };
const trustError = trustedHostsUpdateError(prefs.get(), partial, (host) => phishingList.has(host));
if (trustError) return { ok: false, message: trustError };
try { try {
const next = prefs.set(partial); const next = prefs.set(partial);
if (partial && Object.prototype.hasOwnProperty.call(partial, 'theme')) nativeTheme.themeSource = next.theme; if (partial && Object.prototype.hasOwnProperty.call(partial, 'theme')) nativeTheme.themeSource = next.theme;
@@ -659,6 +706,9 @@ app.on('before-quit', (event) => {
osSettings?.markQuitting(); osSettings?.markQuitting();
identities?.shutdown(); identities?.shutdown();
whisperIpc?.dispose(); whisperIpc?.dispose();
remoteApps?.dispose();
phishingList?.stop();
badgeCatalog?.stop();
streamPopout?.dispose(); streamPopout?.dispose();
appAudio?.stopAll(); appAudio?.stopAll();
capture?.cancel(); capture?.cancel();
+4 -2
View File
@@ -145,9 +145,11 @@ function registerOsSettings({ ipcMain, trustedSender, getWindow, testOffscreen,
return true; return true;
}); });
ipcMain.handle('os:notify', (event, title, body) => { ipcMain.handle('os:notify', (event, title, body, kind = 'private') => {
if (!trustedSender(event) || testOffscreen) return false; if (!trustedSender(event) || testOffscreen) return false;
if (prefs.get().systemNotifyServerPrivate !== true || !Notification.isSupported()) return false; if (kind !== 'private' && kind !== 'channel') return false;
const preference = kind === 'channel' ? 'systemNotifyChannelChat' : 'systemNotifyServerPrivate';
if (prefs.get()[preference] !== true || !Notification.isSupported()) return false;
if (typeof title !== 'string' || typeof body !== 'string' || title.length > 200) return false; if (typeof title !== 'string' || typeof body !== 'string' || title.length > 200) return false;
const win = getWindow(); const win = getWindow();
if (win && !win.isDestroyed() && win.isFocused()) return false; if (win && !win.isDestroyed() && win.isFocused()) return false;
+2
View File
@@ -29,6 +29,7 @@ function isAppOrigin(origin, appOrigin) {
/** setPermissionCheckHandler: enumerateDevices labels/ids and setSinkId depend on this. */ /** setPermissionCheckHandler: enumerateDevices labels/ids and setSinkId depend on this. */
function permissionCheckAllowed(permission, requestingOrigin, details, appOrigin) { function permissionCheckAllowed(permission, requestingOrigin, details, appOrigin) {
if (details?.isMainFrame === false) return false;
if (!isAppOrigin(requestingOrigin, appOrigin)) return false; if (!isAppOrigin(requestingOrigin, appOrigin)) return false;
if (permission === 'media') return Boolean(details) && details.mediaType === 'audio'; if (permission === 'media') return Boolean(details) && details.mediaType === 'audio';
return permission === 'speaker-selection'; return permission === 'speaker-selection';
@@ -36,6 +37,7 @@ function permissionCheckAllowed(permission, requestingOrigin, details, appOrigin
/** setPermissionRequestHandler: getUserMedia for audio only, and full screen, from a page of the app. */ /** setPermissionRequestHandler: getUserMedia for audio only, and full screen, from a page of the app. */
function permissionRequestAllowed(permission, details, appOrigin) { function permissionRequestAllowed(permission, details, appOrigin) {
if (details?.isMainFrame === false) return false;
if (!details || !isAppOrigin(details.requestingUrl, appOrigin)) return false; if (!details || !isAppOrigin(details.requestingUrl, appOrigin)) return false;
if (permission === 'fullscreen') return true; if (permission === 'fullscreen') return true;
if (permission !== 'media') return false; if (permission !== 'media') return false;
+226
View File
@@ -0,0 +1,226 @@
'use strict';
/**
* Threat classification for external links, from the same source as the installed TS6 client's
* ExternalLinkGuard (client_ui/main.js class Ee): PHISHING_LIST_URLS = [PHISHING_LIST_URL], fetched at start
* and every FETCH_INTERVAL_MS (1 h), one domain per line, matched exactly against the link's lowercase
* hostname ("warn-malicious").
*
* Network policy (stricter than the official fetch):
* - one fixed public HTTPS URL, anonymous GET: no cookies or credentials, no referrer, no query, no
* identifiers; the request never contains a visited link — classification is a local Set lookup;
* - redirect:'error': the fixed endpoint is fetched directly and any redirect fails the request before a second
* request is made; the whole request is bounded by REQUEST_TIMEOUT_MS and MAX_BYTES, and a body with any
* non-domain line (other than blank or '#' comment lines) or over MAX_DOMAINS is rejected as a whole, so an
* error page mixed with domains can never replace a known good list;
* - stop() aborts an in-flight request and discards its result: no list or cache update after stop;
* - a failed refresh keeps the previous list; the last good list is cached in the profile so a restart
* while offline still classifies links;
* - disabled (no request, no cache) when the owner passes enabled=false, e.g. offscreen tests.
*/
const fs = require('node:fs');
const path = require('node:path');
const PHISHING_LIST_URL = 'https://files.teamspeak-services.com/client/phishing-domains/active.txt';
const FETCH_INTERVAL_MS = 60 * 60 * 1000;
const REQUEST_TIMEOUT_MS = 20000;
const MAX_BYTES = 16 * 1024 * 1024;
const MAX_DOMAINS = 1000000;
const CACHE_VERSION = 1;
// Lowercase DNS name as WHATWG URL serialises it (punycode for IDN); '_' occurs in real hostnames.
const LABEL = '[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?';
const DOMAIN = new RegExp(`^(?=.{1,253}$)${LABEL}(?:\\.${LABEL})*$`);
const validDomain = (value) => typeof value === 'string' && DOMAIN.test(value);
class ListError extends Error {
constructor(code, message) { super(message); this.code = code; }
}
/** Text → Set of domains. Empty and '#' lines are skipped; any other non-domain line rejects the whole body. */
function parseList(text) {
const domains = new Set();
for (const line of text.split('\n')) {
const entry = line.trim().toLowerCase().replace(/\.$/, '');
if (!entry || entry.startsWith('#')) continue;
if (!validDomain(entry)) throw new ListError('bad-response', 'phishing list contains a line that is not a domain');
domains.add(entry);
if (domains.size > MAX_DOMAINS) throw new ListError('too-large', `phishing list has more than ${MAX_DOMAINS} domains`);
}
return { domains };
}
/** Reads at most `max` bytes; an abort (stop or timeout) cancels the body even if the stream ignores it. */
async function readBounded(res, max, signal) {
const declared = Number(res.headers?.get?.('content-length'));
if (Number.isFinite(declared) && declared > max) throw new ListError('too-large', 'phishing list response too large');
if (!res.body || typeof res.body.getReader !== 'function') {
const text = await res.text();
if (signal.aborted) throw signal.reason;
if (Buffer.byteLength(text) > max) throw new ListError('too-large', 'phishing list response too large');
return text;
}
const reader = res.body.getReader();
const chunks = [];
let total = 0;
const onAbort = () => { reader.cancel(signal.reason).catch(() => {}); };
signal.addEventListener('abort', onAbort, { once: true });
try {
for (;;) {
if (signal.aborted) throw signal.reason;
const { done, value } = await reader.read();
if (signal.aborted) throw signal.reason;
if (done) break;
total += value.byteLength;
if (total > max) {
await reader.cancel().catch(() => {});
throw new ListError('too-large', 'phishing list response too large');
}
chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
}
} finally {
signal.removeEventListener('abort', onAbort);
}
return Buffer.concat(chunks, total).toString('utf8');
}
class PhishingList {
/**
* @param {object} o
* @param {string} o.cacheFile profile file for the last good list
* @param {(url: string, init: object) => Promise<Response>} o.fetchImpl Electron net.fetch in the app
* @param {boolean} [o.enabled]
*/
constructor({ cacheFile, fetchImpl, enabled = true, now = Date.now, setIntervalImpl = setInterval, clearIntervalImpl = clearInterval, log = () => {} }) {
Object.assign(this, { cacheFile, fetchImpl, enabled, now, setIntervalImpl, clearIntervalImpl, log });
this.domains = new Set();
this.fetchedAt = null; // ms of the list in use (network or cache)
this.checkedAt = null; // ms of the last network attempt
this.fromCache = false;
this.error = null;
this.timer = null;
this.pending = null;
this.controller = null; // AbortController of the in-flight request
this.generation = 0; // bumped by stop(); results of an older generation are discarded
}
/** Exact hostname match, like the official `_phishingDomains.has(hostname)`. */
has(host) {
return typeof host === 'string' && this.domains.has(host.toLowerCase().replace(/\.$/, ''));
}
status() {
return {
enabled: this.enabled, source: PHISHING_LIST_URL, loaded: this.fetchedAt !== null, count: this.domains.size,
fetchedAt: this.fetchedAt, checkedAt: this.checkedAt, fromCache: this.fromCache, error: this.error,
};
}
start() {
if (!this.enabled || this.timer !== null) return;
this.loadCache();
void this.refresh();
this.timer = this.setIntervalImpl(() => { void this.refresh(); }, FETCH_INTERVAL_MS);
this.timer?.unref?.();
}
/** Ends the schedule, aborts an in-flight request and discards its result. refresh() may be called again later. */
stop() {
if (this.timer !== null) this.clearIntervalImpl(this.timer);
this.timer = null;
this.generation += 1;
this.controller?.abort(new ListError('stopped', 'phishing list refresh stopped'));
this.controller = null;
this.pending = null;
}
loadCache() {
try {
const stat = fs.statSync(this.cacheFile);
if (!stat.isFile() || stat.size > MAX_BYTES * 2) return;
const data = JSON.parse(fs.readFileSync(this.cacheFile, 'utf8'));
if (data?.version !== CACHE_VERSION || data.source !== PHISHING_LIST_URL || !Number.isFinite(data.fetchedAt)
|| !Array.isArray(data.domains) || data.domains.length > MAX_DOMAINS || !data.domains.every(validDomain)) return;
if (this.fetchedAt !== null && this.fetchedAt >= data.fetchedAt) return;
this.domains = new Set(data.domains);
this.fetchedAt = data.fetchedAt;
this.fromCache = true;
} catch {
// no cache yet, or unreadable: classification starts empty until the first fetch
}
}
/** Single-flight network refresh; never throws. Resolves to status(). */
refresh() {
if (!this.enabled) return Promise.resolve(this.status());
if (!this.pending) {
const pending = this.fetchOnce().finally(() => { if (this.pending === pending) this.pending = null; });
this.pending = pending;
}
return this.pending;
}
async fetchOnce() {
const generation = this.generation;
const stopped = () => generation !== this.generation;
const controller = new AbortController();
this.controller = controller;
const timer = setTimeout(() => controller.abort(new ListError('timeout', `phishing list: no answer in ${REQUEST_TIMEOUT_MS / 1000} s`)), REQUEST_TIMEOUT_MS);
timer.unref?.();
this.checkedAt = this.now();
try {
const res = await this.fetchImpl(PHISHING_LIST_URL, {
method: 'GET', signal: controller.signal, redirect: 'error', cache: 'no-store',
credentials: 'omit', referrerPolicy: 'no-referrer', headers: { Accept: 'text/plain' },
});
if (stopped()) return this.status();
// redirect:'error' already refuses redirects; a fetch implementation that followed one anyway is rejected.
if (res.redirected || (res.url && res.url !== PHISHING_LIST_URL)) throw new ListError('redirect', 'phishing list response did not come from the fixed endpoint');
if (!res.ok) throw new ListError('http', `phishing list: HTTP ${res.status}`);
const text = await readBounded(res, MAX_BYTES, controller.signal);
if (stopped()) return this.status();
const { domains } = parseList(text);
this.domains = domains;
this.fetchedAt = this.now();
this.fromCache = false;
this.error = null;
this.writeCache();
this.log('info', `phishing list: ${domains.size} domains`);
} catch (err) {
if (stopped()) return this.status();
const reason = controller.signal.aborted ? controller.signal.reason : null;
const code = err instanceof ListError ? err.code : reason instanceof ListError ? reason.code : 'network';
this.error = { code, message: String((reason instanceof ListError ? reason : err)?.message ?? err) };
this.log('warn', `phishing list: ${this.error.message} (keeping ${this.domains.size} known domains)`);
} finally {
clearTimeout(timer);
if (this.controller === controller) this.controller = null;
}
return this.status();
}
writeCache() {
try {
fs.mkdirSync(path.dirname(this.cacheFile), { recursive: true });
const tmp = `${this.cacheFile}.tmp`;
fs.writeFileSync(tmp, JSON.stringify({ version: CACHE_VERSION, source: PHISHING_LIST_URL, fetchedAt: this.fetchedAt, domains: [...this.domains] }));
fs.renameSync(tmp, this.cacheFile);
} catch (err) {
this.log('warn', `phishing list cache not written: ${err.message}`);
}
}
}
/** Renderer access: one exact-host lookup per external link, and the source state. */
function registerPhishingIpc({ ipcMain, trustedSender, list }) {
ipcMain.handle('privacy:link-threat', (event, host) => {
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
if (typeof host !== 'string' || host.length > 253) return { ok: false, error: { code: 'bad_request', message: 'Invalid host' } };
return { ok: true, malicious: list.has(host), loaded: list.status().loaded };
});
ipcMain.handle('privacy:threat-status', (event) => (trustedSender(event) ? { ok: true, status: list.status() } : { ok: false, error: { code: 'forbidden', message: 'forbidden' } }));
}
module.exports = { PhishingList, registerPhishingIpc, parseList, PHISHING_LIST_URL, FETCH_INTERVAL_MS, MAX_BYTES, MAX_DOMAINS };
+28 -9
View File
@@ -4,6 +4,10 @@ const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { USER_STYLE_PREF } = require('./themes'); const { USER_STYLE_PREF } = require('./themes');
const { VOICE_SCHEMA, migrateVoicePrefs } = require('./voice-prefs'); const { VOICE_SCHEMA, migrateVoicePrefs } = require('./voice-prefs');
const { PRIVACY_SCHEMA, migratePrivacyPrefs } = require('./privacy-prefs');
const { CHAT_SCHEMA } = require('./chat-prefs');
const { CONTACT_SCHEMA } = require('./contacts-prefs');
const bookmarks = require('../renderer/shared/bookmarks.js');
const LAYOUT_VERSION = 2; const LAYOUT_VERSION = 2;
/** /**
@@ -13,6 +17,7 @@ const LAYOUT_VERSION = 2;
const SCHEMA = { const SCHEMA = {
lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) }, lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) },
...VOICE_SCHEMA, ...VOICE_SCHEMA,
...PRIVACY_SCHEMA,
pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) }, pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) },
inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 }, inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 }, outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
@@ -42,13 +47,15 @@ const SCHEMA = {
updateChannel: { default: 'preview', check: (v) => v === 'preview' || v === 'stable' }, updateChannel: { default: 'preview', check: (v) => v === 'preview' || v === 'stable' },
// Interface language: English for new profiles (owner's request); a stored valid choice is kept. // Interface language: English for new profiles (owner's request); a stored valid choice is kept.
language: { default: 'en', check: (v) => v === 'en' || v === 'ru' }, language: { default: 'en', check: (v) => v === 'en' || v === 'ru' },
// Quick-access servers may select a local identity UID; passwords are never stored. // Quick-access servers may select a local identity UID and a containing folder; passwords are never stored.
savedServers: { default: [], check: validServers }, savedServers: { default: [], check: validServers },
// Chat (official settings.chat.*): formatting toolbar visibility, diagram auto-load, images, trusted link hosts. // Local bookmark folders (official Bookmarks "New Folder") and the shared display order of folders and
chatToolbarVisibility: { default: 'always-visible', check: (v) => v === 'inactive' || v === 'dynamic' || v === 'always-visible' }, // bookmarks. Cross-field rules (references, cycles, depth, order permutation) live in shared/bookmarks.js.
chatMermaidAutoload: { default: 'only-simple', check: (v) => v === 'never' || v === 'only-simple' }, bookmarkFolders: { default: [], check: bookmarks.validFolders },
autoDownloadImages: { default: false, check: (v) => typeof v === 'boolean' }, bookmarkOrder: { default: [], check: bookmarks.validOrder },
trustedExternalHosts: { default: [], check: (v) => Array.isArray(v) && v.length <= 500 && v.every((h) => typeof h === 'string' && h.length >= 1 && h.length <= 253 && /^[a-z0-9.-]+$/.test(h) && h === h.toLowerCase()) }, // Chat (official settings.chat.*): formatting toolbar visibility, diagram auto-load and images.
...CHAT_SCHEMA,
...CONTACT_SCHEMA,
// Official workflowSettings.autoEnableMicrophone (default off): focusing a server tab moves the microphone there. // Official workflowSettings.autoEnableMicrophone (default off): focusing a server tab moves the microphone there.
autoEnableMicrophone: { default: false, check: (v) => typeof v === 'boolean' }, autoEnableMicrophone: { default: false, check: (v) => typeof v === 'boolean' },
// Official workflowSettings.autoReactivateMicOnPreviousTarget (default on): when the microphone's connection // Official workflowSettings.autoReactivateMicOnPreviousTarget (default on): when the microphone's connection
@@ -63,6 +70,7 @@ const SCHEMA = {
// Per event: 0 off, 1 sound, 2 important (also while muted/away); logs are independent. // Per event: 0 off, 1 sound, 2 important (also while muted/away); logs are independent.
notificationStates: { default: {}, check: (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length <= 128 && Object.entries(v).every(([k, s]) => /^[a-z_]{1,96}$/.test(k) && (s === 0 || s === 1 || s === 2)) }, notificationStates: { default: {}, check: (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length <= 128 && Object.entries(v).every(([k, s]) => /^[a-z_]{1,96}$/.test(k) && (s === 0 || s === 1 || s === 2)) },
systemNotifyServerPrivate: { default: false, check: (v) => typeof v === 'boolean' }, systemNotifyServerPrivate: { default: false, check: (v) => typeof v === 'boolean' },
systemNotifyChannelChat: { default: false, check: (v) => typeof v === 'boolean' },
// OS integration (official settings.os.*). // OS integration (official settings.os.*).
osFlashOnMessage: { default: false, check: (v) => typeof v === 'boolean' }, osFlashOnMessage: { default: false, check: (v) => typeof v === 'boolean' },
osFlashOnPoke: { default: false, check: (v) => typeof v === 'boolean' }, osFlashOnPoke: { default: false, check: (v) => typeof v === 'boolean' },
@@ -72,17 +80,20 @@ const SCHEMA = {
const CONTROL = /[\u0000-\u001f\u007f]/; const CONTROL = /[\u0000-\u001f\u007f]/;
const BOOKMARK_KEYS = ['savedServers', 'bookmarkFolders', 'bookmarkOrder'];
function validServers(list) { function validServers(list) {
if (!Array.isArray(list) || list.length > 50) return false; if (!Array.isArray(list) || list.length > bookmarks.MAX_BOOKMARKS) return false;
const ids = new Set(); const ids = new Set();
for (const s of list) { for (const s of list) {
if (!s || typeof s !== 'object' || Array.isArray(s)) return false; if (!s || typeof s !== 'object' || Array.isArray(s)) return false;
const keys = Object.keys(s); const keys = Object.keys(s);
if (!keys.includes('id') || !keys.includes('name') || !keys.includes('address') || keys.some((key) => !['id', 'name', 'address', 'identity_id'].includes(key))) return false; if (!keys.includes('id') || !keys.includes('name') || !keys.includes('address') || keys.some((key) => !['id', 'name', 'address', 'identity_id', 'folder'].includes(key))) return false;
if (typeof s.id !== 'string' || !/^[a-z0-9]{6,32}$/.test(s.id) || ids.has(s.id)) return false; if (typeof s.id !== 'string' || !bookmarks.ID.test(s.id) || ids.has(s.id)) return false;
if (typeof s.name !== 'string' || s.name.trim().length < 1 || s.name.length > 64 || CONTROL.test(s.name)) return false; if (typeof s.name !== 'string' || s.name.trim().length < 1 || s.name.length > 64 || CONTROL.test(s.name)) return false;
if (typeof s.address !== 'string' || s.address.trim().length < 1 || s.address.length > 255 || CONTROL.test(s.address)) return false; if (typeof s.address !== 'string' || s.address.trim().length < 1 || s.address.length > 255 || CONTROL.test(s.address)) return false;
if (s.identity_id !== undefined && (typeof s.identity_id !== 'string' || !/^[A-Za-z0-9+/]{27}=$/.test(s.identity_id))) return false; if (s.identity_id !== undefined && (typeof s.identity_id !== 'string' || !/^[A-Za-z0-9+/]{27}=$/.test(s.identity_id))) return false;
if (s.folder !== undefined && (typeof s.folder !== 'string' || !bookmarks.ID.test(s.folder))) return false;
ids.add(s.id); ids.add(s.id);
} }
return true; return true;
@@ -118,6 +129,7 @@ class Prefs {
if (Object.prototype.hasOwnProperty.call(raw, key) && spec.check(raw[key])) this.values[key] = raw[key]; if (Object.prototype.hasOwnProperty.call(raw, key) && spec.check(raw[key])) this.values[key] = raw[key];
} }
migrateVoicePrefs(raw, this.values); migrateVoicePrefs(raw, this.values);
migratePrivacyPrefs(raw, this.values);
// Two-pane files predate serverPaneWidth. Three-pane saves always include that key, // Two-pane files predate serverPaneWidth. Three-pane saves always include that key,
// so preserve those even before the explicit version marker was introduced. // so preserve those even before the explicit version marker was introduced.
if (!Object.hasOwn(raw, 'layoutVersion') && !Object.hasOwn(raw, 'serverPaneWidth') && Object.hasOwn(raw, 'sidebarWidth') && SCHEMA.sidebarWidth.check(raw.sidebarWidth)) { if (!Object.hasOwn(raw, 'layoutVersion') && !Object.hasOwn(raw, 'serverPaneWidth') && Object.hasOwn(raw, 'sidebarWidth') && SCHEMA.sidebarWidth.check(raw.sidebarWidth)) {
@@ -128,6 +140,8 @@ class Prefs {
} catch { } catch {
// first run or unreadable file: defaults // first run or unreadable file: defaults
} }
// Each bookmark list was validated alone; references and order are repaired together without losing bookmarks.
Object.assign(this.values, bookmarks.normalize(this.values));
} }
get() { get() {
@@ -144,6 +158,11 @@ class Prefs {
if (!spec.check(value)) throw new Error(`prefs: invalid value for ${key}`); if (!spec.check(value)) throw new Error(`prefs: invalid value for ${key}`);
next[key] = value; next[key] = value;
} }
if (BOOKMARK_KEYS.some((key) => Object.hasOwn(partial, key))) {
// A write without an explicit order keeps the stored sequence: removed ids drop out, new ones go last.
if (!Object.hasOwn(partial, 'bookmarkOrder')) next.bookmarkOrder = bookmarks.completeOrder(next);
if (!bookmarks.consistent(next)) throw new Error('prefs: inconsistent bookmarks and folders');
}
// Persist first: if writing fails, neither the file nor the in-memory values change. // Persist first: if writing fails, neither the file nor the in-memory values change.
fs.mkdirSync(path.dirname(this.file), { recursive: true }); fs.mkdirSync(path.dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp`; const tmp = `${this.file}.tmp`;
+66
View File
@@ -0,0 +1,66 @@
'use strict';
/**
* Privacy preferences that follow the installed TS6 client's workflowSettings (client_ui/main.js, class Xe/Ge):
* - trustedExternalHosts: hosts the user chose to "Always trust" in the external-link warning.
* - allowWhitelistMalicious (default off): lets the warning offer "Always trust" for a host the phishing list
* flags. Off, a flagged host can still be opened after the warning but never becomes trusted.
* - confirmationSettings: one boolean per remembered confirmation (true = ask). A confirmation that offers
* "Don't ask again" stores false; Settings > Privacy > Reset Confirmations sets every key back to true.
*
* Myteamspeak chat settings (enableServerShare, enableTypingNotifications) and analytics are not stored:
* TeamsPeach has no chat-service presence or typing channel and sends no diagnostics.
*/
// Official class Ge defaults: every confirmation is shown until the user opts out.
const CONFIRMATION_KEYS = Object.freeze(['delete_ban', 'delete_temp_pw', 'delete_privilege_key', 'clear_file_transfer_history']);
const CONFIRMATION_DEFAULTS = Object.freeze(Object.fromEntries(CONFIRMATION_KEYS.map((key) => [key, true])));
const MAX_TRUSTED_HOSTS = 500;
const HOST = /^[a-z0-9.-]+$/;
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
function validTrustedHosts(v) {
return Array.isArray(v) && v.length <= MAX_TRUSTED_HOSTS
&& v.every((h) => typeof h === 'string' && h.length >= 1 && h.length <= 253 && HOST.test(h));
}
/** Exactly the known keys, each a boolean: the renderer always writes the complete object. */
function validConfirmationSettings(v) {
if (!isPlainObject(v)) return false;
const keys = Object.keys(v);
return keys.length === CONFIRMATION_KEYS.length && CONFIRMATION_KEYS.every((key) => typeof v[key] === 'boolean');
}
const PRIVACY_SCHEMA = {
trustedExternalHosts: { default: [], check: validTrustedHosts },
allowWhitelistMalicious: { default: false, check: (v) => typeof v === 'boolean' },
confirmationSettings: { default: { ...CONFIRMATION_DEFAULTS }, check: validConfirmationSettings },
};
/**
* Keeps the remembered choices of a stored confirmationSettings object that does not match the current key set
* (written by another version): known boolean keys are kept, missing keys default to "ask", unknown keys drop.
* Mirrors the official load merge `{...defaults, ...stored}`. `values` already holds validated keys/defaults.
*/
function migratePrivacyPrefs(raw, values) {
const stored = raw?.confirmationSettings;
if (!isPlainObject(stored) || validConfirmationSettings(stored)) return;
values.confirmationSettings = Object.fromEntries(CONFIRMATION_KEYS.map((key) => [key, typeof stored[key] === 'boolean' ? stored[key] : true]));
}
/**
* Main-side guard for a prefs update: a host the phishing list flags may only become newly trusted while
* allowWhitelistMalicious is (or becomes, in the same update) enabled. Hosts already trusted stay as they are,
* like the official client. Returns an error message or null.
*/
function trustedHostsUpdateError(current, partial, isMalicious) {
if (!partial || !Object.hasOwn(partial, 'trustedExternalHosts') || !Array.isArray(partial.trustedExternalHosts)) return null;
const allow = Object.hasOwn(partial, 'allowWhitelistMalicious') ? partial.allowWhitelistMalicious === true : current.allowWhitelistMalicious === true;
if (allow) return null;
const before = new Set(current.trustedExternalHosts ?? []);
const flagged = partial.trustedExternalHosts.find((host) => !before.has(host) && isMalicious(host));
return flagged ? `prefs: ${flagged} is flagged as malicious; enable "Allow trusting sites flagged as malicious" first` : null;
}
module.exports = { PRIVACY_SCHEMA, CONFIRMATION_KEYS, CONFIRMATION_DEFAULTS, migratePrivacyPrefs, trustedHostsUpdateError };
+182
View File
@@ -0,0 +1,182 @@
'use strict';
// Maps TeamsPeach core snapshots (docs/bridge.md §5 `snapshot`, `talking`, `audio_state`) to the Remote Apps
// message shapes. TeamSpeak's own documentation (installed docs/Remote Apps.md) only states that the auth reply
// carries "connected servers, clients and channels" and that events are `{type, payload}`; the field names used
// here are the ones the public consumer DerTyp7/react-teamspeak-remote-app-api (commit 5ea9cb9,
// src/interfaces/teamspeak.ts + src/handlers/teamspeak/messageHandler.ts) reads from the official client:
// auth.payload.connections[] {id, clientId, channelInfos:{rootChannels, subChannels}, clientInfos[]}
// clientMoved {connectionId, clientId, oldChannelId, newChannelId, properties}
// clientPropertiesUpdated {connectionId, clientId, properties}
// talkStatusChanged {connectionId, clientId, status}
// connectStatusChanged {connectionId, status (0 disconnected, 4 connected), info:{clientId}}
// channels {connectionId, info:{rootChannels, subChannels}}
// channelCreated {connectionId, channelId, parentId, properties}
// clientSelfPropertyUpdated {connectionId, flag:"inputHardware", oldValue, newValue}
// Only properties whose value the core actually reports are included; fields the consumer types but TeamsPeach
// cannot know (connection `properties`, clientMoved `type`/`visibility`, talkStatusChanged `isWhisper`,
// connectStatusChanged `error`, server-property events, channel edit/delete/move events) are omitted, not invented.
// TeamSpeak channel_codec values (TS3 protocol: 0 Speex NB, 1 Speex WB, 2 Speex UWB, 3 CELT mono, 4 Opus Voice,
// 5 Opus Music) for the core's codec names.
const CODEC = Object.freeze({ speex_narrowband: 0, speex_wideband: 1, speex_ultrawideband: 2, celt_mono: 3, opus_voice: 4, opus_music: 5 });
const CONNECT_STATUS = Object.freeze({ disconnected: 0, connected: 4 });
/** Core connection ids are `c<N>`; the remote protocol carries numeric connection ids. */
function connectionNumber(id) {
const match = typeof id === 'string' && /^c([1-9][0-9]{0,8})$/.exec(id);
return match ? Number(match[1]) : null;
}
const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
const isBool = (v) => typeof v === 'boolean';
function channelProperties(ch) {
const p = { name: String(ch.name ?? '') };
if (typeof ch.topic === 'string') p.topic = ch.topic;
if (isBool(ch.has_password)) p.flagPassword = ch.has_password;
if (isBool(ch.is_default)) p.flagDefault = ch.is_default;
// Core: max_clients null = unlimited.
p.flagMaxclientsUnlimited = ch.max_clients === null || ch.max_clients === undefined;
if (isNum(ch.max_clients)) p.maxclients = ch.max_clients;
if (isNum(ch.needed_talk_power)) p.neededTalkPower = ch.needed_talk_power;
if (Object.hasOwn(CODEC, ch.codec)) p.codec = CODEC[ch.codec];
if (isNum(ch.codec_quality)) p.codecQuality = ch.codec_quality;
// Core null = no icon; TeamSpeak uses 0 for "no icon".
p.iconId = isNum(ch.icon_id) ? ch.icon_id : 0;
if (typeof ch.banner_url === 'string') p.bannerGfxUrl = ch.banner_url;
if (isNum(ch.banner_mode)) p.bannerMode = ch.banner_mode;
if (isNum(ch.order)) p.order = String(ch.order);
return p;
}
function channelEntry(ch) {
return { id: ch.id, order: String(ch.order ?? 0), parentId: String(ch.parent_id ?? 0), properties: channelProperties(ch) };
}
/** consumer IChannelInfos: root channels plus children grouped by parent id. */
function channelInfos(channels) {
const rootChannels = [];
const subChannels = {};
for (const ch of channels) {
const entry = channelEntry(ch);
if (!ch.parent_id) rootChannels.push(entry);
else (subChannels[ch.parent_id] ??= []).push(entry);
}
return { rootChannels, subChannels };
}
function clientProperties(c) {
const p = { nickname: String(c.nickname ?? '') };
if (typeof c.uid === 'string') p.uniqueIdentifier = c.uid;
if (c.client_type === 'normal' || c.client_type === 'query') p.type = c.client_type === 'query' ? 1 : 0;
for (const [from, to] of [['input_muted', 'inputMuted'], ['output_muted', 'outputMuted'], ['input_hardware', 'inputHardware'],
['output_hardware', 'outputHardware'], ['away', 'away'], ['is_talker', 'isTalker'], ['is_channel_commander', 'isChannelCommander'],
['is_priority_speaker', 'isPrioritySpeaker'], ['is_recording', 'isRecording']]) {
if (isBool(c[from])) p[to] = c[from];
}
// The core turns TeamSpeak's empty strings into null; the wire value of "unset" is the empty string.
p.awayMessage = typeof c.away_message === 'string' ? c.away_message : '';
p.description = typeof c.description === 'string' ? c.description : '';
p.country = typeof c.country === 'string' ? c.country : '';
p.badges = typeof c.badges === 'string' ? c.badges : '';
if (isNum(c.talk_power)) p.talkPower = c.talk_power;
if (c.talk_request !== undefined) {
p.talkRequest = c.talk_request ? 1 : 0;
p.talkRequestMsg = typeof c.talk_request?.message === 'string' ? c.talk_request.message : '';
}
if (Array.isArray(c.server_groups)) p.serverGroups = c.server_groups.join(',');
if (isNum(c.channel_group_id)) p.channelGroupId = String(c.channel_group_id);
if (isNum(c.channel_group_inherited_from)) p.channelGroupInheritedChannelId = String(c.channel_group_inherited_from);
p.iconId = isNum(c.icon_id) ? c.icon_id : 0;
return p;
}
/** Validated, indexed view of one core snapshot, or null when it does not describe a live server view. */
function indexSnapshot(snapshot) {
if (!snapshot || typeof snapshot !== 'object' || !isNum(snapshot.own_client_id)) return null;
const channels = Array.isArray(snapshot.channels) ? snapshot.channels.filter((ch) => ch && isNum(ch.id)) : [];
const clients = Array.isArray(snapshot.clients) ? snapshot.clients.filter((c) => c && isNum(c.id) && isNum(c.channel_id)) : [];
return {
own: snapshot.own_client_id,
channelList: channels,
channels: new Map(channels.map((ch) => [ch.id, ch])),
clients: new Map(clients.map((c) => [c.id, { channelId: c.channel_id, raw: c, properties: clientProperties(c) }])),
};
}
/** consumer IConnection for the auth reply. */
function connectionEntry(connectionId, view) {
return {
id: connectionId,
clientId: view.own,
channelInfos: channelInfos(view.channelList),
clientInfos: Array.from(view.clients, ([id, c]) => ({ id, channelId: c.channelId, properties: c.properties })),
};
}
/** All live connections in creation order; `views` maps core id → indexed snapshot. */
function authConnections(views) {
const out = [];
for (const [id, view] of views) {
const number = connectionNumber(id);
if (number !== null && view) out.push(connectionEntry(number, view));
}
return out.sort((a, b) => a.id - b.id);
}
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
/** Events turning `prev` into `next` for one connection (either may be null). */
function diffEvents(connectionId, prev, next) {
const events = [];
if (!prev && !next) return events;
if (prev && !next) {
events.push({ type: 'connectStatusChanged', payload: { connectionId, status: CONNECT_STATUS.disconnected, info: { clientId: prev.own } } });
return events;
}
if (!prev || prev.own !== next.own) {
if (prev) events.push({ type: 'connectStatusChanged', payload: { connectionId, status: CONNECT_STATUS.disconnected, info: { clientId: prev.own } } });
// Consumer sequence on connect: connection, then its channels, then every visible client as a join.
events.push({ type: 'connectStatusChanged', payload: { connectionId, status: CONNECT_STATUS.connected, info: { clientId: next.own } } });
events.push({ type: 'channels', payload: { connectionId, info: channelInfos(next.channelList) } });
for (const [clientId, c] of next.clients) {
events.push({ type: 'clientMoved', payload: { connectionId, clientId, oldChannelId: 0, newChannelId: c.channelId, properties: c.properties } });
}
return events;
}
for (const ch of next.channelList) {
if (!prev.channels.has(ch.id)) {
events.push({ type: 'channelCreated', payload: { connectionId, channelId: ch.id, parentId: String(ch.parent_id ?? 0), properties: channelProperties(ch) } });
}
}
for (const [clientId, c] of next.clients) {
const before = prev.clients.get(clientId);
if (!before) {
events.push({ type: 'clientMoved', payload: { connectionId, clientId, oldChannelId: 0, newChannelId: c.channelId, properties: c.properties } });
continue;
}
if (before.channelId !== c.channelId) {
events.push({ type: 'clientMoved', payload: { connectionId, clientId, oldChannelId: before.channelId, newChannelId: c.channelId, properties: c.properties } });
}
if (!same(before.properties, c.properties)) {
events.push({ type: 'clientPropertiesUpdated', payload: { connectionId, clientId, properties: c.properties } });
}
if (clientId === next.own && isBool(before.raw.input_hardware) && isBool(c.raw.input_hardware) && before.raw.input_hardware !== c.raw.input_hardware) {
events.push({ type: 'clientSelfPropertyUpdated', payload: { connectionId, flag: 'inputHardware', oldValue: before.raw.input_hardware, newValue: c.raw.input_hardware } });
}
}
for (const [clientId, before] of prev.clients) {
if (!next.clients.has(clientId)) {
events.push({ type: 'clientMoved', payload: { connectionId, clientId, oldChannelId: before.channelId, newChannelId: 0, properties: before.properties } });
}
}
return events;
}
/** TS3 SDK talk status: 0 not talking, 1 talking. */
function talkEvent(connectionId, clientId, talking) {
return { type: 'talkStatusChanged', payload: { connectionId, clientId, status: talking ? 1 : 0 } };
}
module.exports = { connectionNumber, indexSnapshot, authConnections, diffEvents, talkEvent, channelInfos, clientProperties, channelProperties, CODEC };
+192
View File
@@ -0,0 +1,192 @@
'use strict';
// Persistent Remote Apps configuration (official config blob `remoteApps`, installed client main.js@1292478:
// {enabled:true, port:5899, allowLanAccess:false, apps:{}}) plus the per-app authorization the original keeps
// natively. Only a SHA-256 verifier of each issued API key is stored; the key itself exists only in the reply
// sent to the approved application. Nothing in this file is ever sent to the renderer.
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const FILE_VERSION = 1;
const DEFAULT_PORT = 5899;
// Official TSInputNumber#websocket-port bounds (render@4957240: minimum 1025, maximum 65535).
const PORT_MIN = 1025;
const PORT_MAX = 65535;
const MAX_APPS = 128;
// docs/Remote Apps.md: "Only letters a-z and the dot are valid in the identifier."
const IDENTIFIER = /^[a-z.]{1,128}$/;
const CONTROL = /[\u0000-\u001f\u007f]/;
const LIMITS = Object.freeze({ name: 128, version: 64, description: 1024, apiKey: 256, origin: 256 });
const validPort = (v) => Number.isInteger(v) && v >= PORT_MIN && v <= PORT_MAX;
const validIdentifier = (v) => typeof v === 'string' && IDENTIFIER.test(v);
const validText = (v, max, { allowEmpty = true } = {}) => typeof v === 'string' && v.length <= max && (allowEmpty || v.length > 0) && !CONTROL.test(v);
const validHash = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
function hashKey(key) {
return crypto.createHash('sha256').update(key, 'utf8').digest('hex');
}
/** Metadata an application announces in its auth payload; returns null when any field is invalid. */
function cleanMetadata(payload) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
const { identifier, name, version, description } = payload;
if (!validIdentifier(identifier)) return null;
if (!validText(name, LIMITS.name, { allowEmpty: false }) || name.trim() === '') return null;
if (!validText(version, LIMITS.version) || !validText(description, LIMITS.description)) return null;
return { identifier, name, version, description };
}
/** null = a native client (no Origin header); a string = the exact browser Origin the app was approved for. */
const validOrigin = (v) => v === null || validText(v, LIMITS.origin, { allowEmpty: false });
function validApp(identifier, app) {
return app && typeof app === 'object' && app.identifier === identifier && cleanMetadata(app)
&& typeof app.allowed === 'boolean' && (app.keyHash === null || validHash(app.keyHash))
&& (app.origin === undefined || validOrigin(app.origin));
}
class RemoteAppStore {
constructor(file) {
this.file = file;
this.enabled = true;
this.port = DEFAULT_PORT;
this.apps = new Map();
this.loadError = null;
let raw;
try {
raw = fs.readFileSync(file, 'utf8');
} catch (err) {
if (err.code !== 'ENOENT') this.loadError = err.code ?? 'read_failed';
return;
}
let data;
try {
data = JSON.parse(raw);
} catch {
data = null;
}
if (!data || typeof data !== 'object' || data.version !== FILE_VERSION) {
// Fail closed: an unreadable file never grants anything; keep it aside instead of overwriting it.
this.loadError = 'corrupt';
try { fs.renameSync(file, `${file}.corrupt`); } catch { /* best effort */ }
return;
}
if (typeof data.enabled === 'boolean') this.enabled = data.enabled;
if (validPort(data.port)) this.port = data.port;
if (data.apps && typeof data.apps === 'object' && !Array.isArray(data.apps)) {
for (const [identifier, app] of Object.entries(data.apps).slice(0, MAX_APPS)) {
if (!validApp(identifier, app)) continue;
// Records written before origin binding were approved for native clients; they never trust a web page.
this.apps.set(identifier, { identifier, name: app.name, version: app.version, description: app.description, allowed: app.allowed, keyHash: app.keyHash, origin: app.origin ?? null });
}
}
}
/** Atomic owner-only write; on failure neither the file nor memory changes (callers pass the next state). */
write(next) {
const apps = {};
for (const [identifier, app] of next.apps) apps[identifier] = { ...app };
const body = JSON.stringify({ version: FILE_VERSION, enabled: next.enabled, port: next.port, allowLanAccess: false, apps }, null, 2);
fs.mkdirSync(path.dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp`;
fs.writeFileSync(tmp, body, { mode: 0o600 });
fs.renameSync(tmp, this.file);
this.enabled = next.enabled;
this.port = next.port;
this.apps = next.apps;
}
snapshotState() {
return { enabled: this.enabled, port: this.port, apps: new Map(Array.from(this.apps, ([k, v]) => [k, { ...v }])) };
}
setEnabled(enabled) {
if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean');
this.write({ ...this.snapshotState(), enabled });
}
setPort(port) {
if (!validPort(port)) throw new RangeError(`port must be an integer ${PORT_MIN}-${PORT_MAX}`);
this.write({ ...this.snapshotState(), port });
}
app(identifier) {
const app = this.apps.get(identifier);
return app ? { ...app } : null;
}
/** Public view without verifiers. */
list() {
return Array.from(this.apps.values(), ({ identifier, name, version, description, allowed, origin }) => ({ identifier, name, version, description, allowed, origin }));
}
/**
* Constant-time comparison of SHA-256 digests. The key is valid only from the exact origin it was issued to
* (null = native); a missing verifier, malformed key or other origin never matches.
*/
verifyKey(identifier, apiKey, origin) {
const app = this.apps.get(identifier);
if (!app || !app.allowed || !app.keyHash || !validText(apiKey, LIMITS.apiKey, { allowEmpty: false }) || !validOrigin(origin)) return false;
const match = crypto.timingSafeEqual(Buffer.from(hashKey(apiKey), 'hex'), Buffer.from(app.keyHash, 'hex'));
return match && app.origin === origin;
}
/** User approved `metadata` from `origin`: issues a fresh crypto-random key bound to that origin, revoking any earlier one. */
approve(metadata, origin) {
const meta = cleanMetadata(metadata);
if (!meta) throw new TypeError('invalid application metadata');
if (!validOrigin(origin)) throw new TypeError('invalid origin');
const next = this.snapshotState();
if (!next.apps.has(meta.identifier) && next.apps.size >= MAX_APPS) throw new RangeError('too many registered applications');
const apiKey = crypto.randomUUID();
next.apps.set(meta.identifier, { ...meta, allowed: true, keyHash: hashKey(apiKey), origin });
this.write(next);
return apiKey;
}
/** User denied `metadata`: the app is listed as not allowed and any earlier key is discarded. */
deny(metadata, origin) {
const meta = cleanMetadata(metadata);
if (!meta) throw new TypeError('invalid application metadata');
if (!validOrigin(origin)) throw new TypeError('invalid origin');
const next = this.snapshotState();
if (!next.apps.has(meta.identifier) && next.apps.size >= MAX_APPS) throw new RangeError('too many registered applications');
next.apps.set(meta.identifier, { ...meta, allowed: false, keyHash: null, origin });
this.write(next);
}
/** Metadata refresh after a successful key authentication (the key holder may update name/version/description). */
updateMetadata(metadata) {
const meta = cleanMetadata(metadata);
const app = meta && this.apps.get(meta.identifier);
if (!app || (app.name === meta.name && app.version === meta.version && app.description === meta.description)) return;
const next = this.snapshotState();
next.apps.set(meta.identifier, { ...app, ...meta });
this.write(next);
}
setAllowed(identifier, allowed) {
if (typeof allowed !== 'boolean') throw new TypeError('allowed must be a boolean');
const app = this.apps.get(identifier);
if (!app) return false;
const next = this.snapshotState();
next.apps.set(identifier, { ...app, allowed });
this.write(next);
return true;
}
remove(identifier) {
if (!this.apps.has(identifier)) return false;
const next = this.snapshotState();
next.apps.delete(identifier);
this.write(next);
return true;
}
}
module.exports = {
RemoteAppStore, cleanMetadata, validIdentifier, validPort, validText, validOrigin, hashKey,
DEFAULT_PORT, PORT_MIN, PORT_MAX, LIMITS,
};
+663
View File
@@ -0,0 +1,663 @@
'use strict';
// Remote Apps: the TeamSpeak WebSocket API (installed docs/Remote Apps.md) on loopback port 5899 by default.
// Applications authenticate with {type:"auth", payload:{identifier, version, name, description, content:{apiKey}}};
// an unknown application (or one presenting an empty key) waits for an explicit user decision in Settings →
// Remote Apps, then receives {type:"auth", payload:{apiKey, connections}, status:{code:0, message:"ok"}}.
// Approved applications may send {type:"keyPress", payload:{button, state}}; only state transitions of approved,
// authenticated sockets are reported through `onKey`, and every held button is released when a socket closes or
// its app is revoked, removed or the server stops. Server/channel/client data is never sent before authentication.
// Every key is bound to the exact Origin header of the approved request (none = native program): a browser page
// can never use a native app's key or another page's key, and moving an app to another origin needs a new
// explicit approval. Requests expire after pendingTimeoutMs; web origins have socket/request quotas.
//
// Wire behaviour NOT verified against the original native implementation (no captured exchange exists):
// rejection signalling (here: WebSocket close 1008 with a reason code, no auth reply), whether the original
// re-issues/rotates keys, pre-auth message handling, and limits. See remote-app-snapshot.js for event fields.
const crypto = require('node:crypto');
const { WebSocketServer, WebSocket } = require('ws');
const { RemoteAppStore, cleanMetadata, validIdentifier, validPort, validText, validOrigin, LIMITS: TEXT_LIMITS } = require('./remote-app-state');
const snapshot = require('./remote-app-snapshot');
const DEFAULT_LIMITS = Object.freeze({
// All sockets / all permission requests. Native clients (no Origin header) share these bounds; browser pages
// additionally have per-origin and all-web quotas so web pages can never take every slot from native apps.
maxSockets: 16,
maxPending: 8,
maxWebSockets: 8,
maxWebPending: 4,
maxSocketsPerWebOrigin: 4,
maxPendingPerWebOrigin: 2,
maxPayload: 16 * 1024,
authTimeoutMs: 10_000,
// A permission request the user does not answer expires; the application may ask again later.
pendingTimeoutMs: 120_000,
// Token bucket per socket: sustained messages per second and burst size.
messagesPerSecond: 50,
messageBurst: 100,
maxBufferedBytes: 1024 * 1024,
maxHeldKeys: 64,
buttonLength: 128,
});
// IPv4 and IPv6 loopback; "LAN access" is disabled in the original ("Coming Soon") and not offered here.
const HOSTS = Object.freeze([
{ host: '127.0.0.1', required: true },
{ host: '::1', required: false },
]);
// Address families that may simply not exist on this machine (IPv6 disabled).
const OPTIONAL_BIND_ERRORS = new Set(['EADDRNOTAVAIL', 'EAFNOSUPPORT', 'EINVAL', 'ENOTFOUND']);
const CLOSE = Object.freeze({ normal: 1000, away: 1001, unsupported: 1003, policy: 1008, internal: 1011, overload: 1013 });
function isLoopback(address) {
return typeof address === 'string' && (address === '::1' || /^127\./.test(address) || /^::ffff:127\./i.test(address));
}
function listenOn(WebSocketServerImpl, options) {
return new Promise((resolve) => {
let wss;
try {
wss = new WebSocketServerImpl(options);
} catch (error) {
resolve({ error });
return;
}
const onError = (error) => {
wss.removeListener('listening', onListening);
try { wss.close(); } catch { /* already closed */ }
resolve({ error });
};
const onListening = () => {
wss.removeListener('error', onError);
resolve({ server: wss });
};
wss.once('error', onError);
wss.once('listening', onListening);
});
}
/**
* Browser pages always send Origin with a WebSocket upgrade; native programs normally do not.
* Returns null for no header (native), the exact header string, or undefined when the header is malformed.
*/
function originOf(req) {
const origin = req?.headers?.origin;
if (origin === undefined) return null;
return validOrigin(origin) ? origin : undefined;
}
class RemoteAppsService {
/**
* @param {object} options
* @param {RemoteAppStore} options.store
* @param {boolean} options.listen false (offscreen tests without an explicit disposable flag) never binds a port
* @param {(key:{identifier:string,button:string,state:boolean,synthetic?:true})=>void} [options.onKey] synthetic = safety release
* @param {(status:object)=>void} [options.onStatus]
*/
constructor({ store, listen, onKey = () => {}, onStatus = () => {}, log = () => {}, limits = {}, WebSocketServerImpl = WebSocketServer, now = Date.now }) {
this.store = store;
this.listen = listen === true;
this.onKey = onKey;
this.onStatus = onStatus;
this.log = log;
this.limits = { ...DEFAULT_LIMITS, ...limits };
this.WebSocketServerImpl = WebSocketServerImpl;
this.now = now;
this.servers = [];
this.listening = false;
this.failure = this.listen ? null : 'test_safety';
this.clients = new Set();
this.pending = new Map();
// `${identifier}\0${button}` → sockets holding it; a transition is reported when the set becomes (non-)empty.
this.holders = new Map();
this.views = new Map();
this.transmitting = new Map();
this.queue = Promise.resolve();
this.disposed = false;
}
// ---------- lifecycle ----------
serialize(task) {
const run = this.queue.then(task, task);
this.queue = run.catch(() => {});
return run;
}
start() {
return this.serialize(() => this.startNow());
}
stop() {
return this.serialize(() => this.stopNow(CLOSE.away, 'stopped'));
}
dispose() {
this.disposed = true;
return this.stop();
}
async startNow() {
if (this.disposed || !this.listen || !this.store.enabled || this.servers.length > 0) {
this.emitStatus();
return;
}
const port = this.store.port;
const servers = [];
let failure = null;
for (const { host, required } of HOSTS) {
const result = await listenOn(this.WebSocketServerImpl, {
host, port, maxPayload: this.limits.maxPayload, perMessageDeflate: false, clientTracking: false,
verifyClient: (info, done) => this.verifyClient(info, done),
});
if (result.server) {
servers.push(result.server);
continue;
}
const code = result.error?.code;
if (!required && OPTIONAL_BIND_ERRORS.has(code)) continue;
failure = code === 'EADDRINUSE' || code === 'EACCES' ? 'address_in_use' : 'listen_failed';
this.log('warn', `remote apps: cannot listen on ${host}:${port}: ${code ?? result.error?.message}`);
break;
}
if (failure || this.disposed || !this.store.enabled || this.store.port !== port) {
await Promise.all(servers.map((s) => new Promise((resolve) => s.close(() => resolve()))));
this.failure = failure;
this.listening = false;
this.emitStatus();
return;
}
for (const server of servers) {
server.on('error', (error) => this.log('warn', `remote apps: server error: ${error.code ?? error.message}`));
server.on('connection', (ws, req) => this.accept(ws, req));
}
this.servers = servers;
this.listening = true;
this.failure = null;
this.emitStatus();
}
async stopNow(code, reason) {
for (const client of Array.from(this.clients)) this.closeClient(client, code, reason);
const servers = this.servers;
this.servers = [];
this.listening = false;
await Promise.all(servers.map((s) => new Promise((resolve) => s.close(() => resolve()))));
if (this.listen) this.failure = null;
this.emitStatus();
}
// ---------- settings (user actions from the trusted renderer) ----------
setEnabled(enabled) {
return this.serialize(async () => {
this.store.setEnabled(enabled);
if (enabled) await this.startNow();
else await this.stopNow(CLOSE.away, 'disabled');
return this.status();
});
}
setPort(port) {
return this.serialize(async () => {
if (port === this.store.port && (this.listening || !this.store.enabled)) return this.status();
this.store.setPort(port);
await this.stopNow(CLOSE.away, 'port_changed');
await this.startNow();
return this.status();
});
}
/** The user's decision on one pending request (bound to its socket and the metadata shown). */
respond(requestId, allow) {
const request = this.pending.get(requestId);
if (!request) return { ok: false, error: { code: 'not_found', message: 'The permission request is no longer pending' } };
// Persist first: if writing fails the request stays pending and the socket keeps waiting. The key is bound to
// the origin the user saw in the request (re-authorization from another origin rebinds it).
const apiKey = allow ? this.store.approve(request.meta, request.origin) : null;
if (!allow) this.store.deny(request.meta, request.origin);
this.pending.delete(requestId);
request.client.pendingId = null;
if (allow) {
// Earlier sockets of a re-authorized app hold the revoked key; they must not keep sending input.
for (const other of Array.from(this.clients)) {
if (other !== request.client && other.identifier === request.meta.identifier) this.closeClient(other, CLOSE.policy, 'key_revoked');
}
this.authenticate(request.client, request.meta.identifier, apiKey);
} else {
this.rejectIdentifier(request.meta.identifier, 'denied');
this.closeClient(request.client, CLOSE.policy, 'denied');
}
this.emitStatus();
return { ok: true };
}
/** Apps list toggle (official wssSetApp Allow/Deny): disallowing closes the app's sockets and releases its keys. */
setAllowed(identifier, allowed) {
if (!this.store.setAllowed(identifier, allowed)) return { ok: false, error: { code: 'not_found', message: 'The application is not registered' } };
if (!allowed) this.rejectIdentifier(identifier, 'denied');
this.emitStatus();
return { ok: true };
}
/** "Remove App" (official wssSetApp Remove): forgets the app and its key; open sockets are closed. */
removeApp(identifier) {
if (!this.store.remove(identifier)) return { ok: false, error: { code: 'not_found', message: 'The application is not registered' } };
this.rejectIdentifier(identifier, 'removed');
this.emitStatus();
return { ok: true };
}
rejectIdentifier(identifier, reason) {
for (const client of Array.from(this.clients)) {
if (client.identifier === identifier || (client.pendingId && this.pending.get(client.pendingId)?.meta.identifier === identifier)) {
this.closeClient(client, CLOSE.policy, reason);
}
}
}
// ---------- status (no keys, no verifiers) ----------
status() {
const connected = new Set();
for (const client of this.clients) if (client.state === 'authed') connected.add(client.identifier);
return {
available: this.listen,
enabled: this.store.enabled,
port: this.store.port,
allowLanAccess: false,
listening: this.listening,
failure: this.failure,
requests: Array.from(this.pending.values(), ({ id, meta, origin, reauth }) => ({ id, ...meta, origin, reauth })),
apps: this.store.list().map((app) => ({ ...app, connected: connected.has(app.identifier) })),
};
}
emitStatus() {
try {
this.onStatus(this.status());
} catch (error) {
this.log('warn', `remote apps: status listener failed: ${error.message}`);
}
}
// ---------- sockets ----------
/** Sockets and pending requests sharing `origin` (null = native) and, for web pages, all web pages together. */
usage(origin) {
const usage = { sockets: 0, pending: 0, webSockets: 0, webPending: 0 };
for (const client of this.clients) {
const pending = client.state === 'pending' ? 1 : 0;
if (client.origin === origin) {
usage.sockets += 1;
usage.pending += pending;
}
if (client.origin !== null) {
usage.webSockets += 1;
usage.webPending += pending;
}
}
return usage;
}
/** Why a new socket from `origin` may not be accepted now, or null. */
socketRefusal(origin) {
if (origin === undefined) return 'invalid_origin';
if (this.clients.size >= this.limits.maxSockets) return 'too_many_sockets';
if (origin === null) return null;
const usage = this.usage(origin);
if (usage.sockets >= this.limits.maxSocketsPerWebOrigin || usage.webSockets >= this.limits.maxWebSockets) return 'too_many_sockets';
return null;
}
verifyClient(info, done) {
if (!this.listening || !isLoopback(info.req?.socket?.remoteAddress)) return done(false, 403, 'Forbidden');
const refusal = this.socketRefusal(originOf(info.req));
if (refusal === 'invalid_origin') return done(false, 400, 'Invalid Origin');
if (refusal) return done(false, 503, 'Too many remote applications');
return done(true);
}
accept(ws, req) {
const origin = originOf(req);
if (!this.listening || !isLoopback(req?.socket?.remoteAddress) || this.socketRefusal(origin)) {
ws.terminate();
return;
}
const client = {
ws, state: 'new', identifier: null, pendingId: null, held: new Set(), origin,
tokens: this.limits.messageBurst, refilled: this.now(), timer: null,
};
this.clients.add(client);
client.timer = setTimeout(() => this.closeClient(client, CLOSE.policy, 'auth_timeout'), this.limits.authTimeoutMs);
ws.on('message', (data, isBinary) => {
// Nothing a remote application sends may take down the main process.
try {
this.onMessage(client, data, isBinary);
} catch (error) {
this.log('warn', `remote apps: message handling failed: ${error?.code ?? error?.name ?? 'error'}`);
this.closeClient(client, CLOSE.internal, 'internal_error');
}
});
ws.on('close', () => this.cleanup(client));
// maxPayload violations and protocol errors surface here; ws closes the socket itself.
ws.on('error', () => this.cleanup(client));
}
allowMessage(client) {
const now = this.now();
client.tokens = Math.min(this.limits.messageBurst, client.tokens + ((now - client.refilled) / 1000) * this.limits.messagesPerSecond);
client.refilled = now;
if (client.tokens < 1) return false;
client.tokens -= 1;
return true;
}
onMessage(client, data, isBinary) {
if (client.state === 'closed') return;
if (!this.allowMessage(client)) {
this.closeClient(client, CLOSE.policy, 'rate_limited');
return;
}
if (isBinary) {
this.closeClient(client, CLOSE.unsupported, 'binary_unsupported');
return;
}
let message;
try {
message = JSON.parse(data.toString('utf8'));
} catch {
message = null;
}
if (!message || typeof message !== 'object' || typeof message.type !== 'string') {
this.closeClient(client, CLOSE.policy, 'invalid_message');
return;
}
if (client.state === 'new') {
if (message.type !== 'auth') {
this.closeClient(client, CLOSE.policy, 'auth_required');
return;
}
this.onAuth(client, message.payload);
return;
}
// Pending sockets wait for the user; nothing they send has any effect until approval.
if (client.state !== 'authed') return;
if (message.type === 'keyPress') this.onKeyPress(client, message.payload);
}
onAuth(client, payload) {
const meta = cleanMetadata(payload);
const apiKey = payload?.content?.apiKey ?? '';
if (!meta || !validText(apiKey, TEXT_LIMITS.apiKey)) {
this.closeClient(client, CLOSE.policy, 'invalid_auth');
return;
}
const app = this.store.app(meta.identifier);
if (app && !app.allowed) {
this.closeClient(client, CLOSE.policy, 'denied');
return;
}
if (apiKey !== '') {
// A non-empty key must match exactly and come from the origin it was issued to (null = native); a wrong key
// or origin never turns into a permission request.
if (!this.store.verifyKey(meta.identifier, apiKey, client.origin)) {
this.closeClient(client, CLOSE.policy, 'invalid_api_key');
return;
}
try {
this.store.updateMetadata(meta);
} catch (error) {
// Metadata is informational; the verified key still authenticates with the stored record.
this.log('warn', `remote apps: application details not saved: ${error?.code ?? error?.name ?? 'error'}`);
}
this.authenticate(client, meta.identifier, apiKey);
this.emitStatus();
return;
}
// Empty key: a new app, or a registered app that lost its key, asks the user. One request per identifier;
// a concurrent request can neither replace the metadata the user is looking at nor queue behind it.
for (const request of this.pending.values()) {
if (request.meta.identifier === meta.identifier) {
this.closeClient(client, CLOSE.overload, 'auth_pending');
return;
}
}
const usage = this.usage(client.origin);
if (this.pending.size >= this.limits.maxPending || (client.origin !== null
&& (usage.pending >= this.limits.maxPendingPerWebOrigin || usage.webPending >= this.limits.maxWebPending))) {
this.closeClient(client, CLOSE.overload, 'too_many_requests');
return;
}
const id = crypto.randomUUID();
this.pending.set(id, { id, meta, origin: client.origin, reauth: Boolean(app), client });
client.pendingId = id;
client.state = 'pending';
clearTimeout(client.timer);
// An unanswered request expires (its notice disappears with the next status); the app may ask again.
client.timer = setTimeout(() => this.closeClient(client, CLOSE.policy, 'auth_expired'), this.limits.pendingTimeoutMs);
this.emitStatus();
}
authenticate(client, identifier, apiKey) {
if (client.state === 'closed') return;
clearTimeout(client.timer);
client.timer = null;
client.state = 'authed';
client.identifier = identifier;
this.send(client, { type: 'auth', payload: { apiKey, connections: snapshot.authConnections(this.views) }, status: { code: 0, message: 'ok' } });
}
onKeyPress(client, payload) {
const button = payload?.button;
const state = payload?.state;
if (typeof state !== 'boolean' || !validText(button, this.limits.buttonLength, { allowEmpty: false })) return;
// Revocation and rebinding are synchronous in the store; never trust a socket whose app is no longer allowed
// or whose key now belongs to another origin.
const app = this.store.app(client.identifier);
if (!app?.allowed || app.origin !== client.origin) {
this.closeClient(client, CLOSE.policy, 'denied');
return;
}
if (state) {
if (client.held.has(button) || client.held.size >= this.limits.maxHeldKeys) return;
client.held.add(button);
this.hold(client, button);
} else {
if (!client.held.delete(button)) return;
this.unhold(client, button);
}
}
hold(client, button) {
const key = `${client.identifier}\0${button}`;
let set = this.holders.get(key);
if (!set) this.holders.set(key, (set = new Set()));
set.add(client);
if (set.size === 1) this.emitKey({ identifier: client.identifier, button, state: true });
}
/** `synthetic`: released by close/revoke/remove/disable/restart, not by the app; bound actions must not fire. */
unhold(client, button, synthetic = false) {
const key = `${client.identifier}\0${button}`;
const set = this.holders.get(key);
if (!set || !set.delete(client)) return;
if (set.size > 0) return;
this.holders.delete(key);
this.emitKey(synthetic ? { identifier: client.identifier, button, state: false, synthetic: true } : { identifier: client.identifier, button, state: false });
}
emitKey(key) {
try {
this.onKey(key);
} catch (error) {
this.log('warn', `remote apps: key listener failed: ${error.message}`);
}
}
send(client, message) {
const { ws } = client;
if (client.state === 'closed' || ws.readyState !== WebSocket.OPEN) return;
// A reader that does not keep up is disconnected instead of buffering without bound.
if (ws.bufferedAmount > this.limits.maxBufferedBytes) {
this.closeClient(client, CLOSE.overload, 'backpressure');
ws.terminate();
return;
}
ws.send(JSON.stringify(message));
}
closeClient(client, code, reason) {
if (client.state === 'closed') return;
this.cleanup(client);
const { ws } = client;
// A peer that never answers the closing handshake must not hold the socket (or a port restart) open.
const kill = setTimeout(() => ws.terminate(), 2000);
kill.unref?.();
ws.once('close', () => clearTimeout(kill));
try {
ws.close(code, reason);
} catch {
ws.terminate();
}
}
/** Idempotent: releases held keys, drops a pending request, forgets the socket. */
cleanup(client) {
if (client.state === 'closed') return;
const hadPending = client.pendingId !== null;
const wasAuthed = client.state === 'authed';
client.state = 'closed';
clearTimeout(client.timer);
client.timer = null;
for (const button of Array.from(client.held)) {
client.held.delete(button);
this.unhold(client, button, true);
}
if (hadPending) this.pending.delete(client.pendingId);
client.pendingId = null;
this.clients.delete(client);
if (hadPending || wasAuthed) this.emitStatus();
}
// ---------- server view (core events from main.js) ----------
/** Core event of one server connection (docs/bridge.md §5). */
handleCoreEvent(connectionId, evt) {
if (!evt || typeof evt !== 'object') return;
if (evt.event === 'snapshot') this.updateSnapshot(connectionId, evt);
else if (evt.event === 'state' && evt.state !== 'connected') this.updateSnapshot(connectionId, null);
else if (evt.event === 'talking') this.updateTalking(connectionId, evt.client_id, evt.talking);
else if (evt.event === 'audio_state') this.updateTransmitting(connectionId, evt.transmitting);
}
/** Core process status (connections 'status'): anything but `ready` (exit, restart) ends the server view. */
handleCoreStatus(connectionId, status) {
if (status?.status !== 'ready') this.updateSnapshot(connectionId, null);
}
/** connections 'changed' list: closed tabs and tabs no longer connected lose their cached view. */
updateConnectionList(list) {
const live = new Map(Array.isArray(list) ? list.filter((e) => e && typeof e.id === 'string').map((e) => [e.id, e.state]) : []);
for (const id of Array.from(this.views.keys())) {
if (live.get(id) !== 'connected') this.updateSnapshot(id, null);
}
}
/** Replaces the cached view of one connection (null = gone) and publishes the difference to authenticated apps. */
updateSnapshot(connectionId, data) {
const number = snapshot.connectionNumber(connectionId);
if (number === null) return;
const prev = this.views.get(connectionId) ?? null;
const next = data ? snapshot.indexSnapshot(data) : null;
if (next) this.views.set(connectionId, next);
else {
this.views.delete(connectionId);
this.transmitting.delete(connectionId);
}
for (const event of snapshot.diffEvents(number, prev, next)) this.broadcast(event);
}
updateTalking(connectionId, clientId, talking) {
const number = snapshot.connectionNumber(connectionId);
const view = this.views.get(connectionId);
if (number === null || !view || !view.clients.has(clientId) || typeof talking !== 'boolean') return;
this.broadcast(snapshot.talkEvent(number, clientId, talking));
}
/** Own voice: the core reports it as audio_state.transmitting, not as a `talking` event. */
updateTransmitting(connectionId, transmitting) {
const number = snapshot.connectionNumber(connectionId);
const view = this.views.get(connectionId);
if (number === null || !view || typeof transmitting !== 'boolean') return;
if ((this.transmitting.get(connectionId) ?? false) === transmitting) return;
this.transmitting.set(connectionId, transmitting);
this.broadcast(snapshot.talkEvent(number, view.own, transmitting));
}
broadcast(message) {
for (const client of Array.from(this.clients)) if (client.state === 'authed') this.send(client, message);
}
}
// ---------- IPC (trusted main window only) ----------
const forbidden = { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
const badRequest = (message) => ({ ok: false, error: { code: 'bad_request', message } });
function failure(error) {
return { ok: false, error: { code: error?.code === 'ENOSPC' || error?.code === 'EACCES' || error?.code === 'EPERM' ? 'io' : 'failed', message: error?.message ?? 'failed' } };
}
/**
* Registers `remote-apps:*` handlers and starts the server when enabled.
* `listen` must be false for offscreen/automated runs unless an explicit disposable test flag allows binding.
* `sendToRenderer(channel, payload)` receives `remote-apps:status` (status object) and `remote-apps:key`
* ({identifier, button, state}); `onKey` (optional) additionally receives each key transition in main.
*/
function registerRemoteAppsIpc({ ipcMain, trustedSender, file, listen, sendToRenderer, onKey, log, limits }) {
const store = new RemoteAppStore(file);
if (store.loadError) log?.('warn', `remote apps: configuration ${store.loadError}; starting with no registered apps`);
const service = new RemoteAppsService({
store, listen, log, limits,
onStatus: (status) => sendToRenderer('remote-apps:status', status),
onKey: (key) => {
sendToRenderer('remote-apps:key', key);
onKey?.(key);
},
});
const guarded = (fn) => async (event, ...args) => {
if (!trustedSender(event)) return forbidden;
try {
return await fn(...args);
} catch (error) {
return failure(error);
}
};
ipcMain.handle('remote-apps:get', (event) => (trustedSender(event) ? service.status() : null));
ipcMain.handle('remote-apps:set-enabled', guarded(async (enabled) => {
if (typeof enabled !== 'boolean') return badRequest('enabled must be a boolean');
return { ok: true, status: await service.setEnabled(enabled) };
}));
ipcMain.handle('remote-apps:set-port', guarded(async (port) => {
if (!validPort(port)) return badRequest('port must be an integer 1025-65535');
return { ok: true, status: await service.setPort(port) };
}));
ipcMain.handle('remote-apps:respond', guarded((requestId, allow) => {
if (typeof requestId !== 'string' || requestId.length > 64 || typeof allow !== 'boolean') return badRequest('invalid permission response');
return service.respond(requestId, allow);
}));
ipcMain.handle('remote-apps:set-allowed', guarded((identifier, allowed) => {
if (!validIdentifier(identifier) || typeof allowed !== 'boolean') return badRequest('invalid application');
return service.setAllowed(identifier, allowed);
}));
ipcMain.handle('remote-apps:remove', guarded((identifier) => {
if (!validIdentifier(identifier)) return badRequest('invalid application');
return service.removeApp(identifier);
}));
service.start();
return service;
}
module.exports = { RemoteAppsService, registerRemoteAppsIpc, isLoopback, DEFAULT_LIMITS };
+297
View File
@@ -0,0 +1,297 @@
'use strict';
// Server Icons manager (official client_ui module 33609 with icon provider 66727): the virtual server's
// icon files live in file-transfer channel 0. Listing is `/icons/`; classic storage addresses each file as
// `/icon_<id>` on the wire, which the core derives from the canonical `/icons/icon_<id>` bridge path.
// Channel 0 never reaches the renderer's generic file commands: everything here is main-owned, pinned to
// one connection session, and host paths come only from the native dialog opened by an explicit click.
// HTTPFT/S3 servers are refused by the core (`media_unsupported`); nothing pretends to reach that storage.
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { crc32 } = require('./server-snapshot-codec');
const ICON_FOLDER = '/icons/';
/** Same bound as snapshot icon transfers; also below the core's 256 KiB `fetch_icon` preview limit. */
const MAX_ICON_BYTES = 128 * 1024;
/** Local decode-safety bound for raster headers (not a TeamSpeak rule; the server stays authoritative). */
const MAX_ICON_SIDE = 1024;
const MAX_SELECTION = 32;
/** `file_delete` accepts at most this many paths per command (core/src/file_transfer.rs MAX_DELETE). */
const DELETE_BATCH = 100;
const MAX_DELETE_IDS = 10_000;
const TRANSFER_DEADLINE_MS = 120_000;
/** Official upload dialog filter: image/jpeg, image/png, image/svg+xml. */
const UPLOAD_EXTENSIONS = ['png', 'jpg', 'jpeg', 'svg'];
/** Listing grants (one per open panel listing) and how long a panel may act on one. */
const MAX_GRANTS = 32;
const GRANT_TTL_MS = 30 * 60 * 1000;
function coded(code, message, extra = {}) { return Object.assign(new Error(message), { code }, extra); }
const fail = error => ({ ok: false, error: { code: error.code || 'server_icons_error', message: String(error.message || error) } });
/** Icon id of a listing entry name `icon_<canonical nonzero u32>`, else null. */
function iconIdOf(name) {
const match = /^icon_([1-9]\d{0,9})$/.exec(typeof name === 'string' ? name : '');
if (!match) return null;
const id = Number(match[1]);
return id <= 0xffffffff ? id : null;
}
function validIconId(id) { return Number.isSafeInteger(id) && id >= 1 && id <= 0xffffffff; }
const iconPath = id => `${ICON_FOLDER}icon_${id}`;
/** PNG IHDR or JPEG SOFn dimensions; null when the header is malformed. */
function rasterSize(bytes, mime) {
if (mime === 'image/png') {
if (bytes.length < 24 || bytes.subarray(12, 16).toString('ascii') !== 'IHDR') return null;
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
}
let i = 2;
while (i + 4 <= bytes.length) {
if (bytes[i] !== 0xff) return null;
const marker = bytes[i + 1];
if (marker === 0xff) { i += 1; continue; }
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) { i += 2; continue; }
if (marker === 0xd9 || marker === 0xda) return null;
const length = bytes.readUInt16BE(i + 2);
if (length < 2) return null;
const sof = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
if (sof) return i + 9 <= bytes.length ? { height: bytes.readUInt16BE(i + 5), width: bytes.readUInt16BE(i + 7) } : null;
i += 2 + length;
}
return null;
}
/**
* Type, size and decode checks for one chosen file. Raster headers are bounded before any decode; when
* Electron's nativeImage is supplied the bytes must also decode. SVG stays opaque bytes in main and is only
* ever shown by the renderer as an <img> blob (no script execution).
*/
function checkIconBytes(bytes, nativeImage) {
if (!bytes.length || bytes.length > MAX_ICON_BYTES) throw coded('too_large', 'Icon must be 1 byte to 128 KiB');
let mime = null;
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) mime = 'image/png';
else if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) mime = 'image/jpeg';
else if (/^(?:\uFEFF)?\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*(?:<!DOCTYPE[^>]*>\s*)?<svg[\s>]/i.test(bytes.toString('utf8'))) mime = 'image/svg+xml';
if (!mime) throw coded('unsupported_type', 'Icons must be PNG, JPEG or SVG');
if (mime !== 'image/svg+xml') {
const size = rasterSize(bytes, mime);
if (!size || size.width < 1 || size.height < 1) throw coded('invalid_image', 'The image header is damaged');
if (size.width > MAX_ICON_SIDE || size.height > MAX_ICON_SIDE) throw coded('too_large', `Icons may be at most ${MAX_ICON_SIDE}×${MAX_ICON_SIDE} pixels`);
if (nativeImage && nativeImage.createFromBuffer(bytes).isEmpty()) throw coded('invalid_image', 'The image could not be decoded');
}
return mime;
}
/** Read a dialog-chosen regular file of bounded size; never follows a size that changed while reading. */
async function readChosenFile(file) {
const handle = await fs.open(file, 'r');
try {
const stat = await handle.stat();
if (!stat.isFile()) throw coded('not_a_file', 'Choose a regular image file');
if (stat.size < 1 || stat.size > MAX_ICON_BYTES) throw coded('too_large', 'Icon must be 1 byte to 128 KiB');
const bytes = Buffer.alloc(stat.size + 1);
let read = 0;
for (;;) {
const { bytesRead } = await handle.read(bytes, read, bytes.length - read, read);
if (bytesRead === 0) break;
read += bytesRead;
if (read > stat.size) throw coded('changed', 'The file changed while it was read');
}
if (read !== stat.size) throw coded('changed', 'The file changed while it was read');
return bytes.subarray(0, read);
} finally { await handle.close(); }
}
function registerServerIconsIpc({ ipcMain, trustedSender, dialog, getWindow, request, validConnectionId, getConnection, subscribeCore, testOffscreen, tr, nativeImage = null }) {
const busy = new Set();
const invoke = async (id, command, args = {}) => {
const response = await request(id, command, args);
if (!response?.ok) throw coded(response?.error?.code || 'server_error', response?.error?.message || `${command} failed`);
return response.result;
};
/** The exact connection entry, main session counter and core process the operation started on. */
const pin = id => {
if (!validConnectionId(id)) throw coded('bad_request', 'Invalid server connection');
const entry = getConnection(id); if (!entry) throw coded('connection_closed', 'Server connection is closed');
const pinned = { id, entry, session: entry.session, core: entry.core };
pinned.same = () => getConnection(id) === entry && entry.session === pinned.session && entry.core === pinned.core;
pinned.alive = () => { if (!pinned.same()) throw coded('connection_changed', 'Server connection changed; reopen Server Icons'); };
return pinned;
};
const handle = (channel, callback) => ipcMain.handle(channel, async (event, ...args) => {
if (!trustedSender(event)) return fail(coded('forbidden', 'Forbidden'));
try { return await callback(event, ...args); } catch (error) { return fail(error); }
});
/** One icon operation per connection; `guard.check` fails once the connection or window changed. */
async function exclusive(event, id, work) {
const pinned = pin(id);
if (busy.has(id)) throw coded('busy', 'Another server icon operation is running');
busy.add(id);
const check = () => { pinned.alive(); if (!trustedSender(event)) throw coded('forbidden', 'Server Icons window changed'); };
try { return await work({ check, pinned }); } finally { busy.delete(id); }
}
// Opaque list grants: mutations are accepted only for the exact connection entry, session, core and admin
// generation that produced the listing the user saw. A UI from before a reconnect cannot mutate the new one.
const grants = new Map();
function grant(pinned, generation) {
const now = Date.now();
for (const [token, entry] of grants) if (entry.expires < now || !entry.pinned.same()) grants.delete(token);
while (grants.size >= MAX_GRANTS) grants.delete(grants.keys().next().value);
const token = crypto.randomUUID();
grants.set(token, { pinned, generation, expires: now + GRANT_TTL_MS });
return token;
}
/** Before the first mutation: the grant must belong to this pinned session and its generation still be current. */
async function authorize(id, token, { check, pinned }) {
const entry = typeof token === 'string' ? grants.get(token) : undefined;
const stale = () => coded('connection_changed', 'Server connection changed; reload Server Icons');
if (!entry || entry.expires < Date.now() || entry.pinned.id !== id || entry.pinned.entry !== pinned.entry
|| entry.pinned.session !== pinned.session || entry.pinned.core !== pinned.core || !entry.pinned.same()) throw stale();
const context = await invoke(id, 'admin_context'); check();
if (context?.generation !== entry.generation) { grants.delete(token); throw stale(); }
}
async function list(id, check) {
const listing = await invoke(id, 'file_list', { channel_id: 0, path: ICON_FOLDER }); check();
if (!Array.isArray(listing?.entries)) throw coded('server_error', 'Invalid icon list response');
const icons = [];
for (const entry of listing.entries) {
const iconId = entry?.type === 'file' ? iconIdOf(entry.name) : null;
if (iconId !== null) icons.push({ id: iconId, size: Number(entry.size) || 0, datetime: Number(entry.datetime) || 0 });
}
return icons;
}
/**
* Run one queued transfer to its terminal `file_transfer` event. A transfer abandoned while its session is
* unchanged (window changed, timeout) is cancelled; after a reconnect it is not: transfer ids restart per
* session, so the old id could name an unrelated transfer of the new session.
*/
async function transfer(id, command, args, { check, pinned }) {
check();
let transferId, finished = false, resolve, reject;
const early = new Map();
const completion = new Promise((a, b) => { resolve = a; reject = b; });
completion.catch(() => {});
const accept = event => {
if (finished || !['done', 'failed', 'cancelled'].includes(event.state)) return;
finished = true;
if (event.state === 'done') resolve(event);
else reject(coded(event.error?.code || event.state, event.error?.message || `Icon transfer ${event.state}`));
};
// Installed before the request: short transfers can finish before the queued reply arrives.
const unsubscribe = subscribeCore((connectionId, event) => {
if (connectionId !== id || event?.event !== 'file_transfer' || !pinned.same()) return;
if (transferId === undefined) early.set(event.transfer_id, event);
else if (event.transfer_id === transferId) accept(event);
});
let timer = null, deadline = null;
try {
transferId = (await invoke(id, command, args)).transfer_id;
if (!Number.isSafeInteger(transferId)) throw coded('server_error', 'Missing icon transfer ID');
if (early.has(transferId)) accept(early.get(transferId));
timer = setInterval(() => { try { check(); } catch (error) { if (!finished) { finished = true; reject(error); } } }, 250);
deadline = setTimeout(() => { if (!finished) { finished = true; reject(coded('timeout', 'Icon transfer did not finish')); } }, TRANSFER_DEADLINE_MS);
await completion;
check();
} catch (error) {
const terminal = ['done', 'failed', 'cancelled'].includes(error.code);
if (Number.isSafeInteger(transferId) && !terminal && pinned.same()) {
await request(id, 'file_cancel', { transfer_id: transferId }).catch(() => {});
}
throw error;
} finally {
clearInterval(timer); clearTimeout(deadline); unsubscribe();
}
}
const temporary = async fn => {
const folder = await fs.mkdtemp(path.join(os.tmpdir(), 'teamspeach-icons-'));
try { return await fn(folder); } finally { await fs.rm(folder, { recursive: true, force: true }); }
};
/** Content-addressed upload: never overwrites a different file that already holds this CRC32 name. */
async function uploadBytes(id, bytes, guard) {
const iconId = crc32(bytes);
if (!validIconId(iconId)) throw coded('invalid_image', 'This image has a reserved icon checksum');
const name = `icon_${iconId}`;
return temporary(async folder => {
if ((await list(id, guard.check)).some(icon => icon.id === iconId)) {
await transfer(id, 'file_download', { channel_id: 0, path: iconPath(iconId), dest_dir: folder, subdirs: [], overwrite: false }, guard);
const existing = await fs.readFile(path.join(folder, name));
if (!existing.equals(bytes)) throw coded('collision', 'A different icon already uses this checksum; it was not overwritten');
return { id: iconId, existing: true };
}
const source = path.join(folder, name);
await fs.writeFile(source, bytes, { flag: 'wx', mode: 0o600 });
await transfer(id, 'file_upload', { channel_id: 0, path: iconPath(iconId), source, overwrite: false }, guard);
if (!(await list(id, guard.check)).some(icon => icon.id === iconId)) throw coded('server_error', 'The upload finished but the server does not list the icon');
return { id: iconId, existing: false };
});
}
// A failed listing (e.g. HTTPFT/S3 storage) returns no grant, so nothing can be mutated from it.
handle('server-icons:list', (event, id) => exclusive(event, id, async ({ check, pinned }) => {
const context = await invoke(id, 'admin_context'); check();
if (!Number.isSafeInteger(context?.generation) || context.generation < 1) throw coded('connection_changed', 'Server connection is not ready');
const icons = await list(id, check);
return { ok: true, icons, generation: context.generation, authorization: grant(pinned, context.generation) };
}));
handle('server-icons:upload', (event, id, authorization) => exclusive(event, id, async guard => {
const { check } = guard;
if (testOffscreen) throw coded('unavailable', 'Icon file dialogs are disabled in offscreen tests');
await authorize(id, authorization, guard);
const window = getWindow();
const options = {
title: tr ? tr('server.icons.upload.title') : 'Select icon',
filters: [{ name: 'PNG, JPEG, SVG', extensions: UPLOAD_EXTENSIONS }],
properties: ['openFile', 'multiSelections', 'dontAddToRecent'],
};
const picked = await (window ? dialog.showOpenDialog(window, options) : dialog.showOpenDialog(options)); check();
if (picked.canceled || !picked.filePaths?.length) return { ok: true, cancelled: true };
// The dialog can stay open across a reconnect: verify the grant again before the first transfer.
await authorize(id, authorization, guard);
if (picked.filePaths.length > MAX_SELECTION) throw coded('bad_request', `Choose at most ${MAX_SELECTION} icons at once`);
const uploaded = [], errors = [];
for (const file of picked.filePaths) {
const name = path.basename(file);
try {
const bytes = await readChosenFile(file); check();
checkIconBytes(bytes, nativeImage);
uploaded.push({ ...(await uploadBytes(id, bytes, guard)), name });
} catch (error) {
if (['connection_changed', 'connection_closed', 'forbidden'].includes(error.code)) throw error;
errors.push({ name, code: error.code || 'server_icons_error', message: String(error.message || error) });
}
}
return { ok: true, uploaded, errors };
}));
handle('server-icons:delete', (event, id, authorization, ids) => exclusive(event, id, async guard => {
const { check } = guard;
if (!Array.isArray(ids) || ids.length < 1 || ids.length > MAX_DELETE_IDS || !ids.every(validIconId) || new Set(ids).size !== ids.length) {
throw coded('bad_request', 'Invalid icon selection');
}
await authorize(id, authorization, guard);
const deleted = [];
try {
for (let i = 0; i < ids.length; i += DELETE_BATCH) {
const batch = ids.slice(i, i + DELETE_BATCH);
await invoke(id, 'file_delete', { channel_id: 0, paths: batch.map(iconPath) }); check();
deleted.push(...batch);
}
} catch (error) {
return { ...fail(error), deleted };
}
return { ok: true, deleted };
}));
return { dispose() { busy.clear(); grants.clear(); } };
}
module.exports = { registerServerIconsIpc, checkIconBytes, rasterSize, iconIdOf, MAX_ICON_BYTES };
+5 -3
View File
@@ -66,6 +66,7 @@ function registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow,
}; };
const unsubscribe = subscribeCore((connectionId, event) => { const unsubscribe = subscribeCore((connectionId, event) => {
if (connectionId !== id || event.event !== 'file_transfer') return; if (connectionId !== id || event.event !== 'file_transfer') return;
try { job.alive(); } catch (error) { if (!finished) { finished = true; reject(error); } return; }
if (transferId === undefined) early.set(event.transfer_id, event); if (transferId === undefined) early.set(event.transfer_id, event);
else if (event.transfer_id === transferId) accept(event); else if (event.transfer_id === transferId) accept(event);
}); });
@@ -73,10 +74,11 @@ function registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow,
completion.catch(() => {}); completion.catch(() => {});
try { try {
const result = await invoke(id, command, args); transferId = result.transfer_id; const result = await invoke(id, command, args); transferId = result.transfer_id;
job.alive();
if (!Number.isSafeInteger(transferId) && typeof transferId !== 'string') throw new Error('Missing icon transfer ID'); if (!Number.isSafeInteger(transferId) && typeof transferId !== 'string') throw new Error('Missing icon transfer ID');
job.transferId = transferId; job.transferId = transferId;
if (early.has(transferId)) accept(early.get(transferId)); if (early.has(transferId)) accept(early.get(transferId));
if (job.cancelled) await invoke(id, 'file_cancel', { transfer_id: transferId }); if (job.cancelled) { job.alive(); await invoke(id, 'file_cancel', { transfer_id: transferId }); }
const timer = setInterval(() => { try { check(); } catch (error) { if (error.code !== 'cancelled' && !finished) { finished = true; reject(error); } } }, 250); const timer = setInterval(() => { try { check(); } catch (error) { if (error.code !== 'cancelled' && !finished) { finished = true; reject(error); } } }, 250);
try { await completion; } finally { clearInterval(timer); } try { await completion; } finally { clearInterval(timer); }
check(); check();
@@ -126,7 +128,7 @@ function registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow,
}; };
async function run(event, id, mode, prepare, action) { async function run(event, id, mode, prepare, action) {
if (jobs.has(id)) throw coded('busy', 'A snapshot operation is already running on this connection'); if (jobs.has(id)) throw coded('busy', 'A snapshot operation is already running on this connection');
const alive = pin(id), job = { cancelled: false, transferId: null }; const alive = pin(id), job = { cancelled: false, transferId: null, alive };
jobs.set(id, job); jobs.set(id, job);
let operation; let operation;
const check = () => { alive(); if (!trustedSender(event)) throw coded('forbidden', 'Snapshot window changed'); if (job.cancelled) throw coded('cancelled', 'Snapshot cancelled; completed changes are retained'); }; const check = () => { alive(); if (!trustedSender(event)) throw coded('forbidden', 'Snapshot window changed'); if (job.cancelled) throw coded('cancelled', 'Snapshot cancelled; completed changes are retained'); };
@@ -182,7 +184,7 @@ function registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow,
handle('snapshots:cancel', async (_event, id) => { handle('snapshots:cancel', async (_event, id) => {
const job = jobs.get(id); if (!job) return { ok: true, cancelling: false }; const job = jobs.get(id); if (!job) return { ok: true, cancelling: false };
job.cancelled = true; job.cancelled = true;
if (job.transferId !== null) await invoke(id, 'file_cancel', { transfer_id: job.transferId }); if (job.transferId !== null) { job.alive(); await invoke(id, 'file_cancel', { transfer_id: job.transferId }); }
return { ok: true, cancelling: true }; return { ok: true, cancelling: true };
}); });
return { dispose() { for (const job of jobs.values()) job.cancelled = true; imports.clear(); } }; return { dispose() { for (const job of jobs.values()) job.cancelled = true; imports.clear(); } };
+21 -5
View File
@@ -3,7 +3,8 @@
/** /**
* Voice preferences that follow the official TS6 audio settings model (client_ui/main.js, AudioSettings): * Voice preferences that follow the official TS6 audio settings model (client_ui/main.js, AudioSettings):
* - push to talk is global (`ptt.active`, release delay Off/100/300/500 ms, stored ms default 300); * - push to talk is global (`ptt.active`, release delay Off/100/300/500 ms, stored ms default 300);
* - capture DSP is per input device: agc, denoise, typing suppression, VAD on/off, VAD mode * - capture DSP is per input device: agc, denoise on/off + `denoiseLevel` (the official denoiserLevel
* 0..3 = Low/Moderate/High/Very High, default 1 Moderate), typing suppression, VAD on/off, VAD mode
* (automatic | volume_gate | hybrid), VAD level -50..50 dB (default -30); * (automatic | volume_gate | hybrid), VAD level -50..50 dB (default -30);
* - playback DSP is per output device: aec (echo cancellation), agc (level other users), comfort noise * - playback DSP is per output device: aec (echo cancellation), agc (level other users), comfort noise
* on/off + level -97..-23 dB (default -60), echo reduction/ducking -40..0 dB (default 0); * on/off + level -97..-23 dB (default -60), echo reduction/ducking -40..0 dB (default 0);
@@ -17,8 +18,10 @@
* Fresh profiles get the official defaults. A profile written by an earlier TeamsPeach version is migrated * Fresh profiles get the official defaults. A profile written by an earlier TeamsPeach version is migrated
* in memory from its legacy keys (transmitMode, vadSensitivity, echoCancellation, noiseSuppression, * in memory from its legacy keys (transmitMode, vadSensitivity, echoCancellation, noiseSuppression,
* autoGainControl, voiceVolume): every stored choice keeps its effect; controls that did not exist before * autoGainControl, voiceVolume): every stored choice keeps its effect; controls that did not exist before
* (playback AGC, comfort noise, ducking, typing attenuation, VAD level) start at the official defaults. * (playback AGC, comfort noise, ducking, typing attenuation, VAD level, noise reduction level) start at the
* The file itself is only rewritten — without the legacy keys — by the user's next settings change. * official defaults. Input profiles stored before `denoiseLevel` existed keep every stored field, including
* their denoise on/off choice, and gain the default level. The file itself is only rewritten — without the
* legacy keys — by the user's next settings change.
*/ */
const VAD_MODES = ['automatic', 'volume_gate', 'hybrid']; const VAD_MODES = ['automatic', 'volume_gate', 'hybrid'];
@@ -39,6 +42,7 @@ function validDb(v) {
const IN_FIELDS = { const IN_FIELDS = {
agc: isBool, agc: isBool,
denoise: isBool, denoise: isBool,
denoiseLevel: intIn(0, 3),
typing: isBool, typing: isBool,
vad: isBool, vad: isBool,
vadMode: (v) => VAD_MODES.includes(v), vadMode: (v) => VAD_MODES.includes(v),
@@ -55,7 +59,7 @@ const OUT_FIELDS = {
}; };
// Official defaults (main.js class k / class T). // Official defaults (main.js class k / class T).
const IN_DEFAULT = Object.freeze({ agc: true, denoise: true, typing: false, vad: true, vadMode: 'automatic', vadLevel: -30, vadSensitivity: 'normal' }); const IN_DEFAULT = Object.freeze({ agc: true, denoise: true, denoiseLevel: 1, typing: false, vad: true, vadMode: 'automatic', vadLevel: -30, vadSensitivity: 'normal' });
const OUT_DEFAULT = Object.freeze({ aec: false, agc: true, comfortNoise: false, comfortNoiseLevel: -60, echoReduction: 0 }); const OUT_DEFAULT = Object.freeze({ aec: false, agc: true, comfortNoise: false, comfortNoiseLevel: -60, echoReduction: 0 });
function validProfile(fields) { function validProfile(fields) {
@@ -96,12 +100,24 @@ function percentToDb(pct) {
return Math.max(-200, Math.min(10, db)); return Math.max(-200, Math.min(10, db));
} }
/** An input DSP value stored before `denoiseLevel` existed, with the default level added to every profile. */
function withDenoiseLevel(dsp) {
if (!isPlainObject(dsp) || !isPlainObject(dsp.devices)) return null;
const upgrade = (p) => (isPlainObject(p) && !has(p, 'denoiseLevel') ? { ...p, denoiseLevel: IN_DEFAULT.denoiseLevel } : p);
return { ...dsp, template: upgrade(dsp.template), devices: Object.fromEntries(Object.entries(dsp.devices).map(([id, p]) => [id, upgrade(p)])) };
}
/** /**
* Fills voice keys missing from a stored profile (`raw`, as read from disk) from its legacy keys, into * Fills voice keys missing from a stored profile (`raw`, as read from disk) from its legacy keys, into
* `values` (already holding validated stored keys and defaults). Keys present in `raw` are never touched. * `values` (already holding validated stored keys and defaults). A stored valid key is never touched; a stored
* input DSP that predates `denoiseLevel` is kept with that one field added.
*/ */
function migrateVoicePrefs(raw, values) { function migrateVoicePrefs(raw, values) {
if (!isPlainObject(raw)) return values; if (!isPlainObject(raw)) return values;
if (has(raw, 'inputDsp') && !VOICE_SCHEMA.inputDsp.check(raw.inputDsp)) {
const upgraded = withDenoiseLevel(raw.inputDsp);
if (upgraded && VOICE_SCHEMA.inputDsp.check(upgraded)) values.inputDsp = upgraded;
}
// A first-run or unrelated preference object is not a legacy audio profile. // A first-run or unrelated preference object is not a legacy audio profile.
if (!['transmitMode', 'vadSensitivity', 'autoGainControl', 'noiseSuppression', 'echoCancellation', 'voiceVolume'].some((key) => has(raw, key))) return values; if (!['transmitMode', 'vadSensitivity', 'autoGainControl', 'noiseSuppression', 'echoCancellation', 'voiceVolume'].some((key) => has(raw, key))) return values;
const legacy = (key, check, fallback) => (has(raw, key) && check(raw[key]) ? raw[key] : fallback); const legacy = (key, check, fallback) => (has(raw, key) && check(raw[key]) ? raw[key] : fallback);
+190 -110
View File
@@ -1,8 +1,8 @@
'use strict'; 'use strict';
/** /**
* Whisper lists, the incoming whisper mode and key bindings (local files only), plus the global shortcut * Whisper lists, the incoming whisper mode and key binding profiles (local files only), plus the global
* helper (`teamspeach-core hotkeys`). * shortcut helper (`teamspeach-core hotkeys`).
* *
* The official TeamSpeak 6 client keeps whisper lists and hotkeys as myTeamSpeak "syncable items" * The official TeamSpeak 6 client keeps whisper lists and hotkeys as myTeamSpeak "syncable items"
* (`ApplySyncableItemAction`) and the receive mode as a local JSON blob "whisper"; TeamsPeach has no account, * (`ApplySyncableItemAction`) and the receive mode as a local JSON blob "whisper"; TeamsPeach has no account,
@@ -11,27 +11,26 @@
* List objects keep the official field names (main.js 6.0.0.5163 byte 2368379): * List objects keep the official field names (main.js 6.0.0.5163 byte 2368379):
* { list_uuid, name, type: 1 List | 2 PredefinedGroup, whisper_entry_list: [{ name, uuid, type: 1 Client | 2 Channel }], * { list_uuid, name, type: 1 List | 2 PredefinedGroup, whisper_entry_list: [{ name, uuid, type: 1 Client | 2 Channel }],
* group_type 0..3, group_target_mode 0..6, target_server_uuid, target_server_name, target_group_id, target_group_name }. * group_type 0..3, group_target_mode 0..6, target_server_uuid, target_server_name, target_group_id, target_group_name }.
*
* Key bindings: see keybind-schema.js (profiles, actions, sources, version 1 → 2 migration).
*/ */
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { randomUUID } = require('node:crypto'); const { randomUUID } = require('node:crypto');
const schema = require('./keybind-schema');
const { spawn } = require('node:child_process'); const { spawn } = require('node:child_process');
const WHISPER_FILE = 'whisper.json'; const WHISPER_FILE = 'whisper.json';
const KEYBINDS_FILE = 'keybinds.json'; const KEYBINDS_FILE = 'keybinds.json';
const WHISPER_VERSION = 1; const WHISPER_VERSION = 1;
const KEYBINDS_VERSION = 1;
const MAX_LISTS = 200; const MAX_LISTS = 200;
const MAX_ENTRIES = 1024; const MAX_ENTRIES = 1024;
const MAX_BINDINGS = 64;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const CONTROL = /[\u0000-\u001f\u007f]/; const CONTROL = /[\u0000-\u001f\u007f]/;
const KEY_CODE = /^[A-Za-z0-9]{1,32}$/;
const LIST_TYPE = { List: 1, PredefinedGroup: 2 }; const LIST_TYPE = { List: 1, PredefinedGroup: 2 };
const ENTRY_TYPE = { Client: 1, Channel: 2 }; const ENTRY_TYPE = { Client: 1, Channel: 2 };
const RECEIVE_MODES = ['allow_all', 'deny_all']; const RECEIVE_MODES = ['allow_all', 'deny_all'];
const ACTIONS = ['whisper_list', 'quick_whisper', 'reply_whisper'];
const fail = (code, message) => ({ ok: false, error: { code, message } }); const fail = (code, message) => ({ ok: false, error: { code, message } });
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -143,42 +142,6 @@ function normalizeList(list, { assignUuid = false } = {}) {
}; };
} }
function normalizeBinding(b, listIds) {
if (!isObject(b) || !onlyKeys(b, ['id', 'action', 'target', 'code', 'ctrl', 'alt', 'shift', 'meta', 'global'])) throw new Error('binding: unknown field');
const id = b.id === undefined || b.id === '' ? randomUUID() : b.id;
if (typeof id !== 'string' || !UUID.test(id)) throw new Error('binding id: expected a UUID');
if (!ACTIONS.includes(b.action)) throw new Error('action: unknown');
const target = b.target ?? '';
if (b.action === 'whisper_list') {
// Official resolveTarget: a hotkey whose list is gone shows an empty target and does nothing.
if (typeof target !== 'string' || !listIds.has(target)) throw new Error('target: select a whisper list');
} else if (target !== '') throw new Error('target: only whisper_list has a target');
if (typeof b.code !== 'string' || !KEY_CODE.test(b.code)) throw new Error('code: invalid key');
for (const m of ['ctrl', 'alt', 'shift', 'meta', 'global']) {
if (typeof (b[m] ?? false) !== 'boolean') throw new Error(`${m}: expected true/false`);
}
return { id: id.toLowerCase(), action: b.action, target, code: b.code, ctrl: Boolean(b.ctrl), alt: Boolean(b.alt),
shift: Boolean(b.shift), meta: Boolean(b.meta), global: b.global !== false };
}
const chordKey = (b) => `${b.ctrl ? 'C' : ''}${b.alt ? 'A' : ''}${b.shift ? 'S' : ''}${b.meta ? 'M' : ''}+${b.code}`;
/** Bindings that cannot work as stored: same chord twice, or the push-to-talk key. */
function conflicts(bindings, pttCode) {
const out = [];
const byChord = new Map();
for (const b of bindings) {
const key = chordKey(b);
const other = byChord.get(key);
if (other) {
out.push({ id: b.id, reason: 'duplicate', with: other.id });
if (!out.some((c) => c.id === other.id && c.reason === 'duplicate')) out.push({ id: other.id, reason: 'duplicate', with: b.id });
} else byChord.set(key, b);
if (pttCode && b.code === pttCode && !b.ctrl && !b.alt && !b.shift && !b.meta) out.push({ id: b.id, reason: 'ptt' });
}
return out;
}
class WhisperStore { class WhisperStore {
constructor(dir, { now = Date.now } = {}) { constructor(dir, { now = Date.now } = {}) {
this.file = path.join(dir, WHISPER_FILE); this.file = path.join(dir, WHISPER_FILE);
@@ -249,54 +212,108 @@ class WhisperStore {
} }
} }
/**
* keybinds.json version 2: { version, requireExactMatch, activeProfile, profiles: [{ id, name, bindings }] }.
* A version 1 file is migrated on load (keybind-schema.loadStore); the original bytes are kept next to it as
* `keybinds.v1-<time>.json` before the v2 file replaces it, so nothing of the old file is ever lost.
*/
class KeybindStore { class KeybindStore {
constructor(dir, { now = Date.now } = {}) { constructor(dir, { now = Date.now, defaultProfileName = 'Default' } = {}) {
this.file = path.join(dir, KEYBINDS_FILE); this.file = path.join(dir, KEYBINDS_FILE);
const { data, readOnly, recovered } = readStore(this.file, KEYBINDS_VERSION, now); const { data, readOnly, recovered } = readStore(this.file, schema.KEYBINDS_VERSION, now);
this.readOnly = readOnly; this.readOnly = readOnly;
this.recovered = recovered; this.recovered = recovered;
this.bindings = []; const { state, dropped, migrated } = schema.loadStore(data, { defaultProfileName });
this.rawLoaded = data && Array.isArray(data.bindings) ? data.bindings.slice(0, MAX_BINDINGS) : []; this.state = state;
} this.droppedOnLoad = dropped;
this.migratedFrom = null;
/** Bindings are checked against the lists they target, so they are completed once the lists are known. */ if (migrated && !readOnly) {
attach(listIds) { const backup = path.join(dir, `keybinds.v1-${now()}.json`);
for (const raw of this.rawLoaded) { fs.copyFileSync(this.file, backup, fs.constants.COPYFILE_EXCL);
try { this.persist(state);
const b = normalizeBinding(raw, listIds); this.migratedFrom = backup;
if (!this.bindings.some((x) => x.id === b.id)) this.bindings.push(b);
} catch {
this.droppedOnLoad = (this.droppedOnLoad ?? 0) + 1;
}
} }
this.rawLoaded = [];
} }
get() { get() {
return this.bindings.map((b) => ({ ...b })); return {
requireExactMatch: this.state.requireExactMatch,
activeProfile: this.state.activeProfile,
profiles: this.state.profiles.map((p) => ({ id: p.id, name: p.name, bindings: p.bindings.map(copyBinding) })),
readOnly: this.readOnly,
};
} }
set(rawBindings, listIds) { profile(id) {
if (!Array.isArray(rawBindings) || rawBindings.length > MAX_BINDINGS) throw new Error(`bindings: at most ${MAX_BINDINGS}`); const p = typeof id === 'string' ? this.state.profiles.find((x) => x.id === id.toLowerCase()) : null;
const next = rawBindings.map((b) => normalizeBinding(b, listIds)); if (!p) throw new Error('profile: not found');
if (new Set(next.map((b) => b.id)).size !== next.length) throw new Error('bindings: duplicate id'); return p;
this.persist(next);
return this.get();
} }
/** Official: deleting a whisper list deletes its hotkeys ("…with all associated hotkeys"). */ /** Bindings of the active profile ("No Profile" → none). */
activeBindings() {
return this.state.profiles.find((p) => p.id === this.state.activeProfile)?.bindings ?? [];
}
setExact(value) {
if (typeof value !== 'boolean') throw new Error('requireExactMatch: expected true/false');
this.persist({ ...this.state, requireExactMatch: value });
}
/** Official addHotkeyProfile; the first profile becomes the active one (there is no other). */
addProfile(name) {
if (this.state.profiles.length >= schema.MAX_PROFILES) throw new Error(`at most ${schema.MAX_PROFILES} profiles`);
const profile = { id: randomUUID(), name: schema.normalizeProfileName(name), bindings: [] };
this.persist({ ...this.state, activeProfile: this.state.activeProfile ?? profile.id, profiles: [...this.state.profiles, profile] });
return profile.id;
}
renameProfile(id, name) {
const target = this.profile(id);
const nextName = schema.normalizeProfileName(name);
this.persist({ ...this.state, profiles: this.state.profiles.map((p) => (p === target ? { ...p, name: nextName } : p)) });
}
/** Official setDefault: the chosen profile becomes the one whose bindings are live. */
activateProfile(id) {
const target = this.profile(id);
if (target.id !== this.state.activeProfile) this.persist({ ...this.state, activeProfile: target.id });
}
/** Official shows delete only for a non-active profile; the active one cannot be deleted. */
deleteProfile(id) {
const target = this.profile(id);
if (target.id === this.state.activeProfile) throw new Error('profile: activate another profile before deleting this one');
this.persist({ ...this.state, profiles: this.state.profiles.filter((p) => p !== target) });
}
setBindings(id, rawBindings) {
const target = this.profile(id);
const bindings = schema.normalizeBindings(rawBindings, target.bindings);
this.persist({ ...this.state, profiles: this.state.profiles.map((p) => (p === target ? { ...p, bindings } : p)) });
}
/** Official: deleting a whisper list deletes its hotkeys ("…with all associated hotkeys"), in every profile. */
dropTarget(listUuid) { dropTarget(listUuid) {
const next = this.bindings.filter((b) => !(b.action === 'whisper_list' && b.target === listUuid)); let changed = false;
if (next.length !== this.bindings.length) this.persist(next); const profiles = this.state.profiles.map((p) => {
const bindings = p.bindings.filter((b) => !(b.action === 'whisper_list' && b.target === listUuid));
if (bindings.length === p.bindings.length) return p;
changed = true;
return { ...p, bindings };
});
if (changed) this.persist({ ...this.state, profiles });
} }
persist(next) { persist(next) {
if (this.readOnly) throw new Error('keybinds.json was written by a newer TeamsPeach; not overwriting it'); if (this.readOnly) throw new Error('keybinds.json was written by a newer TeamsPeach; not overwriting it');
writeJson(this.file, { version: KEYBINDS_VERSION, bindings: next }); writeJson(this.file, { version: schema.KEYBINDS_VERSION, requireExactMatch: next.requireExactMatch, activeProfile: next.activeProfile, profiles: next.profiles });
this.bindings = next; this.state = next;
} }
} }
const copyBinding = (b) => (b.remote ? { ...b, remote: { ...b.remote } } : { ...b });
// ------------------------------------------------------------------------------------------- helper // ------------------------------------------------------------------------------------------- helper
const HELPER_BACKENDS = ['windows_registerhotkey', 'xdg_portal_global_shortcuts', 'x11_xgrabkey', 'unavailable']; const HELPER_BACKENDS = ['windows_registerhotkey', 'xdg_portal_global_shortcuts', 'x11_xgrabkey', 'unavailable'];
@@ -304,10 +321,17 @@ const HELPER_ERRORS = ['in_use', 'unsupported_key', 'invalid', 'portal_denied',
const MAX_HELPER_LINE = 64 * 1024; const MAX_HELPER_LINE = 64 * 1024;
const MAX_RESTARTS = 3; const MAX_RESTARTS = 3;
// Backends that fire only on the exact modifier set; "Require exact key match" off adds modifier variants.
const EXACT_MODIFIER_BACKENDS = new Set(['windows_registerhotkey', 'x11_xgrabkey']);
/** /**
* Owns the `teamspeach-core hotkeys` child. It registers only the bindings marked global and reports * Owns the `teamspeach-core hotkeys` child. It registers only the bindings marked global and reports
* press/release for those ids; it never sees other keys (see core/src/hotkeys.rs). Disabled in offscreen * press/release for those ids; it never sees other keys (see core/src/hotkeys.rs). Disabled in offscreen
* tests so a test run never registers shortcuts on the user's desktop. * tests so a test run never registers shortcuts on the user's desktop.
*
* With exact matching off, RegisterHotKey/XGrabKey bindings are also registered with extra modifiers
* (keybind-schema.expandRegistrations); a variant's press/release is reported as its binding. The desktop
* portal decides matching itself, so it always receives only the bindings' own chords.
*/ */
class HotkeyHelper { class HotkeyHelper {
constructor({ resolveBinary, onEvent, onStatus, enabled, spawnProcess = spawn }) { constructor({ resolveBinary, onEvent, onStatus, enabled, spawnProcess = spawn }) {
@@ -319,11 +343,14 @@ class HotkeyHelper {
this.child = null; this.child = null;
this.seq = 0; this.seq = 0;
this.wanted = []; this.wanted = [];
this.held = new Set(); this.exact = true;
this.variantOf = new Map();
this.heldVariants = new Map(); // binding id → registered ids currently down
this.restarts = 0; this.restarts = 0;
const variants = { wanted: 0, registered: 0 };
this.status = enabled this.status = enabled
? { state: 'idle', backend: null, global: false, release: false, detail: '', results: [] } ? { state: 'idle', backend: null, global: false, release: false, detail: '', results: [], exact: true, variants }
: { state: 'disabled', backend: null, global: false, release: false, detail: 'test_offscreen', results: [] }; : { state: 'disabled', backend: null, global: false, release: false, detail: 'test_offscreen', results: [], exact: true, variants };
} }
setStatus(patch) { setStatus(patch) {
@@ -331,15 +358,20 @@ class HotkeyHelper {
this.onStatus(this.status); this.onStatus(this.status);
} }
/** Replaces the registered set with `bindings` (global ones only). Starts or stops the helper as needed. */ /**
bind(bindings) { * Replaces the registered set with the global physical `bindings`. Starts or stops the helper as needed.
this.wanted = bindings.filter((b) => b.global).map((b) => ({ * `exact` is the profile store's requireExactMatch.
*/
bind(bindings, { exact = true } = {}) {
this.wanted = bindings.filter((b) => b.global && !b.remote).map((b) => ({
id: b.id, code: b.code, ctrl: b.ctrl, alt: b.alt, shift: b.shift, meta: b.meta, description: b.description ?? b.action, id: b.id, code: b.code, ctrl: b.ctrl, alt: b.alt, shift: b.shift, meta: b.meta, description: b.description ?? b.action,
})); }));
this.exact = exact;
this.status = { ...this.status, exact };
if (!this.enabled) return; if (!this.enabled) return;
if (this.wanted.length === 0) { if (this.wanted.length === 0) {
this.stop(); this.stop();
this.setStatus({ state: 'idle', results: [] }); this.setStatus({ state: 'idle', results: [], variants: { wanted: 0, registered: 0 } });
return; return;
} }
if (!this.child) this.start(); if (!this.child) this.start();
@@ -410,25 +442,37 @@ class HotkeyHelper {
case 'bound': case 'bound':
case 'rebound': { case 'rebound': {
if (msg.event === 'bound' && msg.seq !== this.seq) return; // answer to a superseded bind if (msg.event === 'bound' && msg.seq !== this.seq) return; // answer to a superseded bind
const results = Array.isArray(msg.results) ? msg.results.filter((r) => isObject(r) && typeof r.id === 'string').map((r) => ({ const all = Array.isArray(msg.results) ? msg.results.filter((r) => isObject(r) && typeof r.id === 'string' && this.variantOf.has(r.id)) : [];
const results = all.filter((r) => this.variantOf.get(r.id) === r.id).map((r) => ({
id: r.id, id: r.id,
ok: r.ok === true, ok: r.ok === true,
trigger: typeof r.trigger === 'string' ? r.trigger.slice(0, 128) : '', trigger: typeof r.trigger === 'string' ? r.trigger.slice(0, 128) : '',
error: r.ok === true ? undefined : (HELPER_ERRORS.includes(r.error) ? r.error : 'failed'), error: r.ok === true ? undefined : (HELPER_ERRORS.includes(r.error) ? r.error : 'failed'),
detail: typeof r.detail === 'string' ? r.detail.slice(0, 512) : '', detail: typeof r.detail === 'string' ? r.detail.slice(0, 512) : '',
})) : []; }));
// Variants another program already owns (in_use) simply do not fire; the binding's own chord decides its status.
const registered = all.filter((r) => this.variantOf.get(r.id) !== r.id && r.ok === true).length;
this.restarts = 0; this.restarts = 0;
this.setStatus({ state: 'ready', results }); this.setStatus({ state: 'ready', results, variants: { ...this.status.variants, registered } });
break; break;
} }
case 'press': case 'press':
case 'release': { case 'release': {
if (typeof msg.id !== 'string' || !this.wanted.some((b) => b.id === msg.id)) return; const id = typeof msg.id === 'string' ? this.variantOf.get(msg.id) : undefined;
if (!id) return;
const down = this.heldVariants.get(id) ?? new Set();
if (msg.event === 'press') { if (msg.event === 'press') {
if (this.held.has(msg.id)) return; if (down.has(msg.id)) return;
this.held.add(msg.id); down.add(msg.id);
} else if (!this.held.delete(msg.id)) return; this.heldVariants.set(id, down);
this.onEvent({ id: msg.id, state: msg.event, source: 'global' }); if (down.size === 1) this.onEvent({ id, state: 'press', source: 'global' });
} else {
if (!down.delete(msg.id)) return;
if (down.size === 0) {
this.heldVariants.delete(id);
this.onEvent({ id, state: 'release', source: 'global' });
}
}
break; break;
} }
case 'error': case 'error':
@@ -442,14 +486,21 @@ class HotkeyHelper {
sendBind() { sendBind() {
if (!this.child || !this.status.global) return; if (!this.child || !this.status.global) return;
this.releaseAll(); this.releaseAll();
const expand = !this.exact && EXACT_MODIFIER_BACKENDS.has(this.status.backend);
const { registrations, variantOf, variants } = schema.expandRegistrations(this.wanted, { exact: !expand });
this.variantOf = variantOf;
this.status = { ...this.status, variants: { wanted: variants.wanted, registered: 0 } };
this.seq = (this.seq + 1) >>> 0; this.seq = (this.seq + 1) >>> 0;
this.child.stdin.write(`${JSON.stringify({ cmd: 'bind', seq: this.seq, bindings: this.wanted })}\n`); this.child.stdin.write(`${JSON.stringify({ cmd: 'bind', seq: this.seq, bindings: registrations })}\n`);
} }
/** A held global key must never stay "held" after a rebind, crash or shutdown: whisper would stick. */ /**
* A held global key must never stay "held" after a rebind, crash or shutdown: whisper or PTT would stick.
* These releases are `synthetic`: they end held actions but never fire release-triggered actions.
*/
releaseAll() { releaseAll() {
for (const id of this.held) this.onEvent({ id, state: 'release', source: 'global' }); for (const id of this.heldVariants.keys()) this.onEvent({ id, state: 'release', source: 'global', synthetic: true });
this.held.clear(); this.heldVariants.clear();
} }
fault(child, detail) { fault(child, detail) {
@@ -492,13 +543,13 @@ class HotkeyHelper {
// ------------------------------------------------------------------------------------------- IPC // ------------------------------------------------------------------------------------------- IPC
/** /**
* Registers the renderer API. `getPttCode` supplies the push-to-talk key for conflict checks; `testOffscreen` * Registers the renderer API. `getPttCode` supplies the Audio push-to-talk key for conflict checks;
* disables the global helper (bindings then work only while the window is focused, and the status says so). * `testOffscreen` disables the global helper (bindings then work only while the window is focused, and the
* status says so). `defaultProfileName` names the profile a version 1 keybinds.json migrates into.
*/ */
function registerWhisperIpc({ ipcMain, trustedSender, getWindow, userDataDir, resolveBinary, testOffscreen, getPttCode, spawnProcess }) { function registerWhisperIpc({ ipcMain, trustedSender, getWindow, userDataDir, resolveBinary, testOffscreen, getPttCode, spawnProcess, defaultProfileName }) {
const whisper = new WhisperStore(userDataDir); const whisper = new WhisperStore(userDataDir);
const keybinds = new KeybindStore(userDataDir); const keybinds = new KeybindStore(userDataDir, { defaultProfileName });
keybinds.attach(whisper.listIds());
const send = (channel, payload) => { const send = (channel, payload) => {
const contents = getWindow()?.webContents; const contents = getWindow()?.webContents;
if (contents && !contents.isDestroyed()) contents.send(channel, payload); if (contents && !contents.isDestroyed()) contents.send(channel, payload);
@@ -510,15 +561,35 @@ function registerWhisperIpc({ ipcMain, trustedSender, getWindow, userDataDir, re
onEvent: (event) => send('keybinds:event', event), onEvent: (event) => send('keybinds:event', event),
onStatus: (status) => send('keybinds:status', status), onStatus: (status) => send('keybinds:status', status),
}); });
const keybindState = () => ({ const conflictsOf = (bindings) => schema.conflicts(bindings, getPttCode(), whisper.listIds());
bindings: keybinds.get(), const keybindState = () => {
conflicts: conflicts(keybinds.bindings, getPttCode()), const state = keybinds.get();
status: helper.status, return {
readOnly: keybinds.readOnly, ...state,
}); profiles: state.profiles.map((p) => ({ ...p, conflicts: conflictsOf(p.bindings) })),
status: helper.status,
recovered: keybinds.recovered,
migratedFrom: keybinds.migratedFrom,
droppedOnLoad: keybinds.droppedOnLoad,
};
};
/**
* Only the active profile is live; conflicting rows are never registered. While the renderer records a
* keyboard chord nothing is registered, so a key already bound globally reaches the recorder instead of
* firing (RegisterHotKey/XGrabKey would swallow it).
*/
let capturing = false;
const bindAvailable = () => { const bindAvailable = () => {
const blocked = new Set(conflicts(keybinds.bindings, getPttCode()).map((c) => c.id)); const bindings = capturing ? [] : keybinds.activeBindings();
helper.bind(keybinds.bindings.filter((b) => !blocked.has(b.id))); const blocked = new Set(conflictsOf(bindings).map((c) => c.id));
helper.bind(bindings.filter((b) => !blocked.has(b.id)), { exact: keybinds.state.requireExactMatch });
};
/** keybinds:capture(on) — the renderer's keyboard recorder started/ended (it also ends on window blur). */
const setCapturing = (on) => {
if (typeof on !== 'boolean') throw new Error('capture: expected true/false');
if (capturing === on) return;
capturing = on;
bindAvailable();
}; };
bindAvailable(); bindAvailable();
@@ -530,9 +601,18 @@ function registerWhisperIpc({ ipcMain, trustedSender, getWindow, userDataDir, re
return fail('bad_request', err.message); return fail('bad_request', err.message);
} }
}; };
const keybindChange = (change) => guard((...args) => {
const extra = change(...args);
bindAvailable();
return { ok: true, ...extra, ...keybindState() };
});
ipcMain.handle('whisper:get', guard(() => ({ ok: true, ...whisper.get(), recovered: whisper.recovered }))); ipcMain.handle('whisper:get', guard(() => ({ ok: true, ...whisper.get(), recovered: whisper.recovered })));
ipcMain.handle('whisper:save-list', guard((list) => ({ ok: true, list: whisper.saveList(list) }))); ipcMain.handle('whisper:save-list', guard((list) => {
const saved = whisper.saveList(list);
bindAvailable(); // a binding waiting for this list may become usable
return { ok: true, list: saved };
}));
ipcMain.handle('whisper:delete-list', guard((listUuid) => { ipcMain.handle('whisper:delete-list', guard((listUuid) => {
if (typeof listUuid !== 'string' || !UUID.test(listUuid)) throw new Error('list_uuid: expected a UUID'); if (typeof listUuid !== 'string' || !UUID.test(listUuid)) throw new Error('list_uuid: expected a UUID');
const deleted = whisper.deleteList(listUuid.toLowerCase()); const deleted = whisper.deleteList(listUuid.toLowerCase());
@@ -547,11 +627,13 @@ function registerWhisperIpc({ ipcMain, trustedSender, getWindow, userDataDir, re
return { ok: true, receiveMode: whisper.receiveMode }; return { ok: true, receiveMode: whisper.receiveMode };
})); }));
ipcMain.handle('keybinds:get', guard(() => ({ ok: true, ...keybindState() }))); ipcMain.handle('keybinds:get', guard(() => ({ ok: true, ...keybindState() })));
ipcMain.handle('keybinds:set', guard((bindings) => { ipcMain.handle('keybinds:set', keybindChange((profileId, bindings) => { keybinds.setBindings(profileId, bindings); }));
keybinds.set(bindings, whisper.listIds()); ipcMain.handle('keybinds:set-exact', keybindChange((value) => { keybinds.setExact(value); }));
bindAvailable(); ipcMain.handle('keybinds:profile-add', keybindChange((name) => ({ profileId: keybinds.addProfile(name) })));
return { ok: true, ...keybindState() }; ipcMain.handle('keybinds:profile-rename', keybindChange((profileId, name) => { keybinds.renameProfile(profileId, name); }));
})); ipcMain.handle('keybinds:profile-activate', keybindChange((profileId) => { keybinds.activateProfile(profileId); }));
ipcMain.handle('keybinds:profile-delete', keybindChange((profileId) => { keybinds.deleteProfile(profileId); }));
ipcMain.handle('keybinds:capture', guard((on) => { setCapturing(on); return { ok: true }; }));
return { return {
whisper, whisper,
@@ -567,7 +649,5 @@ module.exports = {
WhisperStore, WhisperStore,
KeybindStore, KeybindStore,
HotkeyHelper, HotkeyHelper,
conflicts,
normalizeList, normalizeList,
normalizeBinding,
}; };
+26 -2
View File
@@ -23,7 +23,13 @@ contextBridge.exposeInMainWorld('teamspeach', {
deleteWhisperList: (listUuid) => ipcRenderer.invoke('whisper:delete-list', listUuid), deleteWhisperList: (listUuid) => ipcRenderer.invoke('whisper:delete-list', listUuid),
setWhisperReceiveMode: (mode) => ipcRenderer.invoke('whisper:set-receive-mode', mode), setWhisperReceiveMode: (mode) => ipcRenderer.invoke('whisper:set-receive-mode', mode),
getKeybinds: () => ipcRenderer.invoke('keybinds:get'), getKeybinds: () => ipcRenderer.invoke('keybinds:get'),
setKeybinds: (bindings) => ipcRenderer.invoke('keybinds:set', bindings), setKeybinds: (profileId, bindings) => ipcRenderer.invoke('keybinds:set', profileId, bindings),
setKeybindExact: (value) => ipcRenderer.invoke('keybinds:set-exact', value),
addKeybindProfile: (name) => ipcRenderer.invoke('keybinds:profile-add', name),
renameKeybindProfile: (profileId, name) => ipcRenderer.invoke('keybinds:profile-rename', profileId, name),
activateKeybindProfile: (profileId) => ipcRenderer.invoke('keybinds:profile-activate', profileId),
deleteKeybindProfile: (profileId) => ipcRenderer.invoke('keybinds:profile-delete', profileId),
setKeybindCapture: (on) => ipcRenderer.invoke('keybinds:capture', on),
onKeybindEvent: (callback) => subscribe('keybinds:event', callback), onKeybindEvent: (callback) => subscribe('keybinds:event', callback),
onKeybindStatus: (callback) => subscribe('keybinds:status', callback), onKeybindStatus: (callback) => subscribe('keybinds:status', callback),
snapshotExport: (connectionId, options) => ipcRenderer.invoke('snapshots:export', connectionId, options), snapshotExport: (connectionId, options) => ipcRenderer.invoke('snapshots:export', connectionId, options),
@@ -68,10 +74,28 @@ contextBridge.exposeInMainWorld('teamspeach', {
onStreamPopoutReady: (callback) => subscribe('stream-popout:ready', callback), onStreamPopoutReady: (callback) => subscribe('stream-popout:ready', callback),
presentStreamPopout: (input) => ipcRenderer.invoke('stream-popout:present', input), presentStreamPopout: (input) => ipcRenderer.invoke('stream-popout:present', input),
osCapabilities: () => ipcRenderer.invoke('os:capabilities'), osCapabilities: () => ipcRenderer.invoke('os:capabilities'),
getChangelog: () => ipcRenderer.invoke('about:changelog'),
getLicenses: () => ipcRenderer.invoke('about:licenses'),
getLicenseText: (id) => ipcRenderer.invoke('about:license-text', id),
badgeInfo: (uuids) => ipcRenderer.invoke('badges:info', uuids),
badgeArt: (uuid, detailed) => ipcRenderer.invoke('badges:art', uuid, detailed === true),
serverIconsList: (id) => ipcRenderer.invoke('server-icons:list', id),
serverIconsUpload: (id, authorization) => ipcRenderer.invoke('server-icons:upload', id, authorization),
serverIconsDelete: (id, authorization, ids) => ipcRenderer.invoke('server-icons:delete', id, authorization, ids),
osSetAutostart: (on) => ipcRenderer.invoke('os:set-autostart', on === true), osSetAutostart: (on) => ipcRenderer.invoke('os:set-autostart', on === true),
osApply: () => ipcRenderer.invoke('os:apply'), osApply: () => ipcRenderer.invoke('os:apply'),
osFlash: (kind) => ipcRenderer.invoke('os:flash', kind === 'poke' ? 'poke' : 'message'), osFlash: (kind) => ipcRenderer.invoke('os:flash', kind === 'poke' ? 'poke' : 'message'),
osNotify: (title, body) => ipcRenderer.invoke('os:notify', String(title), String(body)), osNotify: (title, body, kind = 'private') => ipcRenderer.invoke('os:notify', String(title), String(body), kind),
privacyLinkThreat: (host) => ipcRenderer.invoke('privacy:link-threat', host),
privacyThreatStatus: () => ipcRenderer.invoke('privacy:threat-status'),
getRemoteApps: () => ipcRenderer.invoke('remote-apps:get'),
setRemoteAppsEnabled: (enabled) => ipcRenderer.invoke('remote-apps:set-enabled', enabled),
setRemoteAppsPort: (port) => ipcRenderer.invoke('remote-apps:set-port', port),
respondRemoteApp: (requestId, allowed) => ipcRenderer.invoke('remote-apps:respond', requestId, allowed),
setRemoteAppAllowed: (identifier, allowed) => ipcRenderer.invoke('remote-apps:set-allowed', identifier, allowed),
removeRemoteApp: (identifier) => ipcRenderer.invoke('remote-apps:remove', identifier),
onRemoteAppsStatus: (callback) => subscribe('remote-apps:status', callback),
onRemoteAppKey: (callback) => subscribe('remote-apps:key', callback),
onOsLock: (callback) => subscribe('os:lock', (locked) => callback(locked === true)), onOsLock: (callback) => subscribe('os:lock', (locked) => callback(locked === true)),
getAppInfo: () => ipcRenderer.invoke('app:info'), getAppInfo: () => ipcRenderer.invoke('app:info'),
getWindowState: () => ipcRenderer.invoke('window:get-state'), getWindowState: () => ipcRenderer.invoke('window:get-state'),
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+24 -2
View File
@@ -2,7 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' tsext:; img-src 'self' data: blob: tsext:; media-src 'self' blob: mediastream:; font-src 'self' tsext:; connect-src 'none'; worker-src 'self'; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'"> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' tsext:; img-src 'self' data: blob: tsext:; media-src 'self' blob: mediastream:; font-src 'self' tsext:; connect-src 'self'; worker-src 'self'; base-uri 'none'; form-action 'none'; frame-src app://teamspeach/mermaid-frame.html; object-src 'none'">
<meta name="color-scheme" content="light dark"> <meta name="color-scheme" content="light dark">
<title>TeamsPeach</title> <title>TeamsPeach</title>
<link rel="stylesheet" href="styles/app.css"> <link rel="stylesheet" href="styles/app.css">
@@ -10,6 +10,13 @@
<link rel="stylesheet" href="styles/titlebar.css"> <link rel="stylesheet" href="styles/titlebar.css">
<link rel="stylesheet" href="styles/user-styles.css"> <link rel="stylesheet" href="styles/user-styles.css">
<link rel="stylesheet" href="styles/settings.css"> <link rel="stylesheet" href="styles/settings.css">
<link rel="stylesheet" href="styles/privacy.css">
<link rel="stylesheet" href="styles/information-panels.css">
<link rel="stylesheet" href="styles/chat-options.css">
<link rel="stylesheet" href="styles/remote-apps.css">
<link rel="stylesheet" href="styles/keybinds.css">
<link rel="stylesheet" href="styles/whisper.css">
<link rel="stylesheet" href="styles/contacts.css">
<link rel="stylesheet" href="styles/admin.css"> <link rel="stylesheet" href="styles/admin.css">
<link rel="stylesheet" href="styles/broadcast.css"> <link rel="stylesheet" href="styles/broadcast.css">
<link rel="stylesheet" href="vendor/katex/katex.min.css"> <link rel="stylesheet" href="vendor/katex/katex.min.css">
@@ -23,6 +30,9 @@
</header> </header>
<svg class="sprite" aria-hidden="true" focusable="false"> <svg class="sprite" aria-hidden="true" focusable="false">
<!-- Official TeamSpeak 6 client icons (proprietary artwork, TeamSpeak Systems GmbH), from the installed client html/client_ui/images/icons; provenance and transforms: LICENSES/teamspeak-client-icons-PROVENANCE.md. Id = "i-" + official TSIcon kebab id (group icons: i-group-<server icon id>); shape-rendering mirrors the official ts-icon renderer. --> <!-- Official TeamSpeak 6 client icons (proprietary artwork, TeamSpeak Systems GmbH), from the installed client html/client_ui/images/icons; provenance and transforms: LICENSES/teamspeak-client-icons-PROVENANCE.md. Id = "i-" + official TSIcon kebab id (group icons: i-group-<server icon id>); shape-rendering mirrors the official ts-icon renderer. -->
<symbol id="i-server-icons" class="tsv-icon-chat-image" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-server-icons--chat_image" x="0" y="0" width="22" height="22" fill="none"/> <g> <g> <path d="M18.355,3C19.263,3 20,3.737 20,4.645L20,17.355C20,18.263 19.263,19 18.355,19L3.645,19C2.737,19 2,18.263 2,17.355L2,4.645C2,3.737 2.737,3 3.645,3L18.355,3ZM17.938,4L4.062,4C3.476,4 3,4.476 3,5.062L3,15.938C3,16.524 3.476,17 4.062,17L17.938,17C18.524,17 19,16.524 19,15.938L19,5.062C19,4.476 18.524,4 17.938,4Z" class="tsv-icon-base-fill"/> </g> </g> <path d="M9.599,12.152L13.017,8.485C13.206,8.282 13.471,8.167 13.748,8.167C14.026,8.167 14.291,8.282 14.48,8.485L18,12.261L18,14.095L14.48,10.318C14.291,10.115 14.026,10 13.748,10C13.471,10 13.206,10.115 13.017,10.318L10.453,13.068L9.599,12.152Z" class="tsv-icon-base-fill"/> <path d="M4,13.854L6.861,10.785C7.051,10.582 7.316,10.467 7.593,10.467C7.87,10.467 8.135,10.582 8.324,10.785L13.186,16L11.322,16L8.324,12.785C8.135,12.582 7.87,12.467 7.593,12.467C7.316,12.467 7.051,12.582 6.861,12.785L4.217,15.622C4.081,15.451 4,15.235 4,15L4,13.854Z" class="tsv-icon-base-fill"/> <circle cx="6.147" cy="7" r="2" class="tsv-icon-base-fill"/> </symbol>
<symbol id="i-server-global" class="tsv-icon-server-global" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-server-global--server_global" x="0" y="0" width="22" height="22" fill="none"/> <g> <path d="M11,3.941C13.922,3.941 16.294,6.313 16.294,9.235C16.294,12.157 13.904,14.872 11,18.059C8.142,14.84 5.706,12.157 5.706,9.235C5.706,6.313 8.078,3.941 11,3.941ZM11,6.294C12.623,6.294 13.941,7.612 13.941,9.235C13.941,10.859 12.623,12.177 11,12.177C9.377,12.177 8.059,10.859 8.059,9.235C8.059,7.612 9.377,6.294 11,6.294Z" class="tsv-icon-base-fill"/> </g> </symbol>
<symbol id="i-folder-action" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-folder-action" fill="none"><path d="M18.5 15.7666C18.5 16.16 18.342 16.5373 18.0607 16.8155C17.7794 17.0937 17.3978 17.25 17 17.25H5C4.60218 17.25 4.22064 17.0937 3.93934 16.8155C3.65804 16.5373 3.5 16.16 3.5 15.7666V6.23343C3.5 5.84 3.65804 5.46269 3.93934 5.18449C4.22064 4.90629 4.60218 4.75 5 4.75H8.75L11.2665 7.18167H17C17.3978 7.18167 17.7794 7.33796 18.0607 7.61616C18.342 7.89435 18.5 8.27167 18.5 8.6651V15.7666Z" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/></symbol>
<symbol id="i-delay-low" class="tsv-icon-delay-low" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-delay-low--delay_low" x="0" y="0" width="22" height="22" fill="none"/> <path d="M14.121,11C14.121,10.18 13.456,9.515 12.636,9.515L10.606,9.515C9.787,9.515 9.121,10.18 9.121,11L9.121,11.015C9.121,11.834 9.787,12.5 10.606,12.5L12.636,12.5C13.456,12.5 14.121,11.834 14.121,11.015L14.121,11Z" class="tsv-icon-base-fill"/> </symbol> <symbol id="i-delay-low" class="tsv-icon-delay-low" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-delay-low--delay_low" x="0" y="0" width="22" height="22" fill="none"/> <path d="M14.121,11C14.121,10.18 13.456,9.515 12.636,9.515L10.606,9.515C9.787,9.515 9.121,10.18 9.121,11L9.121,11.015C9.121,11.834 9.787,12.5 10.606,12.5L12.636,12.5C13.456,12.5 14.121,11.834 14.121,11.015L14.121,11Z" class="tsv-icon-base-fill"/> </symbol>
<symbol id="i-delay-medium" class="tsv-icon-delay-medium" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-delay-medium--delay_medium" x="0" y="0" width="22" height="22" fill="none"/> <path d="M15.611,10.993C15.611,10.173 14.946,9.507 14.126,9.507L9.097,9.507C8.277,9.507 7.611,10.173 7.611,10.993L7.611,11.007C7.611,11.827 8.277,12.493 9.097,12.493L14.126,12.493C14.946,12.493 15.611,11.827 15.611,11.007L15.611,10.993Z" class="tsv-icon-base-fill"/> </symbol> <symbol id="i-delay-medium" class="tsv-icon-delay-medium" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-delay-medium--delay_medium" x="0" y="0" width="22" height="22" fill="none"/> <path d="M15.611,10.993C15.611,10.173 14.946,9.507 14.126,9.507L9.097,9.507C8.277,9.507 7.611,10.173 7.611,10.993L7.611,11.007C7.611,11.827 8.277,12.493 9.097,12.493L14.126,12.493C14.946,12.493 15.611,11.827 15.611,11.007L15.611,10.993Z" class="tsv-icon-base-fill"/> </symbol>
<symbol id="i-delay-high" class="tsv-icon-delay-high" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-delay-high--delay_high" x="0" y="0" width="22" height="22" fill="none"/> <path d="M17.621,10.985C17.621,10.166 16.956,9.5 16.136,9.5L7.106,9.5C6.287,9.5 5.621,10.166 5.621,10.985L5.621,11C5.621,11.82 6.287,12.485 7.106,12.485L16.136,12.485C16.956,12.485 17.621,11.82 17.621,11L17.621,10.985Z" class="tsv-icon-base-fill"/> </symbol> <symbol id="i-delay-high" class="tsv-icon-delay-high" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-delay-high--delay_high" x="0" y="0" width="22" height="22" fill="none"/> <path d="M17.621,10.985C17.621,10.166 16.956,9.5 16.136,9.5L7.106,9.5C6.287,9.5 5.621,10.166 5.621,10.985L5.621,11C5.621,11.82 6.287,12.485 7.106,12.485L16.136,12.485C16.956,12.485 17.621,11.82 17.621,11L17.621,10.985Z" class="tsv-icon-base-fill"/> </symbol>
@@ -206,6 +216,8 @@
<symbol id="i-viewer-small" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-viewer-small" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.62898 9.5406C1.19278 10.0043 0.949062 10.6167 0.949062 11.2529C0.945313 11.3479 0.945312 11.4441 0.945312 11.5366C0.945312 12.0453 1.10029 12.5415 1.38901 12.9602C2.55136 14.5725 5.90095 18.532 10.9441 18.532C15.9872 18.532 19.3368 14.5725 20.4941 12.9564C20.7828 12.539 20.9378 12.044 20.9378 11.5366C20.9428 11.4441 20.9428 11.3479 20.9428 11.2529C20.9428 10.6155 20.7004 10.0018 20.2629 9.53685C19.5592 8.80944 18.6681 7.97829 17.6282 7.22214C15.7772 5.87606 13.4675 4.78369 10.9441 4.78369C8.42063 4.78369 6.11092 5.87606 4.2599 7.22214C3.22003 7.97829 2.32889 8.80944 1.62898 9.5406ZM10.9441 7.28338C12.9201 7.28338 14.7086 8.19077 16.1572 9.24439C17.2083 10.008 18.0844 10.8579 18.7256 11.5566C19.1343 12.009 19.1555 12.0931 18.7768 12.5705C17.3733 14.2328 14.6849 16.685 10.9441 16.685C7.20328 16.685 4.51487 14.2328 3.11879 12.5643C2.74259 12.0906 2.76384 12.0115 3.16754 11.5616C3.80371 10.8579 4.67985 10.008 5.73097 9.24439C7.17954 8.19077 8.96807 7.28338 10.9441 7.28338Z" class="tsv-icon-base-fill"/><path fill-rule="evenodd" clip-rule="evenodd" d="M10.9999 8.20679C12.9052 8.20679 14.4509 9.75247 14.4509 11.6578C14.4509 13.5632 12.9052 15.1089 10.9999 15.1089C9.09451 15.1089 7.54883 13.5632 7.54883 11.6578C7.54883 9.75247 9.09451 8.20679 10.9999 8.20679Z" class="tsv-icon-base-fill"/></symbol> <symbol id="i-viewer-small" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-viewer-small" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.62898 9.5406C1.19278 10.0043 0.949062 10.6167 0.949062 11.2529C0.945313 11.3479 0.945312 11.4441 0.945312 11.5366C0.945312 12.0453 1.10029 12.5415 1.38901 12.9602C2.55136 14.5725 5.90095 18.532 10.9441 18.532C15.9872 18.532 19.3368 14.5725 20.4941 12.9564C20.7828 12.539 20.9378 12.044 20.9378 11.5366C20.9428 11.4441 20.9428 11.3479 20.9428 11.2529C20.9428 10.6155 20.7004 10.0018 20.2629 9.53685C19.5592 8.80944 18.6681 7.97829 17.6282 7.22214C15.7772 5.87606 13.4675 4.78369 10.9441 4.78369C8.42063 4.78369 6.11092 5.87606 4.2599 7.22214C3.22003 7.97829 2.32889 8.80944 1.62898 9.5406ZM10.9441 7.28338C12.9201 7.28338 14.7086 8.19077 16.1572 9.24439C17.2083 10.008 18.0844 10.8579 18.7256 11.5566C19.1343 12.009 19.1555 12.0931 18.7768 12.5705C17.3733 14.2328 14.6849 16.685 10.9441 16.685C7.20328 16.685 4.51487 14.2328 3.11879 12.5643C2.74259 12.0906 2.76384 12.0115 3.16754 11.5616C3.80371 10.8579 4.67985 10.008 5.73097 9.24439C7.17954 8.19077 8.96807 7.28338 10.9441 7.28338Z" class="tsv-icon-base-fill"/><path fill-rule="evenodd" clip-rule="evenodd" d="M10.9999 8.20679C12.9052 8.20679 14.4509 9.75247 14.4509 11.6578C14.4509 13.5632 12.9052 15.1089 10.9999 15.1089C9.09451 15.1089 7.54883 13.5632 7.54883 11.6578C7.54883 9.75247 9.09451 8.20679 10.9999 8.20679Z" class="tsv-icon-base-fill"/></symbol>
<symbol id="i-visible" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-visible" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"><rect id="i-visible--visible" x="0" y="0" width="22" height="22" fill="none"/><path d="M3.547,8.806C3.198,9.177 3.003,9.667 3.003,10.176C3,10.252 3,10.329 3,10.403C3,10.81 3.124,11.207 3.355,11.542C4.285,12.832 6.965,16 11,16C15.035,16 17.715,12.832 18.641,11.539C18.872,11.205 18.996,10.809 18.996,10.403C19,10.329 19,10.252 19,10.176C19,9.666 18.806,9.175 18.456,8.803C17.893,8.221 17.18,7.556 16.348,6.951C14.867,5.874 13.019,5 11,5C8.981,5 7.133,5.874 5.652,6.951C4.82,7.556 4.107,8.221 3.547,8.806ZM11,7C12.581,7 14.012,7.726 15.171,8.569C16.012,9.18 16.713,9.86 17.226,10.419C17.553,10.781 17.57,11.326 17.267,11.708C16.144,13.038 13.993,15 11,15C8.007,15 5.856,13.038 4.739,11.703C4.438,11.324 4.455,10.783 4.778,10.423C5.287,9.86 5.988,9.18 6.829,8.569C7.988,7.726 9.419,7 11,7Z" class="tsv-icon-base-fill"/><g><path d="M11,7.805C12.764,7.805 14.195,9.236 14.195,11C14.195,12.764 12.764,14.195 11,14.195C9.236,14.195 7.805,12.764 7.805,11C7.805,9.236 9.236,7.805 11,7.805ZM10.5,9C11.328,9 12,9.672 12,10.5C12,11.328 11.328,12 10.5,12C9.672,12 9,11.328 9,10.5C9,9.672 9.672,9 10.5,9Z" class="tsv-icon-base-fill"/></g></symbol> <symbol id="i-visible" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-visible" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"><rect id="i-visible--visible" x="0" y="0" width="22" height="22" fill="none"/><path d="M3.547,8.806C3.198,9.177 3.003,9.667 3.003,10.176C3,10.252 3,10.329 3,10.403C3,10.81 3.124,11.207 3.355,11.542C4.285,12.832 6.965,16 11,16C15.035,16 17.715,12.832 18.641,11.539C18.872,11.205 18.996,10.809 18.996,10.403C19,10.329 19,10.252 19,10.176C19,9.666 18.806,9.175 18.456,8.803C17.893,8.221 17.18,7.556 16.348,6.951C14.867,5.874 13.019,5 11,5C8.981,5 7.133,5.874 5.652,6.951C4.82,7.556 4.107,8.221 3.547,8.806ZM11,7C12.581,7 14.012,7.726 15.171,8.569C16.012,9.18 16.713,9.86 17.226,10.419C17.553,10.781 17.57,11.326 17.267,11.708C16.144,13.038 13.993,15 11,15C8.007,15 5.856,13.038 4.739,11.703C4.438,11.324 4.455,10.783 4.778,10.423C5.287,9.86 5.988,9.18 6.829,8.569C7.988,7.726 9.419,7 11,7Z" class="tsv-icon-base-fill"/><g><path d="M11,7.805C12.764,7.805 14.195,9.236 14.195,11C14.195,12.764 12.764,14.195 11,14.195C9.236,14.195 7.805,12.764 7.805,11C7.805,9.236 9.236,7.805 11,7.805ZM10.5,9C11.328,9 12,9.672 12,10.5C12,11.328 11.328,12 10.5,12C9.672,12 9,11.328 9,10.5C9,9.672 9.672,9 10.5,9Z" class="tsv-icon-base-fill"/></g></symbol>
<symbol id="i-waiting" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-waiting" fill="none"><path d="M15.0764 18.0585C18.9747 15.8078 20.3104 10.823 18.0597 6.92461C15.809 3.02624 10.8241 1.69056 6.92578 3.94128" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/><path d="M15.0744 18.0587C11.1761 20.3094 6.19125 18.9737 3.94053 15.0753C1.68981 11.177 3.02548 6.19215 6.92385 3.94143" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 3" class="tsv-icon-base-stroke"/><path d="M11 6.1095V10.9998L14.2602 12.63" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/></symbol> <symbol id="i-waiting" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-waiting" fill="none"><path d="M15.0764 18.0585C18.9747 15.8078 20.3104 10.823 18.0597 6.92461C15.809 3.02624 10.8241 1.69056 6.92578 3.94128" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/><path d="M15.0744 18.0587C11.1761 20.3094 6.19125 18.9737 3.94053 15.0753C1.68981 11.177 3.02548 6.19215 6.92385 3.94143" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 3" class="tsv-icon-base-stroke"/><path d="M11 6.1095V10.9998L14.2602 12.63" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/></symbol>
<symbol id="i-connection-whispers" class="tsv-icon-connection-whispers" viewBox="0 0 22 22" shape-rendering="geometricPrecision" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"> <rect id="i-connection-whispers--connection_whispers" x="-0" y="0" width="22" height="22" fill="none"/> <path d="M21,3C21,1.896 20.104,1 19,1L3,1C1.896,1 1,1.896 1,3L1,19C1,20.104 1.896,21 3,21L19,21C20.104,21 21,20.104 21,19L21,3Z" class="tsv-icon-base-contrast-fill"/> <g> <path d="M14.765,13.157L12.664,13.157C14.122,12.211 14.122,9.685 12.434,8.825L14.535,8.825C15.355,10.105 15.576,11.797 14.765,13.157Z" class="tsv-icon-tint-fill" fill-rule="nonzero"/> <path d="M17.007,15.938L14.494,15.938C14.809,15.747 15.108,15.521 15.383,15.258C17.886,12.871 17.408,8.106 14.478,6.062L17.065,6.062C18.491,7.716 19.28,9.924 18.937,12.163C18.716,13.609 18.009,14.901 17.007,15.938Z" class="tsv-icon-tint-fill" fill-rule="nonzero"/> </g> <g> <path d="M3.66,16.092C3.581,16.039 3.507,15.978 3.439,15.91C3.164,15.636 3.01,15.263 3.01,14.875L3.01,14.874C3.01,13.78 3.445,12.73 4.219,11.956C4.574,11.601 4.986,11.318 5.435,11.115C7.006,12.222 9.25,12.323 10.704,11.171C11.107,11.369 11.478,11.633 11.801,11.956C12.575,12.73 13.01,13.78 13.01,14.874C13.01,14.874 13.01,14.875 13.01,14.875C13.01,15.263 12.856,15.636 12.581,15.91C12.513,15.978 12.439,16.039 12.36,16.092C11.14,16.985 9.636,17.513 8.01,17.513C6.384,17.513 4.88,16.985 3.66,16.092Z" class="tsv-icon-subtitle-fill"/> <ellipse cx="8.01" cy="7.539" rx="3.394" ry="3.6" class="tsv-icon-subtitle-fill"/> </g></symbol>
<symbol id="i-chat-contact" viewBox="0 0 23 23" shape-rendering="geometricPrecision" class="tsv-icon-chat-contact" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M20.6289 11.6531C20.6289 16.6236 16.5995 20.6531 11.6289 20.6531C6.65834 20.6531 2.62891 16.6236 2.62891 11.6531C2.62891 6.68251 6.65834 2.65308 11.6289 2.65308C16.5995 2.65308 20.6289 6.68251 20.6289 11.6531ZM7.16878 13.3811C7.75488 12.795 8.5498 12.4658 9.37866 12.4658H13.8792C14.708 12.4658 15.5029 12.795 16.089 13.3811C16.6751 13.9672 17.0044 14.7621 17.0044 15.591V16.7161C17.0044 17.1994 16.6126 17.5911 16.1294 17.5911C15.6461 17.5911 15.2544 17.1994 15.2544 16.7161V15.591C15.2544 15.2263 15.1095 14.8765 14.8516 14.6186C14.5937 14.3607 14.2439 14.2158 13.8792 14.2158H9.37866C9.01393 14.2158 8.66413 14.3607 8.40622 14.6186C8.14831 14.8765 8.00342 15.2263 8.00342 15.591V16.7161C8.00342 17.1994 7.61167 17.5911 7.12842 17.5911C6.64517 17.5911 6.25342 17.1994 6.25342 16.7161V15.591C6.25342 14.7621 6.58268 13.9672 7.16878 13.3811ZM10.2537 8.48752C10.2537 7.72799 10.8694 7.11227 11.6289 7.11227C12.3884 7.11227 13.0042 7.72799 13.0042 8.48752C13.0042 9.24704 12.3884 9.86276 11.6289 9.86276C10.8694 9.86276 10.2537 9.24704 10.2537 8.48752ZM11.6289 5.36227C9.90288 5.36227 8.50366 6.76149 8.50366 8.48752C8.50366 10.2135 9.90288 11.6128 11.6289 11.6128C13.3549 11.6128 14.7542 10.2135 14.7542 8.48752C14.7542 6.76149 13.3549 5.36227 11.6289 5.36227Z" class="tsv-icon-subtitle-fill"/></symbol>
<symbol id="i-whisper" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-whisper" fill="none"><path d="M13.6445 17.75V16.25C13.6445 15.4544 13.3285 14.6913 12.7659 14.1287C12.2032 13.5661 11.4402 13.25 10.6445 13.25H4.64453C3.84888 13.25 3.08582 13.5661 2.52321 14.1287C1.9606 14.6913 1.64453 15.4544 1.64453 16.25V17.75" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/><path d="M7.64453 10.25C9.30139 10.25 10.6445 8.90685 10.6445 7.25C10.6445 5.59315 9.30139 4.25 7.64453 4.25C5.98768 4.25 4.64453 5.59315 4.64453 7.25C4.64453 8.90685 5.98768 10.25 7.64453 10.25Z" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/><path d="M18.0905 4.33325C19.542 5.7921 20.3574 7.77045 20.3574 9.83325C20.3574 11.8961 19.542 13.8744 18.0905 15.3333M15.3574 7.07936C16.0832 7.80878 16.4909 8.79796 16.4909 9.82936C16.4909 10.8608 16.0832 11.8499 15.3574 12.5794" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/></symbol> <symbol id="i-whisper" viewBox="0 0 22 22" shape-rendering="geometricPrecision" class="tsv-icon-whisper" fill="none"><path d="M13.6445 17.75V16.25C13.6445 15.4544 13.3285 14.6913 12.7659 14.1287C12.2032 13.5661 11.4402 13.25 10.6445 13.25H4.64453C3.84888 13.25 3.08582 13.5661 2.52321 14.1287C1.9606 14.6913 1.64453 15.4544 1.64453 16.25V17.75" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/><path d="M7.64453 10.25C9.30139 10.25 10.6445 8.90685 10.6445 7.25C10.6445 5.59315 9.30139 4.25 7.64453 4.25C5.98768 4.25 4.64453 5.59315 4.64453 7.25C4.64453 8.90685 5.98768 10.25 7.64453 10.25Z" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/><path d="M18.0905 4.33325C19.542 5.7921 20.3574 7.77045 20.3574 9.83325C20.3574 11.8961 19.542 13.8744 18.0905 15.3333M15.3574 7.07936C16.0832 7.80878 16.4909 8.79796 16.4909 9.82936C16.4909 10.8608 16.0832 11.8499 15.3574 12.5794" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="tsv-icon-base-stroke"/></symbol>
<!-- Default client avatar: official ts-icon-stack composition (main.js @3162500, @10693354): ClientDetailed portrait + ClientDetailedPlaceholder under the ClientDetailedMask alpha mask, centred as the masked tsv-avatar layer. Talking ring = i-client-detailed-talking overlay. --> <!-- Default client avatar: official ts-icon-stack composition (main.js @3162500, @10693354): ClientDetailed portrait + ClientDetailedPlaceholder under the ClientDetailedMask alpha mask, centred as the masked tsv-avatar layer. Talking ring = i-client-detailed-talking overlay. -->
<symbol id="i-avatar" viewBox="0 0 51 33"><use href="#i-client-detailed"/><mask id="i-avatar--mask" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="51" height="33"><use href="#i-client-detailed-mask" x="9" width="33" height="33"/></mask><g mask="url(#i-avatar--mask)"><use href="#i-client-detailed-placeholder" x="9" width="33" height="33"/></g></symbol> <symbol id="i-avatar" viewBox="0 0 51 33"><use href="#i-client-detailed"/><mask id="i-avatar--mask" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="51" height="33"><use href="#i-client-detailed-mask" x="9" width="33" height="33"/></mask><g mask="url(#i-avatar--mask)"><use href="#i-client-detailed-placeholder" x="9" width="33" height="33"/></g></symbol>
@@ -331,7 +343,8 @@
<div class="servers-head"> <div class="servers-head">
<h2 id="servers-title" class="servers-title"><button id="servers-toggle" class="servers-toggle" type="button" aria-expanded="true" aria-controls="servers-content"><svg class="icon" aria-hidden="true"><use href="#i-bookmarks"/></svg><span data-i18n="ui.saved.servers">Saved servers</span></button></h2> <h2 id="servers-title" class="servers-title"><button id="servers-toggle" class="servers-toggle" type="button" aria-expanded="true" aria-controls="servers-content"><svg class="icon" aria-hidden="true"><use href="#i-bookmarks"/></svg><span data-i18n="ui.saved.servers">Saved servers</span></button></h2>
<button id="bookmarks-search" class="icon-btn" type="button" aria-label="Search / Connect" data-i18n-aria-label="ui.layout.search"><svg class="icon" aria-hidden="true"><use href="#i-search"/></svg></button> <button id="bookmarks-search" class="icon-btn" type="button" aria-label="Search / Connect" data-i18n-aria-label="ui.layout.search"><svg class="icon" aria-hidden="true"><use href="#i-search"/></svg></button>
<button id="servers-save-current" class="icon-btn" type="button" aria-label="Save current server"><svg class="icon" aria-hidden="true"><use href="#i-plus"/></svg></button> <button id="bookmarks-new-folder" class="icon-btn" type="button" aria-label="New Folder" data-i18n-aria-label="universal.folder.create.title" title="New Folder" data-i18n-title="universal.folder.create.title"><svg class="icon" aria-hidden="true"><use href="#i-folder-action"/></svg></button>
<button id="servers-save-current" class="icon-btn" type="button" aria-label="New Bookmark" data-i18n-aria-label="bookmarks.create.title" title="New Bookmark" data-i18n-title="bookmarks.create.title"><svg class="icon" aria-hidden="true"><use href="#i-plus"/></svg></button>
<svg class="icon servers-chevron" aria-hidden="true"><use href="#i-chevron-down"/></svg> <svg class="icon servers-chevron" aria-hidden="true"><use href="#i-chevron-down"/></svg>
</div> </div>
<div id="servers-content"> <div id="servers-content">
@@ -339,6 +352,7 @@
<div id="servers-empty" class="servers-empty"><p class="bookmarks-empty-title" data-i18n="bookmarks.empty">No Bookmarks</p><p data-i18n="ui.no.saved.servers.enter.an.address.in">Bookmark a server to easily reconnect with users on it</p></div> <div id="servers-empty" class="servers-empty"><p class="bookmarks-empty-title" data-i18n="bookmarks.empty">No Bookmarks</p><p data-i18n="ui.no.saved.servers.enter.an.address.in">Bookmark a server to easily reconnect with users on it</p></div>
</div> </div>
</section> </section>
<section id="contacts-panel" class="contacts-panel" aria-labelledby="contacts-title"></section>
<section id="conversations-panel" class="conversations-panel" aria-label="Chats" data-i18n-aria-label="ui.chats" hidden> <section id="conversations-panel" class="conversations-panel" aria-label="Chats" data-i18n-aria-label="ui.chats" hidden>
<div class="connections-head"><h2 class="connections-title" data-i18n="ui.chats">Chats</h2></div> <div class="connections-head"><h2 class="connections-title" data-i18n="ui.chats">Chats</h2></div>
<div id="chat-tabs" class="chat-tabs" role="tablist" aria-orientation="vertical" aria-label="Chats" data-i18n-aria-label="ui.chats"></div> <div id="chat-tabs" class="chat-tabs" role="tablist" aria-orientation="vertical" aria-label="Chats" data-i18n-aria-label="ui.chats"></div>
@@ -504,6 +518,7 @@
<div class="tsv-settings-category" role="group" aria-labelledby="settings-group-user"> <div class="tsv-settings-category" role="group" aria-labelledby="settings-group-user">
<div id="settings-group-user" class="nav-group-label" data-i18n="ui.user">User</div> <div id="settings-group-user" class="nav-group-label" data-i18n="ui.user">User</div>
<button class="nav-item" type="button" data-panel="identity"><svg class="icon" aria-hidden="true"><use href="#i-settings-identities"/></svg><span data-i18n="settings.nav.identities">Identities</span></button> <button class="nav-item" type="button" data-panel="identity"><svg class="icon" aria-hidden="true"><use href="#i-settings-identities"/></svg><span data-i18n="settings.nav.identities">Identities</span></button>
<button class="nav-item" type="button" data-panel="privacy"><svg class="icon" aria-hidden="true"><use href="#i-settings-privacy"/></svg><span data-i18n="settings.privacy.title">Privacy</span></button>
<button class="nav-item" type="button" data-panel="servers"><svg class="icon" aria-hidden="true"><use href="#i-bookmarks"/></svg><span data-i18n="ui.servers">Servers</span></button> <button class="nav-item" type="button" data-panel="servers"><svg class="icon" aria-hidden="true"><use href="#i-bookmarks"/></svg><span data-i18n="ui.servers">Servers</span></button>
</div> </div>
<div class="tsv-settings-category" role="group" aria-labelledby="settings-group-application"> <div class="tsv-settings-category" role="group" aria-labelledby="settings-group-application">
@@ -518,6 +533,10 @@
<button class="nav-item" type="button" data-panel="transfers"><svg class="icon" aria-hidden="true"><use href="#i-file-transfer"/></svg><span data-i18n="files.title">File Transfer</span></button> <button class="nav-item" type="button" data-panel="transfers"><svg class="icon" aria-hidden="true"><use href="#i-file-transfer"/></svg><span data-i18n="files.title">File Transfer</span></button>
<button class="nav-item" type="button" data-panel="os"><svg class="icon" aria-hidden="true"><use href="#i-settings-behavior"/></svg><span data-i18n="os.title">OS Specific</span></button> <button class="nav-item" type="button" data-panel="os"><svg class="icon" aria-hidden="true"><use href="#i-settings-behavior"/></svg><span data-i18n="os.title">OS Specific</span></button>
</div> </div>
<div class="tsv-settings-category" role="group" aria-labelledby="settings-group-extensions">
<div id="settings-group-extensions" class="nav-group-label" data-i18n="settings.categories.customization">Extensions</div>
<button class="nav-item" type="button" data-panel="remoteapps"><svg class="icon" aria-hidden="true"><use href="#i-settings-addons"/></svg><span data-i18n="settings.remote_apps.title">Remote Apps</span></button>
</div>
<div class="tsv-settings-category" role="group" aria-labelledby="settings-group-information"> <div class="tsv-settings-category" role="group" aria-labelledby="settings-group-information">
<div id="settings-group-information" class="nav-group-label" data-i18n="ui.information">Information</div> <div id="settings-group-information" class="nav-group-label" data-i18n="ui.information">Information</div>
<button class="nav-item" type="button" data-panel="about"><svg class="icon" aria-hidden="true"><use href="#i-mode-info"/></svg><span data-i18n="settings.nav.about">About</span></button> <button class="nav-item" type="button" data-panel="about"><svg class="icon" aria-hidden="true"><use href="#i-mode-info"/></svg><span data-i18n="settings.nav.about">About</span></button>
@@ -525,6 +544,8 @@
</nav> </nav>
<!-- page: .tsv-body.tsv-scroll-area.tsv-clearance > .tsv-readability.ts-widget-container > .ts-widget-wrapper… --> <!-- page: .tsv-body.tsv-scroll-area.tsv-clearance > .tsv-readability.ts-widget-container > .ts-widget-wrapper… -->
<div class="settings-scroll tsv-settings-subcategory"> <div class="settings-scroll tsv-settings-subcategory">
<div class="settings-panel" data-panel="privacy" hidden><h1 class="panel-title" data-i18n="settings.privacy.title">Privacy</h1><div id="privacy-settings"></div></div>
<div class="settings-panel" data-panel="remoteapps" hidden><h1 class="panel-title" data-i18n="settings.remote_apps.title">Remote Apps</h1></div>
<div class="settings-panel" data-panel="identity" hidden> <div class="settings-panel" data-panel="identity" hidden>
<h1 id="settings-title" class="panel-title" data-i18n="settings.nav.identities">Identities</h1> <h1 id="settings-title" class="panel-title" data-i18n="settings.nav.identities">Identities</h1>
<section class="ts-widget-wrapper" aria-labelledby="settings-identities-title"> <section class="ts-widget-wrapper" aria-labelledby="settings-identities-title">
@@ -749,6 +770,7 @@
<!-- About (render@1827639): header card (version, build rows) · Updates --> <!-- About (render@1827639): header card (version, build rows) · Updates -->
<div class="settings-panel" data-panel="about" hidden> <div class="settings-panel" data-panel="about" hidden>
<h1 class="panel-title" data-i18n="settings.nav.about">About</h1> <h1 class="panel-title" data-i18n="settings.nav.about">About</h1>
<div id="about-information"></div>
<section class="ts-widget-wrapper ts-about-settings" aria-labelledby="card-about"> <section class="ts-widget-wrapper ts-about-settings" aria-labelledby="card-about">
<div class="ts-widget-section-header"><h2 id="card-about" class="title" data-i18n="ui.about">About</h2></div> <div class="ts-widget-section-header"><h2 id="card-about" class="title" data-i18n="ui.about">About</h2></div>
<div class="ts-card ts-widget full"> <div class="ts-card ts-widget full">
+22 -1
View File
@@ -16,6 +16,9 @@ import { openServerSnapshots } from './server-snapshots.js';
import { joinChannel } from './tree.js'; import { joinChannel } from './tree.js';
import { openFileBrowser } from './files.js'; import { openFileBrowser } from './files.js';
import { menuPosition } from './menu-position.js'; import { menuPosition } from './menu-position.js';
import { confirmAction } from './confirmations.js';
import { badgeShowcase } from './badges.js';
import { openServerIcons } from './server-icons.js';
const L = (key, args) => t(`admin.${key}`, args); const L = (key, args) => t(`admin.${key}`, args);
let modal = null; // short popup forms (<dialog>) let modal = null; // short popup forms (<dialog>)
@@ -771,6 +774,17 @@ function transferCard(s, v, draw) {
h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftDownload')}: ` }), bytes(v.virtualserver_total_bytes_downloaded)), h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftDownload')}: ` }), bytes(v.virtualserver_total_bytes_downloaded)),
h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftUpload')}: ` }), bytes(v.virtualserver_total_bytes_uploaded))) : null); h('p', {}, h('span', { class: 'adm-unfocused', text: `${L('ftUpload')}: ` }), bytes(v.virtualserver_total_bytes_uploaded))) : null);
} }
function serverIconsPage(s) {
const tools = h('div', { class: 'adm-navbar-tools' });
const pageNo = subpage(s, 'icons', 'server-icons', [tools]);
s.reopen = () => serverIconsPage(s);
s.serverIcons?.close();
s.serverIcons = openServerIcons(s.conn.id, {
host: s.body, toolbar: tools,
onBack: () => { if (pane === s && s.page === pageNo) openPane(s.conn, 'server.info'); },
});
}
function manageCard(s) { function manageCard(s) {
const entry = ([key, iconName, fn, right]) => deny(h('button', { type: 'button', class: 'adm-link', onclick: guarded(s, fn) }, glyph(iconName), h('span', { text: L(key) })), s, right); const entry = ([key, iconName, fn, right]) => deny(h('button', { type: 'button', class: 'adm-link', onclick: guarded(s, fn) }, glyph(iconName), h('span', { text: L(key) })), s, right);
const official = [ const official = [
@@ -778,6 +792,7 @@ function manageCard(s) {
['bans', 'mode-server-bans', () => listPage(s, 'bans'), 'b_client_ban_list'], ['bans', 'mode-server-bans', () => listPage(s, 'bans'), 'b_client_ban_list'],
['keys', 'privilege-key', () => listPage(s, 'keys'), 'b_virtualserver_token_list'], ['keys', 'privilege-key', () => listPage(s, 'keys'), 'b_virtualserver_token_list'],
['passwords', 'lock-opened', () => listPage(s, 'passwords')], ['passwords', 'lock-opened', () => listPage(s, 'passwords')],
['icons', 'server-icons', () => serverIconsPage(s)],
['clients', 'groups', () => database(s), 'b_virtualserver_client_dblist'], ['clients', 'groups', () => database(s), 'b_virtualserver_client_dblist'],
['snapshots', 'settings-addons', () => openServerSnapshots(s.conn.id)], ['snapshots', 'settings-addons', () => openServerSnapshots(s.conn.id)],
]; ];
@@ -891,6 +906,7 @@ function clientInfo(s, id) {
h('p', { class: `adm-topic-text${text ? '' : ' is-empty'}`, text: text || L('noDescription') }))), h('p', { class: `adm-topic-text${text ? '' : ' is-empty'}`, text: text || L('noDescription') }))),
card('adm-full adm-deep adm-groups', h('h4', { text: L('groups') }), card('adm-full adm-deep adm-groups', h('h4', { text: L('groups') }),
groups.length ? h('div', { class: 'adm-group-list' }, ...groups) : h('p', { class: 'adm-empty-text', text: L('groupsEmpty') })), groups.length ? h('div', { class: 'adm-group-list' }, ...groups) : h('p', { class: 'adm-empty-text', text: L('groupsEmpty') })),
card('adm-full adm-deep adm-badges', h('h4', { text: t('client.info.badges.title') }), badgeShowcase(client.badges)),
gridItem('server-connect', Object.assign([[L('connected'), connected], [L('firstConnection'), date(v.client_created)]], { dim: true })), gridItem('server-connect', Object.assign([[L('connected'), connected], [L('firstConnection'), date(v.client_created)]], { dim: true })),
gridItem('globe', Object.assign([[L('location'), region(client.country ?? v.client_country)], [L('totalConnections'), total]], { dim: true }))), gridItem('globe', Object.assign([[L('location'), region(client.country ?? v.client_country)], [L('totalConnections'), total]], { dim: true }))),
h('p', { class: 'adm-footnote' }, h('span', { text: `${L('uidShort')}: ${client.uid}` }), h('br'), h('p', { class: 'adm-footnote' }, h('span', { text: `${L('uidShort')}: ${client.uid}` }), h('br'),
@@ -973,7 +989,12 @@ function listPage(s, kind) {
if (!rows.length) { data.append(emptyEntry(spec.empty)); return; } if (!rows.length) { data.append(emptyEntry(spec.empty)); return; }
for (const r of rows) { for (const r of rows) {
let args, command, target, entry; let args, command, target, entry;
const remove = () => iconButton('item-close', 'delete', guarded(s, () => popup(s, 'confirm', { command, args, titleKey: 'delete', target })), 'adm-destructive'); const remove = () => iconButton('item-close', 'delete', (event) => {
if (!alive(s) || s.busy) return;
const [key, subtitle] = { bans: ['delete_ban', 'server.banlist.delete.warning'], keys: ['delete_privilege_key', 'server.privilege_keys.delete.warning'], passwords: ['delete_temp_pw', 'server.temp_passwords.delete.confirm'] }[kind];
void confirmAction(event, key, t(subtitle), () => run(s, async () => { await request(s, command, args, true); s.reopen?.(); }),
{ onSaveError: (error) => setStatus(s, errorText(error), true) });
}, 'adm-destructive');
if (kind === 'bans') { if (kind === 'bans') {
target = r.banid; command = 'ban_delete'; args = { ban_id: Number(target), confirm: String(target) }; target = r.banid; command = 'ban_delete'; args = { ban_id: Number(target), confirm: String(target) };
const title = r.name || r.ip || r.uid || r.mytsid || String(target); const title = r.name || r.ip || r.uid || r.mytsid || String(target);
+22 -7
View File
@@ -31,16 +31,24 @@ import * as notifications from './notifications.js';
import * as osSettings from './os-settings.js'; import * as osSettings from './os-settings.js';
import { initFiles, renderFiles } from './files.js'; import { initFiles, renderFiles } from './files.js';
import * as userStyles from './user-styles.js'; import * as userStyles from './user-styles.js';
import { initConnectionsUi, renderConnections, connectionLabel } from './connections-ui.js'; import { initConnectionsUi, renderConnections as renderConnectionRows, connectionLabel } from './connections-ui.js';
import { initAdmin, renderChannelInfo } from './admin.js'; import { initAdmin, renderChannelInfo } from './admin.js';
import { initWhisper, setWhisperSelection } from './whisper.js'; import { initWhisper, setWhisperSelection, whisperHistoryButton } from './whisper.js';
import { initKeybinds } from './keybinds.js'; import { initKeybinds } from './keybinds.js';
import { focusIdentity } from './identities.js'; import { focusIdentity } from './identities.js';
import { initSelectControls } from './select-controls.js'; import { initSelectControls } from './select-controls.js';
import * as contacts from './contacts.js';
import { syncServerIcons } from './server-icons.js';
let hostBannerKey = null; let hostBannerKey = null;
let adminView = null; let adminView = null;
function renderConnections() {
renderConnectionRows();
contacts.renderContacts();
syncServerIcons();
}
/** Server-provided artwork decorates the server card, never a separate tree row. */ /** Server-provided artwork decorates the server card, never a separate tree row. */
function renderHostBanner() { function renderHostBanner() {
const img = $('#host-banner'); const img = $('#host-banner');
@@ -672,7 +680,7 @@ function resetConnection(conn, reason, reconnecting = false) {
$('#host-banner').removeAttribute('src'); $('#host-banner').removeAttribute('src');
} }
if (hadMic) { if (hadMic) {
voice.setPtt(false); voice.setPtt(false, 'reset');
restoreMicrophone(); restoreMicrophone();
} }
syncInput(); syncInput();
@@ -846,6 +854,13 @@ async function toggleAudio(key, scope = 'all') {
await setAudio(targets, { [key]: value }); await setAudio(targets, { [key]: value });
} }
/** Key bindings update every server and the defaults for connections opened later. */
async function setSelfAudio(key, value) {
const next = value === 'toggle' ? !audioDefaults[key] : Boolean(value);
audioDefaults[key] = next;
await setAudio(connectionList().filter((conn) => conn.core.status === 'ready'), { [key]: next });
}
async function setAudio(targets, change) { async function setAudio(targets, change) {
await Promise.all(targets.map(async (conn) => { await Promise.all(targets.map(async (conn) => {
try { try {
@@ -936,6 +951,7 @@ async function boot() {
useMicrophone: (id) => setInputConnection(connectionById(id)), useMicrophone: (id) => setInputConnection(connectionById(id)),
unread: (conn) => chat.unreadCount(conn), unread: (conn) => chat.unreadCount(conn),
}); });
contacts.initContacts({ host: $('#contacts-panel'), view: (id) => setViewed(id), changed: renderTree });
initTree({ initTree({
savePrefs, savePrefs,
contextClient: openClientMenu, contextClient: openClientMenu,
@@ -952,7 +968,6 @@ async function boot() {
savePrefs, savePrefs,
connectTo, connectTo,
onIdentityChanged: () => renderConnection(), onIdentityChanged: () => renderConnection(),
addServer: () => { openSettings('servers'); $('#server-add-address').focus(); },
}); });
initDeviceMenus({ openAudioSettings: () => openSettings('audio'), setAudioScope: (key, scope) => toggleAudio(key, scope) }); initDeviceMenus({ openAudioSettings: () => openSettings('audio'), setAudioScope: (key, scope) => toggleAudio(key, scope) });
initUpdates(); initUpdates();
@@ -981,15 +996,15 @@ async function boot() {
osSettings.initOsSettings(); osSettings.initOsSettings();
recording.initRecording(); recording.initRecording();
document.querySelector('.server-status-bar').append(h('div', { class: 'server-informative-buttons' }, document.querySelector('.server-status-bar').append(h('div', { class: 'server-informative-buttons' },
$('#btn-talk-power'), $('#recording-indicator'), connectionStatus, $('#server-events-btn'))); whisperHistoryButton(), $('#btn-talk-power'), $('#recording-indicator'), connectionStatus, $('#server-events-btn')));
initFiles(); initFiles();
on('chat-unread', renderConnections); on('chat-unread', renderConnections);
on('chat-selection', renderSessionHead); on('chat-selection', renderSessionHead);
on('appearance-changed', renderTree); on('appearance-changed', renderTree);
on('admin-view', (view) => { adminView = view; renderSessionHead(); }); on('admin-view', (view) => { adminView = view; renderSessionHead(); });
on('settings-panel', (name) => settings.showPanel(name)); on('settings-panel', (name) => settings.showPanel(name));
void initWhisper(); void initWhisper({ view: (id) => setViewed(id), changed: renderTree });
void initKeybinds(); void initKeybinds({ setSelfAudio, disconnect: (conn) => disconnect(conn) });
on('set-view', (name) => setView(name)); on('set-view', (name) => setView(name));
onLanguageChange(() => { onLanguageChange(() => {
renderConnections(); renderConnections();
+5 -2
View File
@@ -2,7 +2,7 @@
// detailed tree/chat are the official defaults (main.js appearance constructor @1299504). // detailed tree/chat are the official defaults (main.js appearance constructor @1299504).
import { S, emit } from './state.js'; import { S, emit } from './state.js';
import { tp } from './core.js'; import { tp } from './core.js';
import { h, icon } from './dom.js'; import { h, icon, formatTime } from './dom.js';
import { t, onLanguageChange } from './i18n.js'; import { t, onLanguageChange } from './i18n.js';
import { toast } from './toast.js'; import { toast } from './toast.js';
import { errorText } from './text.js'; import { errorText } from './text.js';
@@ -31,7 +31,10 @@ const CAPTIONS = Object.freeze({
let hosts = null; let hosts = null;
let saving = false; let saving = false;
const TREE_CONTROLS = [ const TREE_CONTROLS = [
// Official order (render@4863822): Show User Badges, Show Country Flags, Highlight Contacts, …
['showBadges', 'badges', true],
['showCountryFlags', 'flags', false], ['showCountryFlags', 'flags', false],
['highlightContacts', 'contact_highlight', true],
['showClientsBeforeChannels', 'clients_before_channels', true], ['showClientsBeforeChannels', 'clients_before_channels', true],
['showChannelBanners', 'channel.banner', true], ['showChannelBanners', 'channel.banner', true],
['showChannelBackground', 'channel.bg', true], ['showChannelBackground', 'channel.bg', true],
@@ -132,7 +135,7 @@ function chatPreview(value) {
const list = h('ul', { class: 'ts-style-preview ts-chat-preview', dataset: { preview: value } }); const list = h('ul', { class: 'ts-style-preview ts-chat-preview', dataset: { preview: value } });
const time = new Date(2026, 0, 1, 13, 36); const time = new Date(2026, 0, 1, 13, 36);
for (const [author, key] of [['Alex', 'settings.preview.chat.1'], ['Mira', 'settings.preview.chat.2']]) { for (const [author, key] of [['Alex', 'settings.preview.chat.1'], ['Mira', 'settings.preview.chat.2']]) {
const stamp = () => h('time', { class: 'msg-time', text: time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }); const stamp = () => h('time', { class: 'msg-time', text: formatTime(time) });
const inline = stamp(); inline.classList.add('msg-inline-time'); const inline = stamp(); inline.classList.add('msg-inline-time');
list.append(h('li', { class: 'msg', dataset: { head: 'true', own: 'false' } }, list.append(h('li', { class: 'msg', dataset: { head: 'true', own: 'false' } },
h('div', { class: 'msg-head' }, h('span', { class: 'msg-author', text: author }), stamp()), inline, h('div', { class: 'msg-head' }, h('span', { class: 'msg-author', text: author }), stamp()), inline,
+128 -17
View File
@@ -1,15 +1,33 @@
// Microphone → 20 ms frames of 960 signed 16-bit mono samples at 48 kHz (bridge §4.9). // Microphone → 20 ms frames of 960 signed 16-bit mono samples at 48 kHz (bridge §4.9).
//
// Noise reduction: processorOptions.denoise = { module, level } carries the WebAssembly.Module the
// renderer compiled from the local denoise.wasm (WebRTC-derived sonora noise suppressor, fullband 48 kHz
// through its three-band split/merge) and the official denoiser level 0..3. It runs on 10 ms blocks of
// 480 samples; two blocks make one frame, so a frame still completes at the same input sample — and
// carries the same capture timestamp — as without it. The suppressor itself delays the audio by a fixed
// ≈6.5 ms (312 samples), in order, one sample out per sample in. Without the option the clamped input is
// quantized unchanged. Any denoiser failure posts a fatal error and no further frames: the microphone is
// never sent unprocessed while noise reduction is selected.
//
// WASM ABI (dsp/src/lib.rs): dsp_new(level) → handle, 0 on failure; dsp_input(handle) → byte offset of the
// handle's 480 f32 in/out block (stable for the handle's life); dsp_process(handle) → 0 when the block was
// processed in place; dsp_reset(handle, level) → 0 when all state was cleared (block zeroed); dsp_free(handle).
// Samples are normalized [-1, 1] both ways. Memory grows only in dsp_new/dsp_reset, so the block view is
// re-created after both; dsp_process never allocates.
const FRAME = 960; const FRAME = 960;
const BLOCK = 480;
const TYPING_GAIN = 10 ** (-18 / 20); const TYPING_GAIN = 10 ** (-18 / 20);
class CaptureProcessor extends AudioWorkletProcessor { class CaptureProcessor extends AudioWorkletProcessor {
constructor() { constructor(options) {
super(); super();
this.frame = new Int16Array(FRAME); this.frame = new Int16Array(FRAME);
this.pos = 0; this.pos = 0;
this.sumSq = 0; this.sumSq = 0;
this.peak = 0; this.peak = 0;
this.stopped = false; this.stopped = false;
this.failed = false;
this.denoise = null;
// Hints come only from application key events; this processor never observes global keys. // Hints come only from application key events; this processor never observes global keys.
this.typingEnabled = false; this.typingEnabled = false;
this.typingGain = 1; this.typingGain = 1;
@@ -29,13 +47,76 @@ class CaptureProcessor extends AudioWorkletProcessor {
} }
} else if (data?.type === 'typing-hit' && this.typingEnabled) { } else if (data?.type === 'typing-hit' && this.typingEnabled) {
this.typingRemaining = this.typingAttackSamples + this.typingHoldSamples; this.typingRemaining = this.typingAttackSamples + this.typingHoldSamples;
} else if (data?.type === 'denoise-level') {
this.setDenoiseLevel(data.level);
} }
}; };
if (sampleRate !== 48000) this.port.postMessage({ type: 'error', message: `sample rate ${sampleRate}` }); const denoise = options?.processorOptions?.denoise;
if (denoise) {
this.startDenoise(denoise);
if (!this.failed) this.port.postMessage({ type: 'ready' });
} else if (sampleRate !== 48000) {
this.port.postMessage({ type: 'error', message: `sample rate ${sampleRate}` });
}
}
startDenoise({ module, level }) {
try {
if (sampleRate !== 48000) throw new Error(`sample rate ${sampleRate}`);
if (!Number.isInteger(level) || level < 0 || level > 3) throw new Error(`invalid level ${level}`);
const exports = new WebAssembly.Instance(module, {}).exports;
const handle = exports.dsp_new(level);
if (!handle) throw new Error('dsp_new failed');
this.denoise = { exports, handle, level, block: null, pos: 0, hold: new Float32Array(BLOCK) };
this.viewDenoiseBlock();
} catch (err) {
this.fail(`Noise reduction could not start: ${err.message}`);
}
}
viewDenoiseBlock() {
const d = this.denoise;
const offset = d.exports.dsp_input(d.handle);
if (!offset) throw new Error('dsp_input failed');
d.block = new Float32Array(d.exports.memory.buffer, offset, BLOCK);
}
/** A level change clears the suppressor state; samples already gathered for the next block are kept. */
setDenoiseLevel(level) {
const d = this.denoise;
if (!d || this.failed || level === d.level) return;
try {
if (!Number.isInteger(level) || level < 0 || level > 3) throw new Error(`invalid level ${level}`);
d.hold.set(d.block.subarray(0, d.pos));
const status = d.exports.dsp_reset(d.handle, level);
if (status !== 0) throw new Error(`dsp_reset status ${status}`);
d.level = level;
this.viewDenoiseBlock();
d.block.set(d.hold.subarray(0, d.pos));
} catch (err) {
this.fail(`Noise reduction failed: ${err.message}`);
}
}
releaseDenoise() {
const d = this.denoise;
this.denoise = null;
try {
d?.exports.dsp_free(d.handle);
} catch {
// the instance is discarded with this processor either way
}
}
fail(message) {
this.failed = true;
this.releaseDenoise();
this.port.postMessage({ type: 'error', fatal: true, message });
} }
process(inputs, outputs) { process(inputs, outputs) {
if (this.stopped) { if (this.stopped) {
this.releaseDenoise();
this.port.postMessage({ type: 'stopped' }); this.port.postMessage({ type: 'stopped' });
this.port.close(); this.port.close();
return false; return false;
@@ -43,8 +124,9 @@ class CaptureProcessor extends AudioWorkletProcessor {
const input = inputs[0]; const input = inputs[0];
const out = outputs[0] && outputs[0][0]; const out = outputs[0] && outputs[0][0];
if (out) out.fill(0); if (out) out.fill(0);
if (!input || input.length === 0) return true; if (this.failed || !input || input.length === 0) return true;
const ch = input[0]; const ch = input[0];
const d = this.denoise;
for (let i = 0; i < ch.length; i += 1) { for (let i = 0; i < ch.length; i += 1) {
let s = ch[i]; let s = ch[i];
if (s > 1) s = 1; if (s > 1) s = 1;
@@ -58,24 +140,53 @@ class CaptureProcessor extends AudioWorkletProcessor {
} }
s *= this.typingGain; s *= this.typingGain;
} }
this.frame[this.pos] = s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7fff); if (d === null) {
this.pos += 1; this.emit(s, i);
this.sumSq += s * s; continue;
const a = s < 0 ? -s : s; }
if (a > this.peak) this.peak = a; d.block[d.pos] = s === s ? s : 0; // NaN quantizes to 0 without the denoiser too
if (this.pos === FRAME) { d.pos += 1;
const pcm = this.frame.buffer; if (d.pos === BLOCK) {
// Timestamp in this capture context's sample clock, not wall time or the playback clock. d.pos = 0;
const capturedAt = (currentFrame + i + 1) / sampleRate; let status;
this.port.postMessage({ type: 'frame', pcm, rms: Math.sqrt(this.sumSq / FRAME), peak: this.peak, capturedAt }, [pcm]); try {
this.frame = new Int16Array(FRAME); status = d.exports.dsp_process(d.handle);
this.pos = 0; } catch (err) {
this.sumSq = 0; this.fail(`Noise reduction failed: ${err.message}`);
this.peak = 0; return true;
}
if (status !== 0) {
this.fail(`Noise reduction failed: dsp_process status ${status}`);
return true;
}
const block = d.block;
for (let k = 0; k < BLOCK; k += 1) this.emit(block[k], i);
} }
} }
return true; return true;
} }
/** Quantizes one sample into the frame; `i` is the input sample index of this render quantum. */
emit(sample, i) {
let s = sample;
if (s > 1) s = 1;
else if (s < -1) s = -1;
this.frame[this.pos] = s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7fff);
this.pos += 1;
this.sumSq += s * s;
const a = s < 0 ? -s : s;
if (a > this.peak) this.peak = a;
if (this.pos === FRAME) {
const pcm = this.frame.buffer;
// Timestamp in this capture context's sample clock, not wall time or the playback clock.
const capturedAt = (currentFrame + i + 1) / sampleRate;
this.port.postMessage({ type: 'frame', pcm, rms: Math.sqrt(this.sumSq / FRAME), peak: this.peak, capturedAt }, [pcm]);
this.frame = new Int16Array(FRAME);
this.pos = 0;
this.sumSq = 0;
this.peak = 0;
}
}
} }
registerProcessor('tp-capture', CaptureProcessor); registerProcessor('tp-capture', CaptureProcessor);
+103 -10
View File
@@ -3,6 +3,34 @@
// their context is closed. // their context is closed.
import { dbToGain } from './fader.js'; import { dbToGain } from './fader.js';
const DENOISE_URL = new URL('../../assets/audio/denoise.wasm', import.meta.url);
const DENOISE_EXPORTS = { memory: 'memory', dsp_new: 'function', dsp_input: 'function', dsp_process: 'function', dsp_reset: 'function', dsp_free: 'function' };
/** Fixed algorithmic delay of the noise suppressor (312 samples at 48 kHz, see capture-worklet.js). */
export const DENOISE_DELAY = 312 / 48000;
const PROCESSOR_READY_TIMEOUT_MS = 5000;
let denoiseModule = null;
/**
* Compiles the bundled denoise.wasm once, on the renderer thread: an AudioWorklet cannot fetch, so the
* compiled module is handed to the capture processor. A failure is not cached; the next capture retries.
*/
export function loadDenoiseModule() {
denoiseModule ??= (async () => {
const response = await fetch(DENOISE_URL);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const module = await WebAssembly.compile(await response.arrayBuffer());
const exports = new Map(WebAssembly.Module.exports(module).map(({ name, kind }) => [name, kind]));
const missing = Object.entries(DENOISE_EXPORTS).filter(([name, kind]) => exports.get(name) !== kind).map(([name]) => name);
if (missing.length) throw new Error(`missing exports ${missing.join(', ')}`);
if (WebAssembly.Module.imports(module).length) throw new Error('the module must not import anything');
return module;
})().catch((err) => {
denoiseModule = null;
throw Object.assign(new Error(`Noise reduction is unavailable: ${err.message}`), { code: 'denoise_unavailable' });
});
return denoiseModule;
}
export class AudioEngine { export class AudioEngine {
constructor({ onFrame, onError, log }) { constructor({ onFrame, onError, log }) {
this.onFrame = onFrame; this.onFrame = onFrame;
@@ -16,6 +44,7 @@ export class AudioEngine {
this.playbackEnabled = false; this.playbackEnabled = false;
this.transmitting = false; this.transmitting = false;
this.typingEnabled = false; this.typingEnabled = false;
this.denoiseLevel = null; // official denoiser level 0..3 of the current capture request, null = off
this.captureBoundary = 0; this.captureBoundary = 0;
this.outputDeviceId = ''; this.outputDeviceId = '';
this.capture = null; this.capture = null;
@@ -134,8 +163,24 @@ export class AudioEngine {
typingHit() { if (this.typingEnabled) this.capture?.node.port.postMessage({ type: 'typing-hit' }); } typingHit() { if (this.typingEnabled) this.capture?.node.port.postMessage({ type: 'typing-hit' }); }
// A capture-clock boundary rejects PCM already queued before a route/PTT/privacy transition. /**
discardCapturedFrames() { this.captureBoundary = this.capture ? this.capture.ctx.currentTime + 0.02 : 0; } * Live level change of the running noise reduction; the processor resets its suppressor state.
* Switching noise reduction on or off needs a capture restart (the processor is built for one mode).
*/
setDenoiseLevel(level) {
this.denoiseLevel = level;
const c = this.capture;
if (!c || c.denoiseLevel === null || level === null || level === c.denoiseLevel) return;
c.denoiseLevel = level;
c.node.port.postMessage({ type: 'denoise-level', level });
}
// A capture-clock boundary rejects PCM already queued before a route/PTT/privacy transition: one frame,
// plus the noise suppressor's delay, during which its output still carries pre-boundary input.
discardCapturedFrames() {
const c = this.capture;
this.captureBoundary = c ? c.ctx.currentTime + 0.02 + (c.denoiseLevel === null ? 0 : DENOISE_DELAY) : 0;
}
async setOutputDevice(deviceId) { async setOutputDevice(deviceId) {
this.stopDeviceTestPlayback(); this.stopDeviceTestPlayback();
@@ -200,17 +245,26 @@ export class AudioEngine {
return this.startingGen !== null; return this.startingGen !== null;
} }
/** Whether the running capture was built with noise reduction (switching it needs a restart). */
get captureDenoising() {
return this.capture !== null && this.capture.denoiseLevel !== null;
}
/** /**
* Opens the microphone. Every later startCapture() or stopCapture() supersedes a pending call: when * Opens the microphone. Every later startCapture() or stopCapture() supersedes a pending call: when
* getUserMedia resolves for a superseded call its tracks are stopped at once and null is returned, so a * getUserMedia resolves for a superseded call its tracks are stopped at once and null is returned, so a
* disconnect or a closed mic test during the permission/device wait never leaves a microphone open. * disconnect or a closed mic test during the permission/device wait never leaves a microphone open.
* `denoiseLevel` (0..3, null = off) selects TeamsPeach's noise reduction; Chromium's own noise
* suppression is always off, so the voice is never suppressed twice nor by a different algorithm.
* A noise reduction that cannot load or start fails the capture: the microphone is never sent unprocessed.
*/ */
async startCapture({ deviceId, echoCancellation, noiseSuppression, autoGainControl }) { async startCapture({ deviceId, echoCancellation, autoGainControl, denoiseLevel = null }) {
const gen = ++this.captureGen; const gen = ++this.captureGen;
this.startingGen = gen; this.startingGen = gen;
this.denoiseLevel = denoiseLevel;
this.releaseCapture(); this.releaseCapture();
try { try {
return await this.openCapture(gen, { deviceId, echoCancellation, noiseSuppression, autoGainControl }); return await this.openCapture(gen, { deviceId, echoCancellation, autoGainControl, denoiseLevel });
} catch (err) { } catch (err) {
if (gen !== this.captureGen) return null; // superseded: the failure no longer matters if (gen !== this.captureGen) return null; // superseded: the failure no longer matters
throw err; throw err;
@@ -219,7 +273,7 @@ export class AudioEngine {
} }
} }
async openCapture(gen, { deviceId, echoCancellation, noiseSuppression, autoGainControl }) { async openCapture(gen, { deviceId, echoCancellation, autoGainControl, denoiseLevel }) {
await this.init(); await this.init();
await this.captureClosing; await this.captureClosing;
if (gen !== this.captureGen) return null; if (gen !== this.captureGen) return null;
@@ -229,10 +283,13 @@ export class AudioEngine {
if (gen !== this.captureGen) return null; if (gen !== this.captureGen) return null;
if (this.failedCaptureContext) throw this.captureCloseError; if (this.failedCaptureContext) throw this.captureCloseError;
} }
// Before the microphone opens: a missing or invalid module never leaves it open.
const denoiseModule = denoiseLevel === null ? null : await loadDenoiseModule();
if (gen !== this.captureGen) return null;
const audio = { const audio = {
channelCount: 1, channelCount: 1,
echoCancellation, echoCancellation,
noiseSuppression, noiseSuppression: false,
autoGainControl, autoGainControl,
}; };
if (deviceId) audio.deviceId = { exact: deviceId }; if (deviceId) audio.deviceId = { exact: deviceId };
@@ -255,13 +312,17 @@ export class AudioEngine {
let sink = null; let sink = null;
let ctx = null; let ctx = null;
let processorErrorHandler = null; let processorErrorHandler = null;
let ready = null; // pending noise-reduction start: the processor answers 'ready' or a fatal error
let level = null;
try { try {
ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' }); ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
this.openingCapture = { stream, ctx }; const opening = { stream, ctx, cancel: null };
this.openingCapture = opening;
await ctx.audioWorklet.addModule(new URL('./capture-worklet.js', import.meta.url)); await ctx.audioWorklet.addModule(new URL('./capture-worklet.js', import.meta.url));
if (gen !== this.captureGen) return null; if (gen !== this.captureGen) return null;
if (ctx.state !== 'running') await ctx.resume(); if (ctx.state !== 'running') await ctx.resume();
if (gen !== this.captureGen) return null; if (gen !== this.captureGen) return null;
level = denoiseModule ? (this.denoiseLevel ?? denoiseLevel) : null;
source = ctx.createMediaStreamSource(stream); source = ctx.createMediaStreamSource(stream);
node = new AudioWorkletNode(ctx, 'tp-capture', { node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1, numberOfInputs: 1,
@@ -270,6 +331,7 @@ export class AudioEngine {
channelCount: 1, channelCount: 1,
channelCountMode: 'explicit', channelCountMode: 'explicit',
channelInterpretation: 'speakers', channelInterpretation: 'speakers',
processorOptions: denoiseModule ? { denoise: { module: denoiseModule, level } } : {},
}); });
sink = ctx.createGain(); sink = ctx.createGain();
sink.gain.value = 0; sink.gain.value = 0;
@@ -286,15 +348,43 @@ export class AudioEngine {
return; return;
} }
this.onFrame(data.pcm, data.rms, data.peak); this.onFrame(data.pcm, data.rms, data.peak);
} else if (data.type === 'ready') {
ready?.resolve();
} else if (data.type === 'error') {
if (!data.fatal) this.onError({ code: 'capture', message: data.message });
else if (ready) ready.reject(new Error(data.message));
else if (this.capture?.node === node) {
// The processor stopped emitting frames; release the microphone and report it.
this.stopCapture();
this.onError({ code: 'capture', message: data.message });
}
} }
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
}; };
processorErrorHandler = () => { processorErrorHandler = () => {
if (ready) {
ready.reject(new Error('Microphone audio processor failed'));
return;
}
if (this.capture?.node !== node) return; if (this.capture?.node !== node) return;
this.stopCapture(); this.stopCapture();
this.onError({ code: 'capture', message: 'Microphone audio processor failed' }); this.onError({ code: 'capture', message: 'Microphone audio processor failed' });
}; };
node.addEventListener('processorerror', processorErrorHandler, { once: true }); node.addEventListener('processorerror', processorErrorHandler, { once: true });
if (denoiseModule) {
await new Promise((resolve, reject) => {
let timer = 0;
const settle = (done, value) => { clearTimeout(timer); ready = null; opening.cancel = null; done(value); };
ready = { resolve: () => settle(resolve), reject: (err) => settle(reject, err) };
opening.cancel = ready.resolve; // superseded: stop waiting, the context is being closed
timer = setTimeout(() => ready?.reject(new Error('Noise reduction did not start')), PROCESSOR_READY_TIMEOUT_MS);
});
if (gen !== this.captureGen) {
node.removeEventListener('processorerror', processorErrorHandler);
node.port.onmessage = null;
node.port.close();
return null;
}
}
source.connect(node).connect(sink).connect(ctx.destination); source.connect(node).connect(sink).connect(ctx.destination);
} catch (err) { } catch (err) {
// The microphone is already open: release it and whatever was built before rethrowing. // The microphone is already open: release it and whatever was built before rethrowing.
@@ -326,9 +416,11 @@ export class AudioEngine {
const onUnmute = () => this.log('info', 'audio: capture track unmuted'); const onUnmute = () => this.log('info', 'audio: capture track unmuted');
const trackHandlers = { ended: onEnded, mute: onMute, unmute: onUnmute }; const trackHandlers = { ended: onEnded, mute: onMute, unmute: onUnmute };
for (const [event, handler] of Object.entries(trackHandlers)) track.addEventListener(event, handler); for (const [event, handler] of Object.entries(trackHandlers)) track.addEventListener(event, handler);
this.capture = { ctx, stream, source, node, sink, track, trackHandlers, processorErrorHandler, label: track ? track.label : '' }; this.capture = { ctx, stream, source, node, sink, track, trackHandlers, processorErrorHandler, denoiseLevel: level, label: track ? track.label : '' };
const settings = track ? track.getSettings() : {}; const settings = track ? track.getSettings() : {};
this.log('info', `audio: capture started "${track ? track.label : '?'}" ${settings.sampleRate ?? '?'} Hz, ${settings.channelCount ?? '?'} ch, muted=${track ? track.muted : '?'}, ec=${settings.echoCancellation} ns=${settings.noiseSuppression} agc=${settings.autoGainControl}`); this.log('info', `audio: capture started "${track ? track.label : '?'}" ${settings.sampleRate ?? '?'} Hz, ${settings.channelCount ?? '?'} ch, muted=${track ? track.muted : '?'}, ec=${settings.echoCancellation} ns=${settings.noiseSuppression} agc=${settings.autoGainControl} denoise=${level ?? 'off'}`);
// A level chosen while this capture was starting.
this.setDenoiseLevel(this.denoiseLevel);
return this.capture.label; return this.capture.label;
} }
@@ -343,6 +435,7 @@ export class AudioEngine {
const opening = this.openingCapture; const opening = this.openingCapture;
this.openingCapture = null; this.openingCapture = null;
if (opening) { if (opening) {
opening.cancel?.();
for (const track of opening.stream.getTracks()) track.stop(); for (const track of opening.stream.getTracks()) track.stop();
this.captureClosing = this.closeCaptureContext(opening.ctx); this.captureClosing = this.closeCaptureContext(opening.ctx);
} }
+87 -10
View File
@@ -5,11 +5,23 @@
// 'none' — never play, any other value — that output device id. // 'none' — never play, any other value — that output device id.
// Level is a dB modifier on the official fader (default -23 dB). The context is created on the first // Level is a dB modifier on the official fader (default -23 dB). The context is created on the first
// sound and closed again after IDLE_MS without sounds, so no output stream stays open while idle. // sound and closed again after IDLE_MS without sounds, so no output stream stays open while idle.
//
// Sounds are files of the renderer's own assets/sounds folder (official native playWaveFile(name) → sound pack
// "default"), fetched from the app's read-only scheme only, never remote. The bytes are untrusted input: capped at
// MAX_FILE_BYTES while reading, decoded by Chromium's own decoder in an OfflineAudioContext (no output device),
// and the result checked (1–2 channels, at most MAX_SECONDS). Decoded buffers live in a least-recently-used
// cache bounded to CACHE_BYTES; failures are not cached.
import { dbToGain } from './fader.js'; import { dbToGain } from './fader.js';
const IDLE_MS = 15000; const IDLE_MS = 15000;
const MAX_SECONDS = 10; const MAX_SECONDS = 10;
const MAX_ACTIVE = 4; const MAX_ACTIVE = 4;
const SAMPLE_RATE = 48000;
const SOUND_DIR = new URL('../../assets/sounds/', import.meta.url);
const SOUND_NAME = /^[a-z][a-z_]{0,63}$/;
const MAX_FILE_BYTES = 1024 * 1024;
const MAX_CHANNELS = 2;
const CACHE_BYTES = 8 * 1024 * 1024;
const config = { deviceId: 'voice', levelDb: -23, voiceDeviceId: '' }; const config = { deviceId: 'voice', levelDb: -23, voiceDeviceId: '' };
let ctx = null; let ctx = null;
@@ -22,6 +34,13 @@ let revision = 0;
let preparing = Promise.resolve(); let preparing = Promise.resolve();
const sources = new Set(); const sources = new Set();
/** name → {buffer, size}; Map order is the LRU order (oldest first). */
const cache = new Map();
let cachedBytes = 0;
/** name → in-flight load, so concurrent requests decode a file once. */
const loading = new Map();
let decoder = null;
/** Effective sink for the current config, or null for 'none'. */ /** Effective sink for the current config, or null for 'none'. */
export function notificationSink(c = config) { export function notificationSink(c = config) {
if (c.deviceId === 'none') return null; if (c.deviceId === 'none') return null;
@@ -71,26 +90,84 @@ function scheduleIdleClose() {
}, IDLE_MS); }, IDLE_MS);
} }
async function readCapped(name) {
const response = await fetch(new URL(`${name}.wav`, SOUND_DIR));
if (!response.ok) throw new Error(`sound ${name}: HTTP ${response.status}`);
if (Number(response.headers.get('content-length')) > MAX_FILE_BYTES) throw new Error(`sound ${name}: file too large`);
const reader = response.body.getReader();
const chunks = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > MAX_FILE_BYTES) {
reader.cancel().catch(() => {});
throw new Error(`sound ${name}: file too large`);
}
chunks.push(value);
}
if (total === 0) throw new Error(`sound ${name}: empty file`);
const bytes = new Uint8Array(total);
let at = 0;
for (const chunk of chunks) { bytes.set(chunk, at); at += chunk.byteLength; }
return bytes.buffer;
}
async function decodeSound(name) {
const bytes = await readCapped(name);
decoder ??= new OfflineAudioContext(1, 1, SAMPLE_RATE);
const buffer = await decoder.decodeAudioData(bytes);
if (buffer.numberOfChannels < 1 || buffer.numberOfChannels > MAX_CHANNELS || buffer.length === 0 || buffer.duration > MAX_SECONDS) {
throw new Error(`sound ${name}: ${buffer.numberOfChannels} channels, ${buffer.duration} s`);
}
return buffer;
}
function remember(name, buffer) {
const size = buffer.length * buffer.numberOfChannels * 4;
cache.set(name, { buffer, size });
cachedBytes += size;
for (const [key, entry] of cache) {
if (cachedBytes <= CACHE_BYTES || key === name) break;
cache.delete(key);
cachedBytes -= entry.size;
}
}
/** Decoded sound `name`, from the cache or loaded once (concurrent callers share the load). */
function soundBuffer(name) {
const hit = cache.get(name);
if (hit) {
cache.delete(name);
cache.set(name, hit);
return Promise.resolve(hit.buffer);
}
let job = loading.get(name);
if (!job) {
job = decodeSound(name).then((buffer) => { remember(name, buffer); return buffer; }).finally(() => loading.delete(name));
loading.set(name, job);
}
return job;
}
/** /**
* Plays one notification sound. Resolves true once it started, false when not played: device 'none', * Plays notification sound file `name` (assets/sounds/<name>.wav). Resolves true once it started, false when not
* level at silence, too many sounds at once, or the device/context failed (logged). * played: device 'none', level at silence, too many sounds at once, or the file/decoder/device failed (logged).
* @param {{pcm: Float32Array, sampleRate: number}} sound mono samples in [-1, 1]
*/ */
export async function playNotification({ pcm, sampleRate } = {}) { export async function playNotificationSound(name) {
const sink = notificationSink(); const sink = notificationSink();
if (sink === null || config.levelDb <= -200) return false; if (sink === null || config.levelDb <= -200) return false;
if (!(pcm instanceof Float32Array) || pcm.length === 0 || !(sampleRate >= 8000 && sampleRate <= 96000)) return false; if (typeof name !== 'string' || !SOUND_NAME.test(name) || active >= MAX_ACTIVE) return false;
if (pcm.length > sampleRate * MAX_SECONDS || active >= MAX_ACTIVE) return false;
clearTimeout(idleTimer); clearTimeout(idleTimer);
active += 1; active += 1;
const expected = revision; const expected = revision;
try { try {
const buffer = await soundBuffer(name);
// Serialize sink changes; two concurrent sounds must not race one another onto another device. // Serialize sink changes; two concurrent sounds must not race one another onto another device.
preparing = preparing.catch(() => {}).then(() => ensureContext(sink)); preparing = preparing.catch(() => {}).then(() => ensureContext(sink));
await preparing; await preparing;
if (expected !== revision || sink !== notificationSink()) { active -= 1; if (active === 0) scheduleIdleClose(); return false; } if (expected !== revision || sink !== notificationSink()) { active -= 1; if (active === 0) scheduleIdleClose(); return false; }
const buffer = ctx.createBuffer(1, pcm.length, sampleRate);
buffer.copyToChannel(pcm, 0);
const source = ctx.createBufferSource(); const source = ctx.createBufferSource();
source.buffer = buffer; source.buffer = buffer;
source.connect(gain); source.connect(gain);
@@ -111,7 +188,7 @@ export async function playNotification({ pcm, sampleRate } = {}) {
} }
} }
/** Diagnostics: whether a notification context is open and its sink. */ /** Diagnostics: whether a notification context is open, its sink and the decoded-sound cache. */
export function notificationOutputState() { export function notificationOutputState() {
return { open: Boolean(ctx && ctx.state !== 'closed'), sinkId, active, ...config }; return { open: Boolean(ctx && ctx.state !== 'closed'), sinkId, active, cachedSounds: cache.size, cachedBytes, ...config };
} }
+5
View File
@@ -9,6 +9,11 @@ export function updateDeviceProfile(prefs, direction, patch) {
const id = prefs[direction === 'input' ? 'inputDeviceId' : 'outputDeviceId'] || 'default'; const id = prefs[direction === 'input' ? 'inputDeviceId' : 'outputDeviceId'] || 'default';
return { [key]: { template: { ...prefs[key].template }, devices: { ...prefs[key].devices, [id]: { ...deviceProfile(prefs, direction), ...patch } } } }; return { [key]: { template: { ...prefs[key].template }, devices: { ...prefs[key].devices, [id]: { ...deviceProfile(prefs, direction), ...patch } } } };
} }
/** Official denoiser level 0..3 of the capture device's profile, or null while noise reduction is off. */
export function captureDenoiseLevel(prefs) {
const input = deviceProfile(prefs, 'input');
return input.denoise ? input.denoiseLevel : null;
}
export function transmitConfig(prefs) { export function transmitConfig(prefs) {
const input = deviceProfile(prefs, 'input'); const input = deviceProfile(prefs, 'input');
if (!input.vad) return { mode: 'direct' }; if (!input.vad) return { mode: 'direct' };
+24
View File
@@ -0,0 +1,24 @@
// Client badge string parsing (pure). The core passes `client_badges` through unparsed (snapshot `badges`,
// docs/bridge.md); legacy TeamSpeak clients publish it as `key=value` pairs separated by ':', e.g.
// "Overwolf=0:badges=<uuid>,<uuid>". Only the `badges` value is used: up to MAX_SHOWN_BADGES distinct UUIDs
// (official account settings max_active_badges = 3). Signed TS6 badges (client_signed_badges) are not part of
// the snapshot and are never synthesised here.
export const MAX_SHOWN_BADGES = 3;
export const MAX_BADGE_STRING = 1024;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
export function parseClientBadges(raw) {
if (typeof raw !== 'string' || raw.length === 0 || raw.length > MAX_BADGE_STRING) return [];
const uuids = [];
for (const pair of raw.split(':')) {
const eq = pair.indexOf('=');
if (eq < 0 || pair.slice(0, eq).trim().toLowerCase() !== 'badges') continue;
for (const part of pair.slice(eq + 1).split(',')) {
const uuid = part.trim().toLowerCase();
if (UUID.test(uuid) && !uuids.includes(uuid)) uuids.push(uuid);
if (uuids.length === MAX_SHOWN_BADGES) return uuids;
}
}
return uuids;
}
+144
View File
@@ -0,0 +1,144 @@
// Client badges (official tree `ts-badges` small icons with the badge description as tooltip, and the client
// info "Badge Showcase" with detailed artwork and names). Metadata and artwork come from main's public catalog
// (app/main/badges.js): the renderer only sends badge UUIDs and receives SVG text.
//
// Caching: only successful results are kept, in bounded least-recently-used maps of plain data (catalog entries
// and SVG text). Unknown/failed lookups are forgotten as soon as they settle; badgeEpoch() changes at most every
// 30 s afterwards so rendered rows ask main again (main throttles network retries). Each <img> gets its own blob:
// URL, revoked once the image loaded or failed, so no Blob outlives its element and no cached value can be a
// revoked URL.
import { tp } from './core.js';
import { h, icon } from './dom.js';
import { t } from './i18n.js';
import { parseClientBadges } from './badges-model.js';
const MAX_INFO = 1000;
const MAX_ART = 200;
// Main accepts at most 64 UUIDs per badges:info call (MAX_REQUEST_UUIDS).
const INFO_BATCH = 64;
const UNKNOWN = Object.freeze({ known: false, name: '', description: '' });
const info = new Map(); // uuid → Promise<{ known, name, description }> (in flight or known)
const art = new Map(); // `${uuid}|${detailed}` → Promise<string|null> SVG text (in flight or found)
let queued = null; // uuid → resolve, waiting for the next batched badges:info request
export { parseClientBadges };
/** Least-recently-used lookup: a hit moves to the end; inserts evict the oldest beyond `max`. */
function cached(map, key, max, create) {
const hit = map.get(key);
if (hit) {
map.delete(key);
map.set(key, hit);
return hit;
}
const promise = create();
map.set(key, promise);
while (map.size > max) map.delete(map.keys().next().value);
return promise;
}
// After a failed lookup, rows retry at most once per RETRY_MS: the tree includes badgeEpoch() in its row signature.
const RETRY_MS = 30000;
let epoch = 0;
let retryTimer = null;
/** Changes (at most once per RETRY_MS) after lookups failed, so rendered badge slots ask again. */
export function badgeEpoch() {
return epoch;
}
/** Drops `key` once its promise settled with `failed(value)`, unless a newer promise replaced it meanwhile. */
function forgetFailure(map, key, promise, failed) {
promise.then((value) => {
if (!failed(value)) return;
if (map.get(key) === promise) map.delete(key);
retryTimer ??= setTimeout(() => { retryTimer = null; epoch += 1; }, RETRY_MS);
});
return promise;
}
function flushInfo() {
const pending = [...queued];
queued = null;
const settle = (resolve, badge) => resolve(badge?.known ? { known: true, name: badge.name, description: badge.description } : UNKNOWN);
for (let i = 0; i < pending.length; i += INFO_BATCH) {
const batch = pending.slice(i, i + INFO_BATCH);
const request = typeof tp?.badgeInfo === 'function' ? tp.badgeInfo(batch.map(([uuid]) => uuid)) : Promise.resolve(null);
request.then((r) => {
const byId = new Map((r?.ok ? r.badges : []).map((b) => [b.uuid, b]));
for (const [uuid, resolve] of batch) settle(resolve, byId.get(uuid));
}, () => {
for (const [, resolve] of batch) settle(resolve, null);
});
}
}
/** Catalog name/description; requests made in the same task are batched into one IPC call. */
export function badgeInfo(uuid) {
return cached(info, uuid, MAX_INFO, () => {
let resolveInfo;
const promise = new Promise((resolve) => { resolveInfo = resolve; });
if (!queued) { queued = new Map(); queueMicrotask(flushInfo); }
queued.set(uuid, resolveInfo);
return forgetFailure(info, uuid, promise, (value) => !value.known);
});
}
/** SVG text of the small (tree) or detailed (showcase) artwork, or null when no source has it right now. */
function badgeSvg(uuid, detailed) {
const key = `${uuid}|${detailed}`;
return cached(art, key, MAX_ART, () => {
const request = typeof tp?.badgeArt === 'function' ? tp.badgeArt(uuid, detailed) : Promise.resolve(null);
const promise = request.then((r) => (r?.ok && typeof r.svg === 'string' ? r.svg : null), () => null);
return forgetFailure(art, key, promise, (svg) => svg === null);
});
}
/** An <img> owning a one-off blob: URL, revoked as soon as the image has been decoded (or failed). */
function svgImage(svg) {
const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
const img = h('img', { alt: '', draggable: 'false' });
const revoke = () => URL.revokeObjectURL(url);
img.addEventListener('load', revoke, { once: true });
img.addEventListener('error', revoke, { once: true });
img.src = url;
return img;
}
/** Tree slot icons (official order: after group icons, before the country flag). Badges without artwork stay hidden. */
export function badgeIcons(raw) {
return parseClientBadges(raw).map((uuid) => {
const el = h('span', { class: 'client-badge', role: 'img', hidden: true, 'aria-label': t('client.info.badges.title') });
void badgeInfo(uuid).then(({ known, name, description }) => {
if (!known) return;
el.title = description || name;
el.setAttribute('aria-label', name || description);
});
void badgeSvg(uuid, false).then((svg) => {
if (!svg) return;
el.replaceChildren(svgImage(svg));
el.hidden = false;
});
return el;
});
}
/**
* Official client info "Badge Showcase" (ts-badges detailMode): detailed artwork with the badge name, or the
* "No Badges" row. Shown there regardless of the tree option (settings.appearance.server.show.badges.disabled).
*/
export function badgeShowcase(raw) {
const uuids = parseClientBadges(raw);
if (!uuids.length) return h('div', { class: 'ts-badges-info-container' }, icon('empty'), h('span', { text: t('client.info.badges.empty') }));
return h('div', { class: 'ts-badges ts-account-badges-area' }, ...uuids.map((uuid) => {
const image = h('span', { class: 'ts-account-badges-icon' });
const label = h('span', { class: 'ts-account-badges-text' });
const cell = h('div', { class: 'ts-account-badges-icon-container' }, image, label);
void badgeInfo(uuid).then(({ known, name, description }) => {
label.textContent = known ? name : t('universal.unknown');
if (known && description) cell.title = description;
});
void badgeSvg(uuid, true).then((svg) => { if (svg) image.replaceChildren(svgImage(svg)); });
return cell;
}));
}
+54
View File
@@ -0,0 +1,54 @@
// Settings > Chats > Markdown Help (official ts-chat-markdown-help view, client_ui/main.js module 71415):
// the dialect intro and one card per syntax entry with its source, a copy button and the example rendered by
// the same renderer the chat log uses, so every example shows exactly what TeamsPeach displays.
import { h, icon } from './dom.js';
import { t, hasTranslation } from './i18n.js';
import { tp } from './core.js';
import { renderMarkdownInto } from './markdown/render.js';
import { openExternalLink } from './external-links.js';
import { section } from './settings-ui.js';
import { MARKDOWN_HELP_IDS } from './chat-options.js';
/** Rendered-markdown interaction shared with the chat log: links go through the external-link guard, spoilers toggle. */
export function handleMarkdownClick(e) {
const link = e.target.closest('a');
if (link) { e.preventDefault(); if (link.dataset.href && !link.hasAttribute('data-invalid')) void openExternalLink(link.dataset.href); return; }
const spoiler = e.target.closest('.md-spoiler');
if (spoiler) { const revealed = spoiler.getAttribute('aria-expanded') !== 'true'; spoiler.setAttribute('aria-expanded', String(revealed)); spoiler.classList.toggle('revealed', revealed); }
}
export function handleMarkdownKey(e) {
if ((e.key === 'Enter' || e.key === ' ') && e.target.matches('.md-spoiler')) { e.preventDefault(); e.target.click(); }
}
function rendered(source) {
const content = h('span', { class: 'ts-chat-message-content ts-parsed-text-content offline-preview' });
renderMarkdownInto(content, source);
return content;
}
function card(id) {
const key = (part) => `settings.chat.markdown_help.syntax.${id}.${part}`;
const syntax = t(key('syntax'));
const copy = h('button', { type: 'button', class: 'icon-btn ts-chat-markdown-help-copy-button', 'aria-label': t('universal.copy_to_clipboard'), title: t('universal.copy_to_clipboard'),
onclick: () => { void tp.copyText(syntax); } }, icon('item-copy'));
return h('article', { class: 'ts-chat-markdown-help-card' },
h('h4', { class: 'ts-chat-markdown-help-card-title', text: t(key('name')) }),
hasTranslation(key('notes')) ? h('p', { class: 'ts-card-subtitle', text: t(key('notes')) }) : null,
h('div', { class: 'ts-chat-markdown-help-columns' },
h('div', { class: 'ts-chat-markdown-help-column' },
h('div', { class: 'ts-chat-markdown-help-label' }, h('span', { text: t('settings.chat.markdown_help.card.syntax') }), copy),
h('div', { class: 'ts-chat-markdown-help-syntax-wrapper' }, h('pre', { class: 'ts-chat-markdown-help-syntax' }, h('code', { text: syntax })))),
h('div', { class: 'ts-chat-markdown-help-column' },
h('div', { class: 'ts-chat-markdown-help-label', text: t('settings.chat.markdown_help.card.example') }),
h('div', { class: 'ts-chat-markdown-help-example' }, rendered(t(key('example')))))));
}
/** The two official sections of the help page, ready for showSubpage(). */
export function markdownHelpSections() {
const root = h('div', { class: 'ts-chat-markdown-help', onclick: handleMarkdownClick, onkeydown: handleMarkdownKey },
section(t('settings.chat.markdown_help.intro.title'), h('div', { class: 'ts-card-setting-container' }, rendered(t('settings.chat.markdown_help.intro.body')))),
section(t('settings.chat.markdown_help.syntax.title'), h('div', { class: 'ts-card-setting-container' },
h('div', { class: 'ts-chat-markdown-help-grid' }, MARKDOWN_HELP_IDS.map(card)))));
return root;
}
+68
View File
@@ -0,0 +1,68 @@
// Pure chat-option semantics (official Settings > Chats, see app/main/chat-prefs.js). No DOM or IPC here, so
// chat.js, notifications and tests share one definition of what each preference does.
// Settings > Chats > Markdown Help entries in the official syntaxIds order (client_ui/main.js module 71415);
// texts are settings.chat.markdown_help.syntax.<id>.{name,syntax,example,notes}.
export const MARKDOWN_HELP_IDS = [
'heading', 'setext_heading', 'emphasis_italic', 'strong_bold', 'strikethrough', 'underline', 'highlight',
'superscript', 'subscript', 'inline_code', 'inline_math', 'link', 'reference_link', 'link_reference_definition',
'sized_image_pipe', 'sized_image_equals', 'autolink', 'plain_url', 'blockquote', 'callout', 'unordered_list',
'ordered_list', 'task_list_item', 'fenced_code_block', 'indented_code_block', 'fenced_math_block',
'mermaid_diagram', 'table', 'thematic_break', 'details_summary', 'align', 'footnote_reference',
'footnote_definition', 'spoiler', 'escape_sequence', 'html_entity', 'emoji',
];
/** Official appearanceSettings.chat_show_system_messages: hide moderation events only; text and pokes always show. */
export function showsMessage(msg, prefs) {
return !msg.moderation || prefs?.chatShowModerationEvents !== false;
}
/** Official use24hrTime (default on): "HH:mm" when on, the locale's 12-hour clock ("h:mm A") when off. */
export function formatClock(date, locale, prefs) {
return prefs?.chatUse24hTime === false
? date.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit', hourCycle: 'h12' })
: date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
}
/** Official openIncomingChats (default on): an incoming private message opens its chat in the sidebar list. */
export function opensIncoming(prefs) {
return prefs?.chatOpenIncoming !== false;
}
export function ignoredUsers(prefs) {
return Array.isArray(prefs?.chatIgnoredUsers) ? prefs.chatIgnoredUsers : [];
}
export function isIgnoredUid(prefs, uid) {
return typeof uid === 'string' && uid.length > 0 && ignoredUsers(prefs).some((entry) => entry.uid === uid);
}
/**
* True when an inbound `text` core event (channel/server/client message or poke) comes from an ignored client.
* Only the server-reported invoker UID counts; our own messages and events without a sender UID (server
* notices) are never suppressed. The event object is not modified.
*/
export function isIgnoredText(evt, conn, prefs) {
if (!evt || evt.from_client_id === conn?.snap?.own_client_id) return false;
const uid = typeof evt.from_uid === 'string' ? evt.from_uid : null;
if (!uid || uid === ownUid(conn)) return false;
return isIgnoredUid(prefs, uid);
}
function ownUid(conn) {
const own = conn?.snap?.own_client_id;
return conn?.snap?.clients?.find((client) => client.id === own)?.uid ?? null;
}
const CONTROL = /[\u0000-\u001f\u007f]/g;
/** New ignore list with `uid` added (or its stored name refreshed in place); never mutates `prefs`. */
export function withIgnored(prefs, uid, name) {
const entry = { uid, name: String(name ?? '').replace(CONTROL, '').slice(0, 128) };
const list = ignoredUsers(prefs);
return list.some((item) => item.uid === uid) ? list.map((item) => (item.uid === uid ? entry : item)) : [...list, entry];
}
export function withoutIgnored(prefs, uid) {
return ignoredUsers(prefs).filter((entry) => entry.uid !== uid);
}
+93 -33
View File
@@ -1,53 +1,113 @@
// Settings > Chats in the official order (client_ui/main.js settings component near 4873300): Text Editing
// (toolbar visibility, diagram auto-load, Markdown Help), Options, Ignored Users. Preference semantics live in
// chat-options.js; schema and defaults in app/main/chat-prefs.js.
import { S } from './state.js'; import { S } from './state.js';
import { tp } from './core.js'; import { tp } from './core.js';
import { h, setText } from './dom.js'; import { h, icon } from './dom.js';
import { section, toggleRow, inlineRow } from './settings-ui.js'; import { section, toggleRow, inlineRow } from './settings-ui.js';
import { t } from './i18n.js'; import { t, onLanguageChange } from './i18n.js';
import { toast } from './toast.js'; import { toast } from './toast.js';
import { trustedHosts, removeTrustedHost, clearTrustedHosts } from './external-links.js'; import { showSubpage } from './settings-subpage.js';
import { markdownHelpSections } from './chat-markdown-help.js';
import { ignoredUsers, withIgnored, withoutIgnored } from './chat-options.js';
import { contactSettingsSection } from './contacts.js';
let refresh = () => {};
async function savePrefs(patch) {
const result = await tp.setPrefs(patch);
if (!result?.ok) throw new Error(result?.error?.message ?? result?.message ?? 'Not saved');
S.prefs = result.prefs;
refresh();
}
/** Adds (ignored=true) or removes a client UID from the ignore list; `name` is only the label shown in settings. */
export async function setIgnoredUser(uid, name, ignored) {
await savePrefs({ chatIgnoredUsers: ignored ? withIgnored(S.prefs, uid, name) : withoutIgnored(S.prefs, uid) });
}
export function initChatSettings(changed) { export function initChatSettings(changed) {
const host = document.getElementById('settings-chat-markdown'); const host = document.getElementById('settings-chat-markdown');
if (!host) return; if (!host) return;
let view = 'root';
let helpEntry = null;
const save = async (patch) => { const save = async (patch) => {
try { try { await savePrefs(patch); } catch (error) { toast(() => t('chat.operation_failed', { error: error.message }), 'error'); render(); }
const result = await tp.setPrefs(patch);
if (!result?.ok) throw new Error(result?.error?.message ?? result?.message ?? 'Not saved');
S.prefs = result.prefs; changed();
} catch (error) { toast(() => t('chat.operation_failed', { error: error.message }), 'error'); }
render();
}; };
function render() { refresh = () => { changed(); if (view === 'root') render(); };
// ts-segmented-control rows (official Text Editing section, main.js render@4876834).
const segmented = (key, label, choices) => { const toggle = (key, title, enabledInfo, disabledInfo = enabledInfo, fallback = true) => {
const current = S.prefs?.[key] ?? choices[0][0]; const value = S.prefs?.[key] ?? fallback;
const group = h('div', { class: 'segmented', role: 'radiogroup', 'aria-label': t(label) }); const input = h('input', { type: 'checkbox', class: 'toggle', role: 'switch' });
for (const [value, text] of choices) { input.checked = value;
group.append(h('button', { type: 'button', class: 'segment', role: 'radio', 'aria-checked': String(value === current), onclick: () => { if (value !== current) save({ [key]: value }); } }, t(text))); input.addEventListener('change', () => save({ [key]: input.checked }));
} return toggleRow(t(title), t(value ? enabledInfo : disabledInfo), input);
return group; };
}; // ts-segmented-control rows (official Text Editing section).
const images = h('input', { type: 'checkbox', class: 'toggle', role: 'switch' }); images.checked = S.prefs?.autoDownloadImages === true; const segmented = (key, label, choices) => {
images.addEventListener('change', () => save({ autoDownloadImages: images.checked })); const current = S.prefs?.[key] ?? choices[0][0];
const list = h('ul', { class: 'trusted-hosts' }); const group = h('div', { class: 'segmented', role: 'radiogroup', 'aria-label': t(label) });
for (const name of trustedHosts()) { for (const [value, text] of choices) {
const remove = h('button', { type: 'button', class: 'btn btn-ghost btn-small', 'aria-label': t('chat.settings.remove_host', { host: name }) }); group.append(h('button', { type: 'button', class: 'segment', role: 'radio', 'aria-checked': String(value === current), onclick: () => { if (value !== current) save({ [key]: value }); } }, t(text)));
setText(remove, () => t('chat.settings.remove'));
remove.addEventListener('click', async () => { try { await removeTrustedHost(name); render(); } catch (error) { toast(error.message, 'error'); } });
list.append(h('li', {}, h('span', { text: name }), remove));
} }
const clear = h('button', { type: 'button', class: 'btn btn-small', text: t('chat.settings.clear_hosts'), disabled: trustedHosts().length === 0 }); return group;
clear.addEventListener('click', async () => { try { await clearTrustedHosts(); render(); } catch (error) { toast(error.message, 'error'); } }); };
function ignoredList() {
const list = h('ul', { class: 'ts-chat-ignored-users' });
const cell = (glyph, title, subtitle, action, className = '') => h('li', { class: `tsv-item ${className}`.trim() },
h('div', { class: 'tsv-item-container tsv-item-multiline' },
h('div', { class: 'tsv-item-content' }, glyph,
h('div', { class: 'tsv-item-text' }, h('div', { class: 'tsv-item-title', text: title }), h('div', { class: 'tsv-item-subtitle', text: subtitle })))),
action);
const entries = ignoredUsers(S.prefs);
if (entries.length === 0) {
list.append(cell(icon('empty', 'tsv-icon-primary'), t('settings.chat.ignored_users.empty'), t('settings.chat.ignored_users.empty.info'), null, 'ts-chat-ignored-empty'));
}
for (const entry of entries) {
const name = entry.name || t('contactlist.name.fallback');
const remove = h('button', { type: 'button', class: 'icon-btn tsv-action-subtle', 'aria-label': t('settings.chat.ignored_users.remove', { name }), title: t('settings.chat.ignored_users.remove', { name }) }, icon('decline'));
remove.addEventListener('click', async () => {
remove.disabled = true;
try { await setIgnoredUser(entry.uid, entry.name, false); } catch (error) { remove.disabled = false; toast(() => t('chat.operation_failed', { error: error.message }), 'error'); }
});
list.append(cell(icon('contact-normal', 'tsv-icon-primary'), name, entry.uid, remove));
}
return list;
}
function openHelp() {
view = 'help';
showSubpage(host, markdownHelpSections(), () => { render(); helpEntry?.focus(); }).focus();
}
function render() {
view = 'root';
helpEntry = h('button', { type: 'button', class: 'icon-btn ts-chat-markdown-help-open', 'aria-label': t('settings.chat.text_edit.markdown_help') }, icon('navigation-forward'));
const help = h('div', { class: 'ts-card-setting-container' },
h('div', { class: 'ts-chat-markdown-help-entry', onclick: (e) => { e.preventDefault(); openHelp(); } },
h('div', { class: 'ts-chat-markdown-help-entry-text' },
h('span', { class: 'ts-setting-title', text: t('settings.chat.text_edit.markdown_help') }),
h('p', { class: 'tsv-font-subtitle', text: t('settings.chat.text_edit.markdown_help.info') })),
helpEntry));
host.replaceChildren( host.replaceChildren(
contactSettingsSection(save),
section(t('settings.chat.text_edit'), [ section(t('settings.chat.text_edit'), [
inlineRow(t('settings.chat.toolbar'), t('settings.chat.toolbar.info'), inlineRow(t('settings.chat.toolbar'), t('settings.chat.toolbar.info'),
segmented('chatToolbarVisibility', 'settings.chat.toolbar', [['inactive', 'chat.settings.toolbar.off'], ['dynamic', 'chat.settings.toolbar.dynamic'], ['always-visible', 'chat.settings.toolbar.always']])), segmented('chatToolbarVisibility', 'settings.chat.toolbar', [['inactive', 'settings.chat.text_edit.toolbar_visibility.inactive'], ['dynamic', 'settings.chat.text_edit.toolbar_visibility.dynamic'], ['always-visible', 'settings.chat.text_edit.toolbar_visibility.always_visible']])),
inlineRow(t('settings.chat.diagrams'), t('settings.chat.diagrams.info'), inlineRow(t('settings.chat.diagrams'), t('settings.chat.diagrams.info'),
segmented('chatMermaidAutoload', 'settings.chat.diagrams', [['never', 'chat.settings.diagrams.never'], ['only-simple', 'chat.settings.diagrams.simple']])), segmented('chatMermaidAutoload', 'settings.chat.diagrams', [['never', 'settings.chat.text_edit.mermaid_autoload.never'], ['only-simple', 'settings.chat.text_edit.mermaid_autoload.only_simple']])),
help,
]), ]),
section(t('settings.chat.options'), [toggleRow(t('chat.settings.server_images'), t('chat.settings.remote_images_off'), images)]), section(t('settings.chat.options'), [
section(t('chat.settings.trusted_hosts'), [h('div', { class: 'ts-card-setting-container' }, list, h('div', { class: 'form-actions' }, clear))])); toggle('chatOpenIncoming', 'settings.chat.direct.auto_open', 'settings.chat.direct.auto_open.info.enabled', 'settings.chat.direct.auto_open.disabled'),
toggle('chatShowModerationEvents', 'settings.chat.filter.moderation', 'settings.chat.filter.moderation.enabled', 'settings.chat.filter.moderation.disabled'),
toggle('chatUse24hTime', 'settings.chat.timestamp.format.24', 'settings.chat.timestamp.format.24.enabled', 'settings.chat.timestamp.format.24.disabled'),
toggle('autoDownloadImages', 'settings.chat.auto_download_images', 'settings.chat.auto_download_images.info', undefined, false),
]),
section(t('settings.chat.ignored_users'), ignoredList()));
} }
render(); render();
onLanguageChange(() => { if (view === 'help') openHelp(); else render(); });
document.getElementById('settings-nav')?.addEventListener('click', (e) => { if (e.target.closest('[data-panel="chats"]')) render(); }); document.getElementById('settings-nav')?.addEventListener('click', (e) => { if (e.target.closest('[data-panel="chats"]')) render(); });
} }
+58 -28
View File
@@ -6,11 +6,12 @@ import { errorText } from './text.js';
import { toast } from './toast.js'; import { toast } from './toast.js';
import { renderMarkdownInto, findTs3Files, applyImageSize } from './markdown/render.js'; import { renderMarkdownInto, findTs3Files, applyImageSize } from './markdown/render.js';
import { setMermaidAutoload } from './markdown/mermaid.js'; import { setMermaidAutoload } from './markdown/mermaid.js';
import { openExternalLink } from './external-links.js'; import { handleMarkdownClick, handleMarkdownKey } from './chat-markdown-help.js';
import { requestServerFileDownload, fetchServerImage, chooseAndUploadChatAttachments, canAttachFiles } from './files.js'; import { requestServerFileDownload, fetchServerImage, chooseAndUploadChatAttachments, canAttachFiles } from './files.js';
import { initChatComposer } from './chat-composer.js'; import { initChatComposer } from './chat-composer.js';
import { notify } from './notifications.js'; import { notify } from './notifications.js';
import { initChatSettings } from './chat-settings.js'; import { initChatSettings, setIgnoredUser } from './chat-settings.js';
import { formatClock, showsMessage, opensIncoming, isIgnoredText, isIgnoredUid } from './chat-options.js';
import { openAdminAction } from './admin.js'; import { openAdminAction } from './admin.js';
import { avatarUrl } from './media.js'; import { avatarUrl } from './media.js';
import { senderColor } from './chat-colors.js'; import { senderColor } from './chat-colors.js';
@@ -132,10 +133,8 @@ export function initChat() {
document.querySelector('.detail-modes').prepend(privateInfo); document.querySelector('.detail-modes').prepend(privateInfo);
controls = h('div', { class: 'chat-history-controls' }); controls = h('div', { class: 'chat-history-controls' });
$('#chat-log').before(controls); $('#chat-log').before(controls);
$('#chat-log').addEventListener('click', onLogClick); $('#chat-log').addEventListener('click', handleMarkdownClick);
$('#chat-log').addEventListener('keydown', (e) => { $('#chat-log').addEventListener('keydown', handleMarkdownKey);
if ((e.key === 'Enter' || e.key === ' ') && e.target.matches('.md-spoiler')) { e.preventDefault(); e.target.click(); }
});
closeComposer = initChatComposer({ onChange: () => { if (displayed) displayed.draft = input.value; autosize(); updateComposer(); }, attach }); closeComposer = initChatComposer({ onChange: () => { if (displayed) displayed.draft = input.value; autosize(); updateComposer(); }, attach });
$('#chat-form').append(h('div', { id: 'chat-start-prompt', class: 'chat-start-prompt', hidden: true }, icon('mode-chat'), h('span'))); $('#chat-form').append(h('div', { id: 'chat-start-prompt', class: 'chat-start-prompt', hidden: true }, icon('mode-chat'), h('span')));
on('appearance-changed', renderLog); on('appearance-changed', renderLog);
@@ -199,7 +198,7 @@ async function send() {
try { try {
await callOn(conn.id, 'send_text', { ...target, message: text }); await callOn(conn.id, 'send_text', { ...target, message: text });
if (!isAlive(conn) || conn.session !== session) return; if (!isAlive(conn) || conn.session !== session) return;
notify('message_sent', conn, { cue: 'message_out' }); notify('message_sent', conn);
chat.draft = ''; chat.draft = '';
if (current() === chat && input.value.replace(/\s+$/u, '') === text) { input.value = ''; autosize(); } if (current() === chat && input.value.replace(/\s+$/u, '') === text) { input.value = ''; autosize(); }
} catch (err) { report(err); } } catch (err) { report(err); }
@@ -209,17 +208,22 @@ async function send() {
export function onText(evt, conn) { export function onText(evt, conn) {
const state = stateFor(conn); const state = stateFor(conn);
if (!state) return; if (!state) return;
// Ignored users (Settings > Chats): their messages and pokes are dropped before any chat state or history changes.
if (isIgnoredText(evt, conn, S.prefs)) return;
const own = conn.snap?.own_client_id; const own = conn.snap?.own_client_id;
let chat; let chat;
if (evt.target === 'channel') chat = state.chats.get(`channel:${conn.snap?.own_channel_id}`); if (evt.target === 'channel') chat = state.chats.get(`channel:${conn.snap?.own_channel_id}`);
else if (evt.target === 'server') chat = state.chats.get('server'); else if (evt.target === 'server') chat = state.chats.get('server');
else { else {
const other = evt.from_client_id === own ? evt.to_client_id : evt.from_client_id; const outgoing = evt.from_client_id === own;
const key = openPrivate(conn, other, { focus: false, nickname: evt.from_client_id === own ? undefined : evt.from_nickname }); const other = outgoing ? evt.to_client_id : evt.from_client_id;
// Official openIncomingChats: incoming chats join the sidebar list without taking focus; when off they stay
// out of the list and are only counted as unread until opened.
const key = openPrivate(conn, other, { focus: false, reveal: outgoing || opensIncoming(S.prefs), nickname: outgoing ? undefined : evt.from_nickname });
chat = state.chats.get(key); chat = state.chats.get(key);
} }
if (!chat) return; if (!chat) return;
const msg = { author: evt.from_nickname ?? '?', authorUid: clientById(evt.from_client_id, conn)?.uid ?? null, const msg = { author: evt.from_nickname ?? '?', authorUid: evt.from_uid ?? clientById(evt.from_client_id, conn)?.uid ?? null,
own: evt.from_client_id === own, text: String(evt.message ?? '').slice(0, 32768), time: new Date() }; own: evt.from_client_id === own, text: String(evt.message ?? '').slice(0, 32768), time: new Date() };
addMessage(chat, msg); addMessage(chat, msg);
if (chat.scope) { if (chat.scope) {
@@ -275,7 +279,7 @@ function onChannelEvent(event, conn) {
if (byInvoker) key += '.by_invoker'; if (byInvoker) key += '.by_invoker';
} else key = entering ? 'channel.chat.events.client.joined.from_channel' : 'channel.chat.events.client.left'; } else key = entering ? 'channel.chat.events.client.joined.from_channel' : 'channel.chat.events.client.left';
const params = { victim, invoker, channel, reason }; const params = { victim, invoker, channel, reason };
addMessage(chat, { system: true, text: () => t(key, params), emphasis: [victim, invoker, channel].filter(Boolean), time: new Date() }); addMessage(chat, { system: true, moderation: true, text: () => t(key, params), emphasis: [victim, invoker, channel].filter(Boolean), time: new Date() });
} }
} }
function addMessage(chat, msg) { function addMessage(chat, msg) {
@@ -288,18 +292,25 @@ function addMessage(chat, msg) {
badge(); badge();
} }
export function openPrivate(conn, clientId, { focus = true, nickname } = {}) { /** `reveal: false` keeps a newly created chat out of the sidebar list (openIncomingChats off); focus always reveals. */
export function openPrivate(conn, clientId, { focus = true, reveal = true, nickname } = {}) {
const state = stateFor(conn); const state = stateFor(conn);
const client = clientById(clientId, conn); const client = clientById(clientId, conn);
// Ephemeral numeric client IDs are never durable identity keys. // Ephemeral numeric client IDs are never durable identity keys.
if (!state || !client?.uid) return null; if (!state || !client?.uid) return null;
const key = `client:${client.uid}`; const key = `client:${client.uid}`;
const existing = state.chats.has(key);
const chat = ensureChat(state, key, 'client', client.uid, nickname ?? client.nickname); const chat = ensureChat(state, key, 'client', client.uid, nickname ?? client.nickname);
persistOpen(chat, true); if (focus || reveal) revealChat(chat);
else if (!existing) chat.hidden = true;
if (focus) select(state, key); if (focus) select(state, key);
else renderTabs(); else renderTabs();
return key; return key;
} }
function revealChat(chat) {
chat.hidden = false;
persistOpen(chat, true);
}
function select(state, key) { function select(state, key) {
if (!state.chats.has(key)) return; if (!state.chats.has(key)) return;
if (displayed) displayed.draft = $('#chat-input').value; if (displayed) displayed.draft = $('#chat-input').value;
@@ -326,7 +337,7 @@ export function showOwnChannel() {
export function renderTabs() { export function renderTabs() {
const state = stateFor(viewedConnection()); const state = stateFor(viewedConnection());
const host = $('#chat-tabs'); const host = $('#chat-tabs');
const conversations = [...(state?.chats.values() ?? [])].filter((chat) => chat.kind !== 'channel' && (chat.kind === 'client' || chat.opened || chat.messages.some((message) => !message.system))); const conversations = [...(state?.chats.values() ?? [])].filter((chat) => chat.kind !== 'channel' && (chat.kind === 'client' ? !chat.hidden : chat.opened || chat.messages.some((message) => !message.system)));
if (host) reconcile(host, conversations, (c) => `${c.state.conn.id}:${c.scope?.identity}:${c.scope?.server}:${c.key}`, createTab, updateTab); if (host) reconcile(host, conversations, (c) => `${c.state.conn.id}:${c.scope?.identity}:${c.scope?.server}:${c.key}`, createTab, updateTab);
$('#conversations-panel').hidden = conversations.length === 0; $('#conversations-panel').hidden = conversations.length === 0;
if (privateInfo) { if (privateInfo) {
@@ -386,10 +397,12 @@ export function renderLog() {
for (const url of imageUrls) URL.revokeObjectURL(url); imageUrls.clear(); for (const url of imageUrls) URL.revokeObjectURL(url); imageUrls.clear();
log.replaceChildren(); log.replaceChildren();
setMermaidAutoload(S.prefs?.chatMermaidAutoload); setMermaidAutoload(S.prefs?.chatMermaidAutoload);
if (!chat?.messages.length) log.append(h('li', { class: 'chat-empty', text: t('chat.history.empty') })); // Hidden moderation events stay in memory, so turning the option back on shows them again.
const shown = chat?.messages.filter((msg) => showsMessage(msg, S.prefs)) ?? [];
if (!shown.length) log.append(h('li', { class: 'chat-empty', text: t('chat.history.empty') }));
else { else {
let prev = null; let prev = null;
for (const msg of chat.messages) { log.append(rowFor(chat, msg, prev)); prev = msg; } for (const msg of shown) { log.append(rowFor(chat, msg, prev)); prev = msg; }
} }
log.scrollTop = chat?.older ? 0 : nearBottom ? log.scrollHeight : scrollTop; log.scrollTop = chat?.older ? 0 : nearBottom ? log.scrollHeight : scrollTop;
renderHistoryControls(chat); updateComposer(); renderHistoryControls(chat); updateComposer();
@@ -397,10 +410,15 @@ export function renderLog() {
function appendRow(chat, msg) { function appendRow(chat, msg) {
const log = $('#chat-log'); const log = $('#chat-log');
const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80; const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
log.querySelector('.chat-empty')?.remove(); const shown = chat.messages.filter((entry) => showsMessage(entry, S.prefs));
log.append(rowFor(chat, msg, chat.messages.at(-2))); if (showsMessage(msg, S.prefs)) {
while (log.children.length > chat.messages.length) { log.querySelector('.chat-empty')?.remove();
const first = log.firstElementChild; log.append(rowFor(chat, msg, shown.at(-2) ?? null));
}
// Rows mirror the shown messages; drop the rows of messages that left the front of the buffer.
const rows = () => log.querySelectorAll(':scope > .msg, :scope > .msg-system');
for (let extra = rows().length - shown.length; extra > 0; extra -= 1) {
const first = rows()[0];
for (const img of first.querySelectorAll('img')) { for (const img of first.querySelectorAll('img')) {
if (imageUrls.delete(img.src)) URL.revokeObjectURL(img.src); if (imageUrls.delete(img.src)) URL.revokeObjectURL(img.src);
} }
@@ -412,7 +430,7 @@ function appendRow(chat, msg) {
} }
function messageTime(date, withDay = false) { function messageTime(date, withDay = false) {
const locale = getLanguage(); const locale = getLanguage();
const clock = date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); const clock = formatClock(date, locale, S.prefs);
if (!withDay) return clock; if (!withDay) return clock;
const today = new Date(); const today = new Date();
const day = (value) => Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()) / 86400000; const day = (value) => Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()) / 86400000;
@@ -493,12 +511,6 @@ function rowFor(chat, msg, prev) {
} }
li.append(body); return li; li.append(body); return li;
} }
function onLogClick(e) {
const link = e.target.closest('a');
if (link) { e.preventDefault(); if (link.dataset.href && !link.hasAttribute('data-invalid')) void openExternalLink(link.dataset.href); return; }
const spoiler = e.target.closest('.md-spoiler');
if (spoiler) { const revealed = spoiler.getAttribute('aria-expanded') !== 'true'; spoiler.setAttribute('aria-expanded', String(revealed)); spoiler.classList.toggle('revealed', revealed); }
}
export function updateComposer() { export function updateComposer() {
const input = $('#chat-input'); if (!input) return; const input = $('#chat-input'); if (!input) return;
const chat = current(); const enabled = canSend(chat); const chat = current(); const enabled = canSend(chat);
@@ -518,6 +530,11 @@ export function updateComposer() {
export function onSnapshot(conn) { export function onSnapshot(conn) {
const state = stateFor(conn); if (!state) return; const state = stateFor(conn); if (!state) return;
void restore(state); void restore(state);
// A chat kept out of the sidebar (openIncomingChats off) is opened from its client in the tree; once that client
// has left, the sidebar list is the only way left to read its unread messages.
for (const chat of state.chats.values()) {
if (chat.kind === 'client' && chat.hidden && chat.unread > 0 && !partner(chat)) revealChat(chat);
}
if (viewedConnection() === conn) { if (viewedConnection() === conn) {
if (displayed !== current()) onViewChanged(); if (displayed !== current()) onViewChanged();
else { renderTabs(); if (displayed && !displayed.loaded) void loadPage(displayed); } else { renderTabs(); if (displayed && !displayed.loaded) void loadPage(displayed); }
@@ -532,7 +549,20 @@ export function onViewChanged() {
renderTabs(); renderLog(); badge(); renderTabs(); renderLog(); badge();
if (displayed && !displayed.loaded) void loadPage(displayed); if (displayed && !displayed.loaded) void loadPage(displayed);
} }
export function onConnectionClosed(conn) { states.delete(conn); onViewChanged(); } export function onConnectionClosed(conn) {
// Unread chats that were kept out of the sidebar reopen with the next session instead of being lost.
for (const chat of states.get(conn)?.chats.values() ?? []) if (chat.kind === 'client' && chat.hidden && chat.unread > 0) persistOpen(chat, true);
states.delete(conn); onViewChanged();
}
/** Unread private messages from client `uid` on `conn` (tree highlight while openIncomingChats is off). */
export function privateUnread(conn, uid) { return states.get(conn)?.chats.get(`client:${uid}`)?.unread ?? 0; }
export function isClientIgnored(conn, clientId) { return isIgnoredUid(S.prefs, clientById(clientId, conn)?.uid); }
/** Client-menu "Ignore User": adds or removes the client's UID; own client and UID-less clients are refused. */
export async function setClientIgnored(conn, clientId, ignored) {
const client = clientById(clientId, conn);
if (!client?.uid || client.id === conn?.snap?.own_client_id) throw new Error('This client cannot be ignored');
await setIgnoredUser(client.uid, client.nickname, ignored);
}
export function unreadCount(conn) { let count = 0; for (const chat of states.get(conn)?.chats.values() ?? []) count += chat.unread; return count; } export function unreadCount(conn) { let count = 0; for (const chat of states.get(conn)?.chats.values() ?? []) count += chat.unread; return count; }
function badge() { function badge() {
let count = 0; for (const conn of states.keys()) count += unreadCount(conn); let count = 0; for (const conn of states.keys()) count += unreadCount(conn);
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more