release: prepare v0.1.5 verified account-free snapshot

This commit is contained in:
omar committed 2026-11-02 10:50:54 +03:00
1 parent 8336f01be7
commit 9cbb80991c
39 files changed
+565 -2374

No files matched your search

+12 -4
View File
@@ -2,6 +2,15 @@
## Unreleased
## 0.1.5 — 2026-11-02
Current development snapshot; full visual parity and native Asahi verification remain unfinished.
- Added source-style advanced notification controls with independent persisted event choices,
confirmation before hiding advanced controls and single-event expansion.
- Corrected server-tree painting against paired hidden captures. Remaining light-theme,
narrow-layout and composer differences are not claimed fixed in this release.
- Rebuilt Identities around the original selector, inline creation/rename, selected-identity Details,
security-level controls and related bookmarks. Fixed default-profile UID leakage into selected Details,
selector popup initialization and the final improvement level briefly reverting during a list refresh.
@@ -23,9 +32,8 @@
connections. Automatic microphone mute is applied before connecting and never changes speaker mute.
- 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.
- Removed the mistakenly added Remote Apps integration to honor the owner's explicit exclusion:
no listener, authorization IPC, settings page, remote-button capture or WebSocket production dependency.
- 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
@@ -49,7 +57,7 @@
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
or global; 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
+1 -1
View File
@@ -229,7 +229,7 @@ notifications opaque; forced colours use system tokens.
- 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
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
- Local UID contacts, public badge display, bookmark folders, Privacy 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.
+2 -2
View File
@@ -2,7 +2,7 @@
## Expanded local panels checkpoint (2026-11-01)
This supersedes the earlier exclusion of Remote Apps and the absence of local contacts below.
This supersedes the earlier absence of local contacts below. Remote Apps remains explicitly excluded.
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`.
@@ -13,7 +13,7 @@ the exact build hashes and limits are in `docs/evidence/official-parity/qa-parit
| 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 |
| Remote Apps | Excluded by the owner's explicit instruction; erroneous intermediate integration removed | Historical test artifacts describe only that removed intermediate implementation |
| 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 |
-2
View File
@@ -17,8 +17,6 @@
- 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.
+12 -8
View File
@@ -85,8 +85,8 @@ attached with a `local` designation and a `*-build-info.txt` provenance file.
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.
A binding is an in-window key or a global key (depends on the OS backend and permissions).
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
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,
@@ -167,11 +167,8 @@ attached with a `local` designation and a `*-build-info.txt` provenance file.
- **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.
- **Remote Apps:** excluded by the owner's explicit instruction. No Remote Apps listener, authorization
IPC, page or remote-button binding is included.
- **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.
@@ -308,7 +305,14 @@ rewritten to resemble the current interface. Unicode test fixtures retain their
It preserves explicit brand/account/native-caption exceptions, checks painted chat timestamps rather
than hidden DOM history, and exercises bottom-anchor/history-reading behavior across window resize.
The strict pixel gate currently fails; see `docs/evidence/official-parity/qa-parity-harness.md`.
The default 860px matrix entry is below the current 880px product minimum; use the sizes above.
The default matrix uses 1553×998, 1280×800 and the supported 880×800 minimum-width case.
- `smoke-identity-offscreen.mjs`, `smoke-information-offscreen.mjs` and `smoke-file-settings-offscreen.mjs`
exercise actual local UI, native identity CLI, document navigation and persisted transfer settings.
`smoke-notification-groups-offscreen.mjs` checks mute precedence and restart without playing sound.
- `smoke-bookmarks-offscreen.mjs` is Windows-specific: real DPAPI save/reveal/restart, safe credential
deletion, session-bound channel drops and startup routing with main's server-connect guard retained.
`smoke-server-icons-offscreen.mjs` uses the production main grant service with synthetic core replies,
not a real server or native file chooser. All accept `--exe <isolated-package> --out <evidence-directory>`.
- `node scripts/core-smoke.mjs <core-binary>` checks identity invariants offline.
- `node scripts/smoke-ui.mjs`, `smoke-voice.mjs`, `probe-stream.mjs`, `loopback-stream.mjs` and
`smoke-tree.mjs` exercise the real UI. Recorded results are in `docs/evidence/runtime/`; each run's
+10 -23
View File
@@ -11,10 +11,8 @@
* 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.
* A binding's source is 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.
*/
const { randomUUID } = require('node:crypto');
@@ -27,7 +25,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. */
@@ -73,7 +70,7 @@ function normalizeId(id) {
* 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');
if (!isObject(b) || !onlyKeys(b, ['id', 'action', 'target', 'code', 'ctrl', 'alt', 'shift', 'meta', 'global'])) fail('binding: unknown field');
const id = normalizeId(b.id);
const spec = ACTIONS[b.action];
if (!spec) fail('action: unknown');
@@ -81,20 +78,11 @@ function normalizeBinding(b) {
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 };
return { id, action: b.action, target: target.toLowerCase(), 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) {
@@ -173,23 +161,22 @@ function loadStore(data, { defaultProfileName = 'Default' } = {}) {
}
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
* Bindings that cannot work as stored: the same chord 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();
const byChord = new Map();
for (const b of bindings) {
const key = sourceKey(b);
const other = bySource.get(key);
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 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' });
} else byChord.set(key, b);
if (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;
-10
View File
@@ -49,7 +49,6 @@ const { registerClientVolumesIpc } = require('./client-volumes');
const { registerWhisperIpc } = require('./whisper-main');
const { registerServerSnapshotsIpc } = require('./server-snapshots');
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');
@@ -124,7 +123,6 @@ let identities = null;
let whisperIpc = null;
let filesController = null;
let streamPopout = null;
let remoteApps = null;
let phishingList = null;
let badgeCatalog = null;
@@ -160,7 +158,6 @@ function sendToRenderer(channel, payload) {
// ---------- server connections (one core process each) ----------
function sendConnections(list) {
remoteApps?.updateConnectionList(list);
sendToRenderer('connections:changed', { connections: list, input: connections.inputId });
}
@@ -168,7 +165,6 @@ function startConnections() {
fs.mkdirSync(logsDir(), { recursive: true });
connections = new ConnectionManager({ resolveBinary: resolveCoreBinary, dataDir: dataDir(), logsDir: logsDir() });
connections.on('status', (id, status) => {
remoteApps?.handleCoreStatus(id, status);
if (status.status !== 'ready') onConnectionInactive(id);
sendToRenderer('core:status', { ...status, connectionId: id });
});
@@ -190,7 +186,6 @@ function onConnectionInactive(id) {
}
function onCoreEvent(id, evt) {
remoteApps?.handleCoreEvent(id, evt);
filesController?.onEvent(id, evt);
if (evt.event === 'audio') {
if (typeof evt.pcm !== 'string') return;
@@ -479,10 +474,6 @@ function registerIpc() {
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 });
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}`) });
@@ -709,7 +700,6 @@ app.on('before-quit', (event) => {
osSettings?.markQuitting();
identities?.shutdown();
whisperIpc?.dispose();
remoteApps?.dispose();
phishingList?.stop();
badgeCatalog?.stop();
streamPopout?.dispose();
-182
View File
@@ -1,182 +0,0 @@
'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
@@ -1,192 +0,0 @@
'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
@@ -1,663 +0,0 @@
'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 };
+2 -4
View File
@@ -239,7 +239,7 @@ class KeybindStore {
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) })),
profiles: this.state.profiles.map((p) => ({ id: p.id, name: p.name, bindings: p.bindings.map((b) => ({ ...b })) })),
readOnly: this.readOnly,
};
}
@@ -312,8 +312,6 @@ class KeybindStore {
}
}
const copyBinding = (b) => (b.remote ? { ...b, remote: { ...b.remote } } : { ...b });
// ------------------------------------------------------------------------------------------- helper
const HELPER_BACKENDS = ['windows_registerhotkey', 'xdg_portal_global_shortcuts', 'x11_xgrabkey', 'unavailable'];
@@ -363,7 +361,7 @@ class HotkeyHelper {
* `exact` is the profile store's requireExactMatch.
*/
bind(bindings, { exact = true } = {}) {
this.wanted = bindings.filter((b) => b.global && !b.remote).map((b) => ({
this.wanted = bindings.filter((b) => b.global).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,
}));
this.exact = exact;
-8
View File
@@ -88,14 +88,6 @@ contextBridge.exposeInMainWorld('teamspeach', {
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)),
getAppInfo: () => ipcRenderer.invoke('app:info'),
getWindowState: () => ipcRenderer.invoke('window:get-state'),
+1 -6
View File
@@ -10,11 +10,11 @@
<link rel="stylesheet" href="styles/titlebar.css">
<link rel="stylesheet" href="styles/user-styles.css">
<link rel="stylesheet" href="styles/settings.css">
<link rel="stylesheet" href="styles/notifications.css">
<link rel="stylesheet" href="styles/file-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">
@@ -535,10 +535,6 @@
<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>
</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 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>
@@ -547,7 +543,6 @@
<!-- 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-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>
<h1 id="settings-title" class="panel-title" data-i18n="settings.nav.identities">Identities</h1>
<!-- Official ts-identity-settings (main.js @4939589): selector bar, info, import; Details of the selected
+3 -3
View File
@@ -3,8 +3,8 @@
// everything else calls the module that owns the operation.
//
// Lifecycle per binding: down(binding, scope) once, then up(id, { synthetic }). `hold` actions end on any up;
// `trigger` actions run only on a real (non-synthetic) up, so focus loss, a rebind, a revoked Remote App or
// a crashed helper never toggles anything; `press` actions run on down.
// `trigger` actions run only on a real (non-synthetic) up, so focus loss, a rebind or a crashed helper
// never toggles anything; `press` actions run on down.
import { ACTION_KIND } from './keybind-catalog.js';
import { callOn } from './core.js';
import { connectionList, inputConnection, viewedConnection, isConnected, ownClient } from './state.js';
@@ -123,7 +123,7 @@ export function createKeybindActions(hooks) {
}
return {
/** scope: 'local' (focused window), 'global' (helper) or 'remote' (Remote App). */
/** scope: 'local' (focused window) or 'global' (helper). */
down(binding, scope) {
if (held.has(binding.id)) return;
held.set(binding.id, { binding, scope });
+3 -31
View File
@@ -21,10 +21,10 @@ export class KeyTracker {
clear() { this.pressed.clear(); }
}
/** Bindings (physical) that a keydown `e` activates. `pressed` must already include e.code. */
/** Bindings that a keydown `e` activates. `pressed` must already include e.code. */
export function matchKeydown(bindings, e, { exact, pressed }) {
const hits = bindings.filter((b) => {
if (b.remote || b.code !== e.code) return false;
if (b.code !== e.code) return false;
if (exact) {
if (!MODIFIERS.every(([k, ek]) => b[k] === Boolean(e[ek]))) return false;
for (const code of pressed) if (code !== e.code) return false;
@@ -37,7 +37,7 @@ export function matchKeydown(bindings, e, { exact, pressed }) {
return hits.filter((b) => modifierCount(b) === best);
}
/** Whether keyup `e` ends held physical binding `b`: its key, or one of its modifiers, went up. */
/** Whether keyup `e` ends held binding `b`: its key, or one of its modifiers, went up. */
export function keyupReleases(b, e) {
if (b.code === e.code) return true;
return MODIFIERS.some(([k, ek]) => b[k] && !e[ek]);
@@ -70,31 +70,3 @@ export class KeyChordRecorder {
return { kind: 'none' };
}
}
/**
* Records one Remote App button from approved keyPress transitions: complete once every button pressed
* during capture is released. A binding source is one button, so a chord of several buttons is rejected
* and recording continues. Releases of buttons pressed before capture began are ignored.
*/
export class RemoteChordRecorder {
constructor() {
this.down = new Map();
this.buttons = new Map();
}
feed({ identifier, button, state }) {
const key = JSON.stringify([identifier, button]);
if (state === true) {
this.down.set(key, { remoteApp: identifier, remoteButton: button });
this.buttons.set(key, { remoteApp: identifier, remoteButton: button });
return { kind: 'update', remote: this.buttons.size === 1 ? [...this.buttons.values()][0] : null };
}
if (!this.down.delete(key) || this.down.size > 0) return { kind: 'none' };
const buttons = [...this.buttons.values()];
this.buttons.clear();
return buttons.length === 1 ? { kind: 'complete', remote: buttons[0] } : { kind: 'reject', reason: 'single_button' };
}
}
/** Remote bindings that one approved transition addresses. */
export const matchRemote = (bindings, { identifier, button }) => bindings.filter((b) => b.remote?.remoteApp === identifier && b.remote.remoteButton === button);
+57 -126
View File
@@ -1,11 +1,11 @@
// Settings → Key Bindings (official SettingsKeybind, render@4916202; profile editor render@4179307) and the
// runtime that turns key/Remote App transitions into actions (keybind-actions.js).
// runtime that turns key transitions into actions (keybind-actions.js).
//
// Page: card "Require exact key match when triggering hotkeys" → section Profile (profile cell, rename,
// choose, Activate, delete, add; inline "New Profile Name" editor) → section Bindings (one group per action:
// rows with mode/list selectors, key text, status glyph, Done/Clear or Add/Remove; unset rows offer Choose).
// Sources: local (this window), global (teamspeach-core hotkeys helper) and remote (approved Remote App
// keyPress). Only the active profile is live; the profile shown may be another one being edited.
// Sources: local (this window) and global (teamspeach-core hotkeys helper). Only the active profile is live;
// the profile shown may be another one being edited.
import { tp } from './core.js';
import { S, on } from './state.js';
import { h, icon } from './dom.js';
@@ -14,14 +14,13 @@ import { t, onLanguageChange } from './i18n.js';
import { errorText, keyLabel } from './text.js';
import { whisperLists } from './whisper.js';
import { GROUPS, MAX_PER_GROUP, groupOf } from './keybind-catalog.js';
import { KeyTracker, KeyChordRecorder, RemoteChordRecorder, matchKeydown, keyupReleases, matchRemote, chordLabel } from './keybind-match.js';
import { KeyTracker, KeyChordRecorder, matchKeydown, keyupReleases, chordLabel } from './keybind-match.js';
import { createKeybindActions } from './keybind-actions.js';
let state = { requireExactMatch: false, activeProfile: null, profiles: [], status: {}, readOnly: false };
let remote = { enabled: false, apps: [] };
let viewedId = null; // profile shown in the editor
let profileEdit = null; // null | 'add' | 'rename'
let recording = null; // { group, action, target, existing, kind, recorder, chord, remote, row, error, cleanup }
let recording = null; // { group, action, target, existing, recorder, chord, partial, error, cleanup }
const modeChoice = new Map(); // group id → action chosen on its unset row
let error = '';
let initialized = false;
@@ -35,10 +34,7 @@ const conflictOf = (profile, id) => profile?.conflicts?.find((c) => c.id === id)
const usable = (b) => !conflictOf(activeProfile(), b.id);
const registeredGlobally = (b) => state.status.global === true && state.status.results?.some((r) => r.id === b.id && r.ok);
/** Physical bindings this window handles itself: local ones, and global ones the helper could not register. */
const windowBindings = () => (activeProfile()?.bindings ?? []).filter((b) => !b.remote && usable(b) && (!b.global || !registeredGlobally(b)));
const remoteApp = (identifier) => remote.apps?.find((a) => a.identifier === identifier) ?? null;
const remoteLive = (identifier) => remote.enabled !== false && remoteApp(identifier)?.allowed === true && remoteApp(identifier)?.connected === true;
const remoteSupported = () => typeof tp.onRemoteAppKey === 'function';
const windowBindings = () => (activeProfile()?.bindings ?? []).filter((b) => usable(b) && (!b.global || !registeredGlobally(b)));
// ------------------------------------------------------------------------------------------- runtime
@@ -56,13 +52,13 @@ export async function initKeybinds(hooks) {
window.addEventListener('blur', () => {
tracker.clear();
actions.releaseAll((entry) => entry.scope === 'local');
if (recording?.kind === 'keyboard') cancelRecording();
if (recording) cancelRecording();
});
document.addEventListener('visibilitychange', () => { if (document.hidden && recording?.kind === 'keyboard') cancelRecording(); });
document.addEventListener('visibilitychange', () => { if (document.hidden && recording) cancelRecording(); });
tp.onKeybindEvent((event) => {
if (event.state === 'press') {
const b = activeProfile()?.bindings.find((x) => x.id === event.id);
if (b && !b.remote && usable(b) && !recording) actions.down(b, 'global');
if (b && usable(b) && !recording) actions.down(b, 'global');
} else actions.up(event.id, { synthetic: event.synthetic === true });
});
tp.onKeybindStatus((status) => {
@@ -70,11 +66,6 @@ export async function initKeybinds(hooks) {
if (!status.global) actions.releaseAll((entry) => entry.scope === 'global');
renderKeybindSettings();
});
if (remoteSupported()) {
tp.onRemoteAppKey(onRemoteKey);
tp.onRemoteAppsStatus?.(applyRemoteStatus);
tp.getRemoteApps?.().then(applyRemoteStatus, () => {});
}
on('keybinds-refresh', refreshKeybinds);
on('whisper-lists', () => void refreshKeybinds());
on('set-view', () => cancelRecording());
@@ -99,26 +90,6 @@ function onKeyUp(e) {
}
}
function onRemoteKey(event) {
if (!event || typeof event.identifier !== 'string' || typeof event.button !== 'string' || typeof event.state !== 'boolean') return;
if (recording?.kind === 'remote') {
if (event.synthetic !== true) feedRemoteRecorder(event);
return;
}
for (const b of matchRemote(activeProfile()?.bindings ?? [], event)) {
if (event.state) { if (usable(b) && !recording) actions.down(b, 'remote'); }
else actions.up(b.id, { synthetic: event.synthetic === true });
}
}
/** A Remote App that is no longer connected/allowed (or the service is off) cannot release its keys itself. */
function applyRemoteStatus(status) {
if (!status || typeof status !== 'object') return;
remote = status;
actions.releaseAll((entry) => entry.scope === 'remote' && !remoteLive(entry.binding.remote.remoteApp));
renderKeybindSettings();
}
export async function refreshKeybinds() {
try {
const r = await tp.getKeybinds();
@@ -156,48 +127,41 @@ const saveBindings = (profile, bindings) => call(tp.setKeybinds(profile.id, bind
// ------------------------------------------------------------------------------------------- recording
/** Starts recording a key (kind 'keyboard') or Remote App button (kind 'remote') for a new or existing row. */
function startRecording({ group, action, target = '', existing = null, kind }) {
/** Starts recording a key chord for a new or existing row. */
function startRecording({ group, action, target = '', existing = null }) {
cancelRecording();
actions.releaseAll();
tracker.clear();
recording = { group, action, target, existing, kind, recorder: kind === 'remote' ? new RemoteChordRecorder() : new KeyChordRecorder(), chord: null, remote: null, error: '' };
recording = { group, action, target, existing, recorder: new KeyChordRecorder(), chord: null, error: '' };
renderKeybindSettings({ force: true });
const input = document.querySelector('#keybind-settings .ts-keybinds-hidden-input input');
const cleanups = [];
if (kind === 'keyboard') {
const down = (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const r = recording.recorder.keydown(e);
if (r.kind === 'cancel') cancelRecording();
else if (r.kind === 'update') { recording.chord = r.chord; recording.partial = r.modifiers; recording.error = ''; updateRecordingRow(); }
};
const up = (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const r = recording.recorder.keyup(e);
if (r.kind === 'complete') void commitRecording();
else if (r.kind === 'update') { recording.chord = null; recording.partial = r.modifiers; updateRecordingRow(); }
};
window.addEventListener('keydown', down, true);
window.addEventListener('keyup', up, true);
cleanups.push(() => { window.removeEventListener('keydown', down, true); window.removeEventListener('keyup', up, true); });
// Global registrations would swallow an already-bound key before it reaches the recorder, and the Audio
// push-to-talk key (voice.js, an earlier window listener) must not transmit while it is being recorded.
void tp.setKeybindCapture(true);
S.keybindCapture = true;
cleanups.push(() => { S.keybindCapture = false; void tp.setKeybindCapture(false); });
// Focus leaving the recorder (click elsewhere, Tab) cancels; Done/Clear keep focus via mousedown.
const blur = () => cancelRecording();
input?.addEventListener('blur', blur);
cleanups.push(() => input?.removeEventListener('blur', blur));
} else {
// Remote capture (official editing_remote_app_only) is not ended by focus moving: the button is elsewhere.
const esc = (e) => { if (e.code === 'Escape') { e.preventDefault(); e.stopImmediatePropagation(); cancelRecording(); } };
window.addEventListener('keydown', esc, true);
cleanups.push(() => window.removeEventListener('keydown', esc, true));
}
const down = (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const r = recording.recorder.keydown(e);
if (r.kind === 'cancel') cancelRecording();
else if (r.kind === 'update') { recording.chord = r.chord; recording.partial = r.modifiers; recording.error = ''; updateRecordingRow(); }
};
const up = (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const r = recording.recorder.keyup(e);
if (r.kind === 'complete') void commitRecording();
else if (r.kind === 'update') { recording.chord = null; recording.partial = r.modifiers; updateRecordingRow(); }
};
window.addEventListener('keydown', down, true);
window.addEventListener('keyup', up, true);
cleanups.push(() => { window.removeEventListener('keydown', down, true); window.removeEventListener('keyup', up, true); });
// Global registrations would swallow an already-bound key before it reaches the recorder, and the Audio
// push-to-talk key (voice.js, an earlier window listener) must not transmit while it is being recorded.
void tp.setKeybindCapture(true);
S.keybindCapture = true;
cleanups.push(() => { S.keybindCapture = false; void tp.setKeybindCapture(false); });
// Focus leaving the recorder (click elsewhere, Tab) cancels; Done/Clear keep focus via mousedown.
const blur = () => cancelRecording();
input?.addEventListener('blur', blur);
cleanups.push(() => input?.removeEventListener('blur', blur));
// Navigating away (another settings page, closing settings) hides the editor: cancel.
const host = document.querySelector('#keybind-settings');
const panel = host?.closest('.settings-panel');
@@ -208,13 +172,6 @@ function startRecording({ group, action, target = '', existing = null, kind }) {
input?.focus({ preventScroll: true });
}
function feedRemoteRecorder(event) {
const r = recording.recorder.feed(event);
if (r.kind === 'update') { recording.remote = r.remote; recording.error = ''; updateRecordingRow(); }
else if (r.kind === 'reject') { recording.remote = null; recording.error = t('keybind.remote.single_button'); updateRecordingRow(); }
else if (r.kind === 'complete') { recording.remote = r.remote; void commitRecording(); }
}
function endRecording() {
const r = recording;
recording = null;
@@ -229,31 +186,26 @@ export function cancelRecording() {
renderKeybindSettings();
}
const sameSource = (a, b) => (a.remote || b.remote
? a.remote?.remoteApp === b.remote?.remoteApp && a.remote?.remoteButton === b.remote?.remoteButton
: a.code === b.code && a.ctrl === b.ctrl && a.alt === b.alt && a.shift === b.shift && a.meta === b.meta);
const sameChord = (a, b) => a.code === b.code && a.ctrl === b.ctrl && a.alt === b.alt && a.shift === b.shift && a.meta === b.meta;
/** Saves the recorded source on the row; a source another row of this profile already uses is refused. */
/** Saves the recorded chord on the row; a chord another row of this profile already uses is refused. */
async function commitRecording() {
const profile = viewedProfile();
if (!recording || !profile) return;
const source = recording.kind === 'remote'
? (recording.remote ? { remote: recording.remote } : null)
: (recording.chord ? { code: recording.chord.code, ctrl: recording.chord.ctrl, alt: recording.chord.alt, shift: recording.chord.shift, meta: recording.chord.meta } : null);
if (!source) { cancelRecording(); return; }
const chord = recording.chord;
if (!chord) { cancelRecording(); return; }
const source = { code: chord.code, ctrl: chord.ctrl, alt: chord.alt, shift: chord.shift, meta: chord.meta };
const others = profile.bindings.filter((b) => b.id !== recording.existing?.id);
if (others.some((b) => sameSource(b, source))) {
if (others.some((b) => sameChord(b, source))) {
recording.error = t('settings.hotkey.portal.already_bound_toast_generic');
recording.chord = null;
recording.remote = null;
recording.recorder = recording.kind === 'remote' ? new RemoteChordRecorder() : new KeyChordRecorder();
recording.recorder = new KeyChordRecorder();
updateRecordingRow();
return;
}
const r = endRecording();
const base = r.existing ?? { action: r.action, target: r.target };
const global = source.remote ? undefined : (r.existing && !r.existing.remote ? r.existing.global : true);
const binding = { ...(r.existing?.id ? { id: r.existing.id } : {}), action: base.action, target: base.target ?? '', ...source, ...(global === undefined ? {} : { global }) };
const binding = { ...(r.existing?.id ? { id: r.existing.id } : {}), action: base.action, target: base.target ?? '', ...source, global: r.existing ? r.existing.global : true };
const next = r.existing ? profile.bindings.map((b) => (b.id === r.existing.id ? binding : b)) : [...profile.bindings, binding];
await saveBindings(profile, next);
}
@@ -349,7 +301,7 @@ function focusProfileEditor() {
document.querySelector('#keybind-settings .ts-keybinds-profile-cell .ts-input')?.focus();
}
// ---- menus (profile list, Choose: system shortcut / Remote App)
// ---- profile list menu
let menu = null;
function closeMenu() {
@@ -365,7 +317,7 @@ function openMenu(anchor, items, { minWidth = false } = {}) {
const el = h('div', { class: 'device-menu keybind-menu', role: 'menu', tabindex: '-1' }, ...items.map((item) => {
const button = h('button', { type: 'button', class: `menu-item${item.active ? ' active' : ''}`, role: 'menuitem', tabindex: '-1', onclick: () => { closeMenu(); item.run(); } },
item.icon ? h('span', { class: 'menu-check', 'aria-hidden': 'true' }, icon(item.icon)) : null,
h('span', { class: 'menu-label' }, h('span', { text: item.label }), item.subtitle ? h('span', { class: 'menu-subtitle', text: item.subtitle }) : null),
h('span', { class: 'menu-label' }, h('span', { text: item.label })),
item.badge ? h('span', { class: 'tsv-item-badge', text: item.badge }) : null);
return button;
}));
@@ -400,15 +352,6 @@ function showProfileList(anchor) {
run: () => { viewedId = p.id; renderKeybindSettings(); } })), { minWidth: true });
}
/** Official showChooseMenu / showRemoteAppCaptureMenu. */
function chooseSource(anchor, spec) {
if (!remoteSupported()) { startRecording({ ...spec, kind: 'keyboard' }); return; }
openMenu(anchor, [
{ label: t('settings.hotkey.system_shortcut.action'), subtitle: t('settings.hotkey.system_shortcut.guidance'), icon: 'add', run: () => startRecording({ ...spec, kind: 'keyboard' }) },
{ label: t('settings.hotkey.remote_app.capture_action'), subtitle: t('settings.hotkey.remote_app.guidance'), icon: 'settings-addons', run: () => startRecording({ ...spec, kind: 'remote' }) },
]);
}
// ---- bindings
function bindingsSection() {
@@ -424,7 +367,7 @@ function bindingsSection() {
/** Honest helper state: global shortcuts missing, or extra-modifier variants that could not all be registered. */
function helperNote() {
const s = state.status;
const anyGlobal = (activeProfile()?.bindings ?? []).some((b) => !b.remote && b.global);
const anyGlobal = (activeProfile()?.bindings ?? []).some((b) => b.global);
if (!anyGlobal) return '';
if (!s.global) return `${t('keybind.globalUnavailable')}${s.detail ? `: ${s.detail}` : ''}`;
if (s.exact === false && s.variants?.wanted > s.variants.registered) return t('keybind.variants_partial', { registered: s.variants.registered, wanted: s.variants.wanted });
@@ -461,13 +404,7 @@ function targetSelect(group, value, onchange) {
return select;
}
function rowDisplay(b) {
if (b.remote) return b.remote.remoteButton;
return chordLabel(b, keyLabel);
}
function recordingDisplay() {
if (recording.kind === 'remote') return recording.remote ? recording.remote.remoteButton : t('settings.hotkey.press_combination');
if (recording.chord) return chordLabel(recording.chord, keyLabel);
const m = recording.partial;
const mods = m ? [m.ctrl && 'Ctrl', m.alt && 'Alt', m.shift && 'Shift', m.meta && 'Meta'].filter(Boolean) : [];
@@ -475,16 +412,11 @@ function recordingDisplay() {
}
function statusGlyph(profile, b) {
const glyph = (name, label, className = '') => h('div', { class: `ts-keybinds-hotkeys-status ${className}`.trim(), role: 'img', 'aria-label': label, title: label, tabindex: '0' }, icon(name));
const glyph = (name, label) => h('div', { class: 'ts-keybinds-hotkeys-status', role: 'img', 'aria-label': label, title: label, tabindex: '0' }, icon(name));
const conflict = conflictOf(profile, b.id);
if (conflict?.reason === 'select_list') return glyph('warning', t('settings.hotkey.portal.select_list'));
if (conflict?.reason === 'duplicate') return glyph('warning', t('settings.hotkey.portal.already_bound_toast_generic'));
if (conflict?.reason === 'ptt') return glyph('warning', t('keybind.conflict.ptt'));
if (b.remote) {
return remoteApp(b.remote.remoteApp)
? glyph('settings-addons', `${t('settings.hotkey.remote_app.badge_tooltip')} (${remoteApp(b.remote.remoteApp).name})`, 'ts-keybinds-hotkeys-status-remoteapp')
: glyph('warning', t('settings.hotkey.remote_app.unregistered'));
}
if (profile.id === state.activeProfile && b.global) {
const failure = state.status.results?.find((r) => r.id === b.id && !r.ok);
if (failure) return glyph('warning', `${t('settings.hotkey.portal.activation_failed')}: ${failure.error}${failure.detail ? ` (${failure.detail})` : ''}`);
@@ -493,7 +425,6 @@ function statusGlyph(profile, b) {
}
function scopeButton(profile, b) {
if (b.remote) return null;
return h('button', { type: 'button', class: 'ts-button btn btn-small ts-keybinds-scope', 'aria-pressed': String(b.global), title: t(b.global ? 'keybind.global.info' : 'keybind.local.info'),
text: t(b.global ? 'keybind.global' : 'keybind.local'),
onclick: (e) => { e.stopPropagation(); void saveBindings(profile, profile.bindings.map((x) => (x.id === b.id ? { ...x, global: !x.global } : x))); } });
@@ -504,7 +435,7 @@ function rowActions({ done = false, add = null, remove = null }) {
return h('div', { class: 'ts-keybind-hotkeys-entry-actions tsv-flex-center' },
done ? iconButton('accept', t('universal.done'), (e) => { e.stopPropagation(); void commitRecording(); }, 'is-constructive') : null,
done ? iconButton('decline', t('settings.hotkey.clear_hotkey_aria'), (e) => { e.stopPropagation(); cancelRecording(); }, 'is-destructive') : null,
add ? iconButton('add', t('settings.hotkey.add_hotkey_aria'), (e) => { e.stopPropagation(); add(e.currentTarget); }) : null,
add ? iconButton('add', t('settings.hotkey.add_hotkey_aria'), (e) => { e.stopPropagation(); add(); }) : null,
remove ? iconButton('remove', t('settings.hotkey.remove_hotkey_aria'), (e) => { e.stopPropagation(); remove(); }) : null,
);
}
@@ -538,7 +469,7 @@ function updateRecordingRow() {
const err = row.querySelector('.ts-keybinds-recording-error');
if (text) text.textContent = recordingDisplay();
if (err) err.textContent = recording.error;
row.querySelector('.ts-keybinds-hotkeys-key')?.classList.toggle('ts-keybinds-press-any-key', !recording.chord && !recording.remote);
row.querySelector('.ts-keybinds-hotkeys-key')?.classList.toggle('ts-keybinds-press-any-key', !recording.chord);
}
function bindingRow(profile, group, b, index, count) {
@@ -553,13 +484,13 @@ function bindingRow(profile, group, b, index, count) {
return entry({
additional: index > 0,
descriptor,
value: h('div', { class: 'ts-keybinds-hotkeys-key tsv-flex-center ts-keybinds-hotkeys-entry-details' }, h('span', { text: rowDisplay(b) }), scopeButton(profile, b)),
value: h('div', { class: 'ts-keybinds-hotkeys-key tsv-flex-center ts-keybinds-hotkeys-entry-details' }, h('span', { text: chordLabel(b, keyLabel) }), scopeButton(profile, b)),
status: statusGlyph(profile, b),
actionsCell: rowActions({
add: index === 0 && count < MAX_PER_GROUP ? (anchor) => chooseSource(anchor, { group: group.id, action: group.modes[0][0], target: b.target }) : null,
add: index === 0 && count < MAX_PER_GROUP ? () => startRecording({ group: group.id, action: group.modes[0][0], target: b.target }) : null,
remove: () => saveBindings(profile, profile.bindings.filter((x) => x.id !== b.id)),
}),
onClick: (row) => chooseSource(row, spec),
onClick: () => startRecording(spec),
});
}
@@ -574,11 +505,11 @@ function unsetRow(group) {
const descriptor = [h('span', { class: 'ts-keybinds-hotkeys-entry-name tsv-text-truncate', text: t(group.label) }),
modeSelect(group, chosen, (action) => { modeChoice.set(group.id, action); }),
group.target ? targetSelect(group, target, (value) => { target = value; }) : null];
const begin = (anchor) => chooseSource(anchor, { group: group.id, action: modeChoice.get(group.id) ?? group.modes[0][0], target: group.target ? target : '' });
const begin = () => startRecording({ group: group.id, action: modeChoice.get(group.id) ?? group.modes[0][0], target: group.target ? target : '' });
return entry({
descriptor,
value: h('div', { class: 'tsv-flex-center tsv-reveal-on-hover ts-keybinds-hotkeys-entry-details ts-keybinds-hotkeys-entry-unset' },
h('button', { type: 'button', class: 'ts-button btn btn-small', text: t('universal.choose'), onclick: (e) => { e.stopPropagation(); begin(e.currentTarget); } })),
h('button', { type: 'button', class: 'ts-button btn btn-small', text: t('universal.choose'), onclick: (e) => { e.stopPropagation(); begin(); } })),
unset: true,
onClick: begin,
});
+218 -41
View File
@@ -13,15 +13,18 @@
// logged per connection even when its sound is disabled or muted.
import { t, getLanguage } from './i18n.js';
import { h, icon } from './dom.js';
import { section, stackedRow, inlineRow, zeroDbMark } from './settings-ui.js';
import { section, inlineRow, zeroDbMark, stackedRow } from './settings-ui.js';
import { refreshSliders } from './select-controls.js';
import { S, on, emit, viewedConnection } from './state.js';
import { tp } from './core.js';
import { playNotificationSound, notificationSink, configureNotifications } from './audio/notify-output.js';
import { bindFader, formatDb } from './audio/fader.js';
import { buildDeviceOptions } from './audio/devices.js';
import { toast } from './toast.js';
import { errorText } from './text.js';
import { isIgnoredText, formatClock } from './chat-options.js';
import { showWarningDialog } from './warning-dialog.js';
import { menuPosition } from './menu-position.js';
export const STATE = Object.freeze({ DISABLED: 0, ENABLED: 1, IMPORTANT: 2 });
const LOG_MAX = 500;
@@ -62,9 +65,30 @@ export const EVENTS = Object.freeze({
});
function eventPref(id, event) { return `event_${id}_${event}`; }
function advancedPref(id) { return `advanced_${id}`; }
/** The original offers advanced controls on every setting, including a single underlying event. */
function advancedEvents(id) {
return EVENTS[id] ?? (SETTING_OF.has(id) ? [id] : null);
}
/**
* Official CoalescedNotificationSetting.isAdvanced: while true each event uses its own state, while false the
* coalesced state decides and the event states stay stored but inactive. Profiles saved before the flag existed
* had their event overrides active; they remain advanced until the user hides them, so an upgrade never drops one.
*/
export function isAdvanced(id) {
const events = advancedEvents(id);
if (!events) return false;
const states = S.prefs?.notificationStates ?? {};
const stored = states[advancedPref(id)];
if (stored === 0 || stored === 1) return stored === 1;
return events.some((event) => [0, 1, 2].includes(states[eventPref(id, event)]));
}
/** Official isNotificationSoundAllowed input: the actual setting while advanced, otherwise the coalesced one. */
export function eventState(id, event) {
const state = S.prefs?.notificationStates?.[eventPref(id, event)];
const state = isAdvanced(id) ? S.prefs?.notificationStates?.[eventPref(id, event)] : undefined;
return [0, 1, 2].includes(state) ? state : settingState(id);
}
@@ -450,20 +474,39 @@ async function saveNotificationPrefs(partial) {
// ---------- settings UI ----------
let notificationStateSave = Promise.resolve();
function setState(id, value, event = null) {
/** Serialized read-modify-write of notificationStates: every change applies to the latest saved map. */
function updateStates(change) {
const pending = notificationStateSave.catch(() => {}).then(async () => {
const next = { ...(S.prefs?.notificationStates ?? {}) };
if (event) next[eventPref(id, event)] = value;
else {
next[id] = value;
for (const key of Object.keys(next)) if (key.startsWith(`event_${id}_`)) delete next[key];
}
change(next);
await saveNotificationPrefs({ notificationStates: next });
});
notificationStateSave = pending;
return pending;
}
// The official coalesced and sub-setting states are independent: changing one never rewrites the other.
function setState(id, value, event = null) {
return updateStates((next) => { next[event ? eventPref(id, event) : id] = value; });
}
/** Context menu "Show Advanced": the event states become active, starting from their stored values. */
export function showAdvanced(id) {
return updateStates((next) => { next[advancedPref(id)] = 1; });
}
/**
* "Hide Advanced" asks first (official ts-warning-dialog, "settings.notifications.advanced.close.warning").
* Only a confirmation deactivates the event states; they stay stored, so Show Advanced restores them as in the
* original. Cancel changes nothing. Resolves whether the section was hidden.
*/
export async function hideAdvanced(id, anchor, ask = showWarningDialog) {
const { confirmed } = await ask(anchor, { subtitle: t('settings.notifications.advanced.close.warning'), requiresConfirmationCheckbox: false });
if (!confirmed) return false;
await updateStates((next) => { next[advancedPref(id)] = 0; });
return true;
}
const STATES = Object.freeze([['disabled', 'item-close'], ['enabled', 'accept'], ['important', 'item-pin']]);
/** Official notification item SegmentedControl: ✕ no sound · ✓ play · pin = even when muted or away. */
function stateControl(id, label, event = null) {
@@ -484,43 +527,188 @@ function stateControl(id, label, event = null) {
return group;
}
/** Official .ts-notifications-content-item-button: 22px glyph, then tint2 text at .9em. */
function itemButton(glyph, text, onclick) {
return h('button', { type: 'button', class: 'tsv-item-text ts-notifications-content-item-button', onclick }, icon(glyph), h('span', { text }));
}
/** Official Listen button (playPreview → playSoundForDefaultEvent ignoring the throttle); absent without a sound. */
function listenButton(sound) {
if (!SOUNDS[sound]) return null;
const listen = h('button', { class: 'notify-listen', type: 'button' }, icon('phonetic-available'), h('span', {}, t('notify.listen')));
listen.addEventListener('click', () => { playSound(sound, true); });
return listen;
return SOUNDS[sound] ? itemButton('phonetic-available', t('universal.listen'), () => { playSound(sound, true); }) : null;
}
/**
* ContentItemCell with the notification list component (module 186, render@4925679): title, then Listen or
* the advanced-editing note, control at the right. `inset` is the advanced sub setting (.tsv-inset-right).
*/
function itemCell(title, second, control, { inset = false, disabled = false, dataset }) {
return h('li', { class: `tsv-item ${inset ? 'tsv-inset-right' : 'tsv-no-padding'}`, dataset },
h('div', { class: 'tsv-notifications-content-item' },
h('div', { class: 'tsv-item-container' },
h('div', { class: 'tsv-item-content' },
h('div', { class: `tsv-item-text tsv-flex-grow${disabled ? ' tsv-notifications-content-item-disabled' : ''}` }, h('div', { class: 'tsv-text-truncate', text: title, title }))),
second ? h('div', { class: 'tsv-item-content' }, second) : null),
h('div', { class: 'tsv-bar tsv-bar-item' }, control)));
}
let rowMenu = null;
function closeRowMenu(restoreFocus = false) {
const menu = rowMenu;
if (!menu) return;
rowMenu = null;
document.removeEventListener('pointerdown', menu.outside, true);
menu.el.remove();
if (restoreFocus && menu.opener?.isConnected) menu.opener.focus({ preventScroll: true });
}
/**
* Official showCoalescedContextMenu / showEmptyContextMenu: "Show Advanced" (ItemExpand) on a coalesced setting
* that is not advanced, otherwise the disabled "No Actions" (Empty). Opens at the pointer, or at the row for the
* keyboard menu key / Shift+F10.
*/
function openRowMenu(event, onShow) {
event.preventDefault();
closeRowMenu();
const row = event.currentTarget;
const opener = document.activeElement;
const item = h('button', { type: 'button', role: 'menuitem', class: 'client-menu-item', 'aria-disabled': onShow ? null : 'true' },
h('span', { class: 'client-menu-icon' }, icon(onShow ? 'item-expand' : 'empty')),
h('span', { class: 'client-menu-label', text: t(onShow ? 'universal.show.advanced' : 'universal.no_actions') }));
const el = h('div', { class: 'client-menu notification-row-menu', role: 'menu', 'aria-label': row.querySelector('.tsv-text-truncate')?.textContent ?? '' }, item);
const outside = (e) => { if (!el.contains(e.target)) closeRowMenu(); };
rowMenu = { el, opener, outside };
item.addEventListener('click', () => {
if (!onShow) return;
closeRowMenu();
onShow();
});
el.addEventListener('keydown', (e) => {
if (e.key !== 'Escape' && e.key !== 'Tab') return;
e.preventDefault();
closeRowMenu(true);
});
document.body.append(el);
// A keyboard-opened menu (menu key, Shift+F10 on a row control) may report no point; it opens at the row.
const pointer = event.button === 2 || event.clientX !== 0 || event.clientY !== 0;
const rect = pointer ? { left: event.clientX, right: event.clientX, top: event.clientY, bottom: event.clientY } : row.getBoundingClientRect();
const size = el.getBoundingClientRect();
const { x, y } = menuPosition(rect, { width: size.width, height: size.height }, { width: window.innerWidth, height: window.innerHeight });
el.style.left = `${x}px`;
el.style.top = `${y}px`;
document.addEventListener('pointerdown', outside, true);
item.focus({ preventScroll: true });
}
/** Returns focus to the setting's actual control after a re-render removed the element that held it. */
function focusSetting(id) {
const row = document.querySelector(`#settings-notifications-events [data-setting="${id}"]`);
row?.querySelector('[aria-checked="true"], .tsv-bar-item button')?.focus({ preventScroll: true });
}
async function onShowAdvanced(id) {
try { await showAdvanced(id); }
catch (error) { toast(errorText(error), 'error'); }
finally {
renderNotificationSettings();
focusSetting(id);
}
}
async function onHideAdvanced(id, event) {
try {
if (!(await hideAdvanced(id, event))) return;
} catch (error) { toast(errorText(error), 'error'); }
renderNotificationSettings();
focusSetting(id);
}
/** One coalesced setting (official ul.tsv-list.ts-notifications-item) and, while advanced, its event rows. */
function settingList(id) {
const label = t(`notify.setting.${id}`);
const events = advancedEvents(id);
const advanced = isAdvanced(id);
const row = advanced
? itemCell(label,
h('div', { class: 'tsv-item-text tsv-flex-grow ts-notifications-content-item-subtitle' }, h('div', { class: 'tsv-text-truncate', text: t('settings.notifications.advanced.editing.info') })),
h('div', { class: 'tsv-item-content' }, itemButton('item-collapse', t('universal.hide_advanced'), (event) => onHideAdvanced(id, event))),
{ disabled: true, dataset: { setting: id } })
: itemCell(label, listenButton(PREVIEW_SOUND[id]), stateControl(id, label), { dataset: { setting: id } });
row.addEventListener('contextmenu', (event) => openRowMenu(event, events && !advanced ? () => onShowAdvanced(id) : null));
const list = h('ul', { class: 'tsv-list ts-notifications-item' }, row);
if (advanced) {
for (const event of events) {
const eventLabel = events.length === 1 ? label : t(`notify.event.${event}`);
const cell = itemCell(eventLabel, listenButton(EVENT_SOUNDS[id]?.[event]), stateControl(id, eventLabel, event), { inset: true, dataset: { event } });
cell.addEventListener('contextmenu', (e) => openRowMenu(e, null));
list.append(cell);
}
}
return list;
}
export function applyNotificationOutputPreferences() {
configureNotifications({ deviceId: S.prefs.notificationDeviceId, levelDb: S.prefs.notificationLevelDb, voiceDeviceId: S.prefs.outputDeviceId });
}
/**
* audio-device-selector actualDeviceName (module 40598): Default Device names the device behind Chromium's
* "default" alias; Use Playback Device names the chosen voice output, or that default while voice follows the
* system. Other choices have none, and a name the engine did not report stays blank rather than guessed.
*/
function deviceCaption(value, outputs) {
const systemDefault = buildDeviceOptions(outputs, '').options[0].caption;
if (value === '') return systemDefault;
if (value !== 'voice') return '';
const voice = S.prefs.outputDeviceId ?? '';
return voice ? outputs.find((d) => d.deviceId === voice)?.label ?? '' : systemDefault;
}
function outputControls() {
const device = h('select', { id: 'notification-device' },
h('option', { value: 'voice' }, t('notify.output.voice')),
h('option', { value: '' }, t('notify.output.default')),
h('option', { value: 'none' }, t('notify.output.none')));
h('option', { value: 'voice' }, t('audio.use_playback_device')),
h('option', { value: '' }, t('ui.system.default.device')),
h('option', { value: 'none' }, t('universal.none')));
const selected = S.prefs.notificationDeviceId ?? 'voice';
if (!['voice', '', 'none'].includes(selected)) device.append(h('option', { value: selected }, t('notify.output.saved')));
device.value = selected;
const note = h('p', { class: 'tsv-font-subtitle', role: 'status' });
const caption = h('span', { class: 'ts-device-caption', 'aria-hidden': 'true', hidden: true });
const note = h('p', { class: 'tsv-font-subtitle', role: 'status', hidden: true });
let outputs = [];
const showCaption = () => {
const text = deviceCaption(device.value, outputs);
caption.textContent = text;
caption.hidden = !text;
if (text) device.setAttribute('aria-description', text);
else device.removeAttribute('aria-description');
};
// Enumeration alone never opens capture or requests microphone permission.
navigator.mediaDevices?.enumerateDevices().then((devices) => {
if (!device.isConnected) return;
for (const item of devices.filter((d) => d.kind === 'audiooutput' && d.deviceId)) {
const existing = [...device.options].find((option) => option.value === item.deviceId);
if (existing) { if (item.label) existing.textContent = item.label; }
else device.append(h('option', { value: item.deviceId }, item.label || t('notify.output.saved')));
outputs = devices.filter((d) => d.kind === 'audiooutput');
// A choice saved by an earlier version may be a Chromium alias; it keeps its own option and label.
const saved = [...device.options].find((option) => option.value === selected && !['voice', '', 'none'].includes(selected));
const savedLabel = outputs.find((d) => d.deviceId === selected)?.label;
if (saved && savedLabel) saved.textContent = savedLabel;
for (const option of buildDeviceOptions(outputs, '').options.slice(1)) {
if (option.value !== selected) device.append(h('option', { value: option.value }, option.label));
}
}).catch((error) => { note.textContent = errorText(error); });
showCaption();
}).catch((error) => {
note.textContent = errorText(error);
note.hidden = false;
});
device.addEventListener('change', async () => {
device.disabled = true;
showCaption();
try {
await saveNotificationPrefs({ notificationDeviceId: device.value });
applyNotificationOutputPreferences();
} catch (error) { toast(errorText(error), 'error'); }
finally { device.value = S.prefs.notificationDeviceId ?? 'voice'; device.disabled = false; }
finally {
device.value = S.prefs.notificationDeviceId ?? 'voice';
device.disabled = false;
showCaption();
}
});
const slider = h('input', { id: 'notification-level', type: 'range', min: '0', max: '100', step: '1', 'aria-label': t('ui.volume') });
const output = h('output', { for: 'notification-level' });
@@ -543,9 +731,13 @@ function outputControls() {
}
},
});
// Official: label, audio-device-selector, description; an enumeration error appears only when it occurs.
return [
stackedRow(t('settings.notifications.output_device'), device, t('settings.notifications.output_device.desc')),
h('div', { class: 'ts-card-setting-container' }, note),
h('div', { class: 'ts-card-setting-container' },
h('label', { class: 'ts-setting-title', for: 'notification-device', text: t('settings.notifications.output_device') }),
h('div', { class: 'ts-device-selection ts-audio-device-selector' }, device, caption),
h('p', { class: 'tsv-font-subtitle', text: t('settings.notifications.output_device.desc') }),
note),
stackedRow(t('ui.volume'), h('span', { class: 'setting-slider ts-slider has-marks' }, slider, output, zeroDbMark()), t('settings.notifications.volume.info')),
];
}
@@ -553,6 +745,7 @@ function outputControls() {
export function renderNotificationSettings() {
const panel = document.querySelector('.settings-panel[data-panel="notifications"]');
if (!panel) return;
closeRowMenu();
let host = document.getElementById('settings-notifications-events');
if (!host) {
host = h('div', { id: 'settings-notifications-events', class: 'settings-group' });
@@ -576,24 +769,8 @@ export function renderNotificationSettings() {
section(t('notify.system.title'), systemRows),
];
for (const [group, items] of GROUPS) {
const list = h('ul', { class: 'tsv-list ts-notifications-item' });
for (const { id } of items) {
const label = t(`notify.setting.${id}`);
const row = h('li', { class: 'notify-row', dataset: { setting: id } },
h('div', { class: 'notify-text' }, h('span', { class: 'row-name' }, label), listenButton(PREVIEW_SOUND[id])), stateControl(id, label));
list.append(row);
if ((EVENTS[id]?.length ?? 0) > 1) {
const advanced = h('details', { class: 'notify-advanced' }, h('summary', {}, t('notify.advanced')));
for (const event of EVENTS[id]) {
const eventLabel = t(`notify.event.${event}`);
advanced.append(h('div', { class: 'notify-row notify-row-inset' },
h('div', { class: 'notify-text' }, h('span', { class: 'row-name' }, eventLabel), listenButton(EVENT_SOUNDS[id]?.[event])), stateControl(id, eventLabel, event)));
}
list.append(h('li', {}, advanced));
}
}
const enabled = S.prefs?.notificationStates?.[`group_${group}`] !== STATE.DISABLED;
const block = section(t(`notify.group.${group}`), enabled ? [list] : [h('div', { class: 'ts-card-setting-container' }, h('p', { class: 'tsv-font-subtitle', text: t('settings.notifications.system.group_disabled') }))]);
const block = section(t(`notify.group.${group}`), enabled ? items.map(({ id }) => settingList(id)) : [h('div', { class: 'ts-card-setting-container' }, h('p', { class: 'tsv-font-subtitle', text: t('settings.notifications.system.group_disabled') }))]);
const toggle = h('input', { type: 'checkbox', class: 'toggle ts-card-top-button', role: 'switch', checked: enabled, 'aria-label': t(`notify.group.${group}`) });
toggle.addEventListener('change', async () => {
toggle.disabled = true;
-340
View File
@@ -1,340 +0,0 @@
// Settings → Remote Apps (official SettingsRemoteApps, installed client render@4957240; manager main.js@1292478):
// Global {documentation button, start failure, Enabled, Port 1025–65535, Allow LAN Access "Coming Soon" (disabled
// in the original too)} · Permission Requests {name, description, Deny / Allow} · Apps {name, description, allowed
// toggle, context menu "Remove App"}. Like the original, a new request and a start failure also raise a global
// notice. Main (app/main/remote-apps.js) owns the WebSocket server and keys; this page never sees an API key.
import { t, onLanguageChange } from './i18n.js';
import { h, icon } from './dom.js';
import { tp } from './core.js';
import { toast } from './toast.js';
import { section, toggleRow, inlineRow } from './settings-ui.js';
const PORT_MIN = 1025;
const PORT_MAX = 65535;
const START_FAILURES = new Set(['address_in_use', 'listen_failed']);
let status = null;
let openSettingsPage = null;
let menuEl = null;
const requestNotices = new Map();
let failureNotice = null;
function panel() {
return document.querySelector('.settings-panel[data-panel="remoteapps"]');
}
function errorOf(result) {
return result?.error?.message ?? t('remote_apps.error.action');
}
/** Runs one main-side action; a returned status replaces the shown one, failures are reported. */
async function act(promise) {
let result;
try {
result = await promise;
} catch (err) {
toast(err?.message ?? t('remote_apps.error.action'), 'error');
await refresh();
return false;
}
if (!result?.ok) {
toast(errorOf(result), 'error');
await refresh();
return false;
}
if (result.status) applyStatus(result.status);
return true;
}
async function refresh() {
const next = await tp.getRemoteApps();
if (next) applyStatus(next);
}
// ---------- global notices (official createGlobalNotification) ----------
function notice({ title, subtitle, details = [], actions, kind = 'info' }) {
const host = document.getElementById('toasts');
if (!host) return null;
const close = h('button', { class: 'icon-btn', type: 'button', 'aria-label': t('ui.dismiss.notification') }, icon('x'));
const el = h('div', { class: 'toast remote-apps-notice', role: kind === 'error' ? 'alert' : 'status', dataset: { kind } },
h('div', { class: 'toast-text ts-notification-body' },
h('span', { class: 'ts-notification-title', text: title }),
subtitle ? h('p', { class: 'ts-notification-subtitle', text: subtitle }) : null,
details.filter(Boolean).map((text) => h('p', { class: 'ts-notification-subtitle', text })),
actions.length ? h('div', { class: 'remote-apps-notice-actions' }, actions) : null),
close);
close.addEventListener('click', () => el.remove());
host.append(el);
return el;
}
const normalName = (name) => String(name).normalize('NFKC').trim().toLowerCase();
/** True when the request's display name equals a registered app's or another pending request's name. */
function nameCollides(request, next) {
const name = normalName(request.name);
return next.apps.some((app) => normalName(app.name) === name)
|| next.requests.some((other) => other.id !== request.id && normalName(other.name) === name);
}
function syncNotices(next) {
// One-click approval only for a first-time native client whose name cannot be mistaken for another app.
// Browser pages, re-authorizations and look-alike names are reviewed in Settings, where every detail is shown.
const quickOf = (request) => request.origin === null && !request.reauth && !nameCollides(request, next);
const current = new Map(next.requests.map((r) => [r.id, r]));
for (const [id, shown] of requestNotices) {
const request = current.get(id);
// A later look-alike request or registration withdraws an earlier one-click Accept.
if (!request || shown.quick !== quickOf(request)) {
shown.el.remove();
requestNotices.delete(id);
}
}
for (const request of next.requests) {
if (requestNotices.has(request.id)) continue;
const button = (key, allow, cls) => h('button', {
type: 'button', class: `btn btn-small ${cls}`,
onclick: (event) => { event.currentTarget.disabled = true; void act(tp.respondRemoteApp(request.id, allow)); },
}, icon(allow ? 'accept' : 'decline'), h('span', { text: t(key) }));
const quick = quickOf(request);
const settingsButton = h('button', {
type: 'button', class: 'btn btn-small btn-primary',
onclick: () => { openSettingsPage?.(); },
}, icon('settings'), h('span', { text: t('universal.open_settings') }));
const el = notice({
title: t('settings.remote_apps.app_requires_auth', { name: request.name }),
subtitle: request.description,
details: [
t('remote_apps.request.identifier', { identifier: request.identifier }),
request.origin !== null ? t('remote_apps.request.origin', { origin: request.origin }) : null,
request.reauth ? t('remote_apps.request.reauth') : null,
quick ? null : t('remote_apps.notice.review'),
],
actions: quick ? [button('universal.reject', false, 'btn-danger'), button('universal.accept', true, 'btn-primary')] : [settingsButton],
});
if (el) requestNotices.set(request.id, { el, quick });
}
const failed = START_FAILURES.has(next.failure);
if (failed && !failureNotice) {
failureNotice = notice({
kind: 'error',
title: t('remote_apps.error.start_failed'),
subtitle: t('remote_apps.error.start_failed.info'),
actions: [h('button', {
type: 'button', class: 'btn btn-small',
onclick: () => { failureNotice?.remove(); openSettingsPage?.(); },
}, icon('settings'), h('span', { text: t('universal.open_settings') }))],
});
} else if (!failed && failureNotice) {
failureNotice.remove();
failureNotice = null;
}
}
function applyStatus(next) {
status = next;
syncNotices(next);
if (panel()) render();
}
// ---------- page ----------
function documentationButton() {
const label = t('settings.remote_apps.documentation.tooltip');
return h('button', { type: 'button', class: 'icon-btn ts-apps-info-button', 'aria-label': label, title: label, onclick: openDocumentation }, icon('mode-info'));
}
function globalSection() {
const rows = [];
if (!status.available) {
rows.push(h('div', { class: 'ts-card-setting-container' }, h('p', { class: 'tsv-font-subtitle', text: t('remote_apps.unavailable.test_mode') })));
} else if (START_FAILURES.has(status.failure)) {
rows.push(h('div', { class: 'ts-card-setting-container ts-notification-body' },
icon('exclamation-triangle', 'tsv-mar-r-minimal'), h('p', { class: 'ts-notification-text', text: t('settings.remote_apps.error.start') })));
}
const enabled = h('input', { type: 'checkbox', class: 'toggle', role: 'switch' });
enabled.checked = status.enabled;
enabled.addEventListener('change', async () => {
enabled.disabled = true;
await act(tp.setRemoteAppsEnabled(enabled.checked));
enabled.disabled = false;
});
rows.push(toggleRow(t('universal.enabled'), t('settings.remote_apps.enabled.info'), enabled));
// Official TSInputNumber#websocket-port: lazy (applies on commit), minimum 1025, maximum 65535, default 5899.
const port = h('input', { type: 'number', class: 'field', id: 'websocket-port', min: String(PORT_MIN), max: String(PORT_MAX), step: '1', title: `${PORT_MIN} – ${PORT_MAX}`, value: String(status.port) });
port.addEventListener('change', async () => {
const value = Number(port.value);
if (!Number.isInteger(value) || value < PORT_MIN || value > PORT_MAX) {
port.setAttribute('aria-invalid', 'true');
return;
}
port.removeAttribute('aria-invalid');
if (value === status.port) return;
port.disabled = true;
await act(tp.setRemoteAppsPort(value));
port.disabled = false;
});
rows.push(inlineRow(t('universal.port'), t('settings.remote_apps.port.info'), port));
// Disabled in the original ("Coming Soon"); connections are accepted from this computer only.
const lan = h('input', { type: 'checkbox', class: 'toggle', role: 'switch', disabled: true });
const lanRow = toggleRow(t('settings.remote_apps.remote_access.title'), t('settings.remote_apps.remote_access.info'), lan);
lanRow.querySelector('.ts-setting-title')?.replaceChildren(
h('del', { text: t('settings.remote_apps.remote_access.title') }),
h('small', { text: ` ${t('universal.coming_soon')}` }));
rows.push(lanRow);
const wrapper = section(t('universal.global'), h('div', { class: 'ts-card-content' }, rows));
wrapper.querySelector('.ts-widget-section-header')?.append(documentationButton());
return wrapper;
}
function cell(name, subtitles, controls, extra = {}) {
return h('li', { class: 'remote-apps-cell', ...extra },
h('span', { class: 'icon-container', 'aria-hidden': 'true' }, icon('settings-addons')),
h('div', { class: 'remote-apps-cell-text' },
h('span', { class: 'remote-apps-cell-name', text: name }),
subtitles.filter(Boolean).map((text) => h('p', { class: 'tsv-font-subtitle', text }))),
h('div', { class: 'remote-apps-cell-controls' }, controls));
}
function requestsSection() {
const body = status.requests.length === 0
? h('div', { class: 'ts-card-setting-container' }, h('p', { class: 'tsv-font-subtitle', text: t('settings.remote_apps.permissions.empty') }))
: h('ul', { class: 'remote-apps-list', 'aria-label': t('settings.remote_apps.permissions.title') }, status.requests.map((request) => {
const decide = (allow) => async (event) => {
for (const b of event.currentTarget.parentElement.querySelectorAll('button')) b.disabled = true;
await act(tp.respondRemoteApp(request.id, allow));
};
return cell(request.name, [
request.description,
request.version ? t('remote_apps.request.version', { version: request.version }) : null,
t('remote_apps.request.identifier', { identifier: request.identifier }),
request.origin ? t('remote_apps.request.origin', { origin: request.origin }) : null,
request.reauth ? t('remote_apps.request.reauth') : null,
], [
h('button', { type: 'button', class: 'btn btn-danger', onclick: decide(false) }, icon('decline'), h('span', { text: t('settings.remote_apps.app.deny') })),
h('button', { type: 'button', class: 'btn btn-primary', onclick: decide(true) }, icon('accept'), h('span', { text: t('settings.remote_apps.app.allow') })),
], { dataset: { request: request.id } });
}));
return section(t('settings.remote_apps.permissions.title'), body);
}
function closeMenu() {
menuEl?.remove();
menuEl = null;
}
function openAppMenu(app, anchor, point) {
closeMenu();
const remove = h('button', { type: 'button', role: 'menuitem', class: 'files-menu-item is-destructive' }, icon('item-close'), h('span', { text: t('settings.remote_apps.remove') }));
remove.addEventListener('click', async () => {
closeMenu();
await act(tp.removeRemoteApp(app.identifier));
});
menuEl = h('div', { class: 'files-menu', role: 'menu', 'aria-label': app.name }, remove);
menuEl.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
event.preventDefault();
closeMenu();
anchor.focus();
}
});
document.body.append(menuEl);
const rect = menuEl.getBoundingClientRect();
const at = point ?? (() => { const r = anchor.getBoundingClientRect(); return { x: r.left, y: r.bottom }; })();
menuEl.style.left = `${Math.max(4, Math.min(at.x, window.innerWidth - rect.width - 4))}px`;
menuEl.style.top = `${Math.max(4, Math.min(at.y, window.innerHeight - rect.height - 4))}px`;
remove.focus();
setTimeout(() => document.addEventListener('pointerdown', (event) => { if (!menuEl?.contains(event.target)) closeMenu(); }, { once: true }));
}
function appsSection() {
// The original renders the empty text followed by a period.
const body = status.apps.length === 0
? h('div', { class: 'ts-card-setting-container' }, h('p', { class: 'tsv-font-subtitle', text: `${t('settings.remote_apps.installed.empty')}.` }))
: h('ul', { class: 'remote-apps-list', 'aria-label': t('settings.remote_apps.installed.title') }, status.apps.map((app) => {
const allowed = h('input', { type: 'checkbox', class: 'toggle', role: 'switch', 'aria-label': app.name });
allowed.checked = app.allowed;
allowed.addEventListener('change', async () => {
allowed.disabled = true;
await act(tp.setRemoteAppAllowed(app.identifier, allowed.checked));
allowed.disabled = false;
});
const li = cell(app.name, [app.description, t('remote_apps.request.identifier', { identifier: app.identifier }), app.origin ? t('remote_apps.request.origin', { origin: app.origin }) : null], [allowed], { tabindex: '0', dataset: { app: app.identifier } });
li.addEventListener('contextmenu', (event) => {
event.preventDefault();
openAppMenu(app, li, { x: event.clientX, y: event.clientY });
});
li.addEventListener('keydown', (event) => {
if (event.target === li && (event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey))) {
event.preventDefault();
openAppMenu(app, li, null);
}
});
return li;
}));
return section(t('settings.remote_apps.installed.title'), body);
}
function render() {
const page = panel();
if (!page || !status) return;
let host = document.getElementById('settings-remote-apps');
if (!host) {
host = h('div', { id: 'settings-remote-apps', class: 'settings-group ts-apps-settings' });
page.append(host);
}
const focusedKey = document.activeElement?.closest?.('#settings-remote-apps [data-app], #settings-remote-apps [data-request]');
host.replaceChildren(globalSection(), requestsSection(), appsSection());
if (focusedKey?.dataset.app) host.querySelector(`[data-app="${CSS.escape(focusedKey.dataset.app)}"]`)?.focus();
}
export async function renderRemoteAppsSettings() {
await refresh();
}
// ---------- documentation (official "docs:remote-apps"; summarises the installed docs/Remote Apps.md) ----------
function openDocumentation() {
const port = status?.port ?? 5899;
const code = (value) => h('pre', { class: 'remote-apps-doc-code' }, h('code', { text: JSON.stringify(value, null, 2) }));
const title = h('h2', { id: 'remote-apps-doc-title', class: 'client-dialog-title', text: t('remote_apps.docs.title') });
const closeButton = h('button', { type: 'button', class: 'btn btn-primary', text: t('universal.close') });
const dialog = h('dialog', { class: 'client-dialog remote-apps-doc', 'aria-labelledby': title.id }, title,
h('div', { class: 'client-dialog-body' },
h('p', { text: t('remote_apps.docs.intro') }),
h('p', { text: t('remote_apps.docs.connect', { url: `ws://localhost:${port}` }) }),
code({ type: 'auth', payload: { identifier: 'net.example.myapp', version: '1.0.0', name: 'Example Application', description: 'An example application that does things', content: { apiKey: '' } } }),
h('p', { text: t('remote_apps.docs.auth_reply') }),
h('p', { text: t('remote_apps.docs.keypress') }),
code({ type: 'keyPress', payload: { button: 'some.button', state: true } }),
h('p', { text: t('remote_apps.docs.events') }),
h('p', { text: t('remote_apps.docs.loopback') })),
h('div', { class: 'client-dialog-footer' }, closeButton));
const close = () => { dialog.close(); dialog.remove(); };
closeButton.addEventListener('click', close);
dialog.addEventListener('cancel', (event) => { event.preventDefault(); close(); });
document.body.append(dialog);
dialog.showModal();
closeButton.focus();
}
/** `openSettings()` shows Settings → Remote Apps (used by the start-failure notice). */
export function initRemoteApps({ openSettings } = {}) {
openSettingsPage = openSettings ?? null;
tp.onRemoteAppsStatus?.((next) => { if (next) applyStatus(next); });
onLanguageChange(() => {
for (const shown of requestNotices.values()) shown.el.remove();
requestNotices.clear();
failureNotice?.remove();
failureNotice = null;
if (status) applyStatus(status);
});
void refresh();
}
export const _test = { applyStatus, get status() { return status; } };
-3
View File
@@ -10,7 +10,6 @@ import { initIdentities, refreshIdentities } from './identities.js';
import { initVoiceDspSettings, renderVoiceDspSettings } from './voice-dsp-settings.js';
import { refreshSliders, refreshSelects } from './select-controls.js';
import { initPrivacySettings, showPrivacySettings } from './privacy-settings.js';
import { initRemoteApps, renderRemoteAppsSettings } from './remote-apps.js';
import { initInformationPanels, showInformationPanels } from './information-panels.js';
let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} };
@@ -21,7 +20,6 @@ export function initSettings(h0) {
initIdentities();
initVoiceDspSettings({ savePrefs: hooks.savePrefs });
initPrivacySettings();
initRemoteApps({ openSettings: () => open('remoteapps') });
initInformationPanels();
$('#language-select').value = S.prefs.language;
refreshSelects($('#language-select'));
@@ -218,7 +216,6 @@ export function showPanel(name) {
if (name === 'video') renderVideo();
if (name === 'audio') voice.refreshDevices();
if (name === 'privacy') showPrivacySettings();
if (name === 'remoteapps') void renderRemoteAppsSettings();
if (name === 'about') void showInformationPanels();
}
+3 -3
View File
@@ -20,8 +20,8 @@ import { DeviceTest } from './audio/device-test.js';
const pttGate = new PushToTalkGate();
// Push-to-talk holders: 'key' (Audio PTT key), 'button' (footer button) and keybind holders
// `keybind:<bindingId>:<local|global|remote>`. PTT is down while any holder is down. Window focus loss
// releases only window-scoped holders; a global or remote keybind keeps PTT until its own release.
// `keybind:<bindingId>:<local|global>`. PTT is down while any holder is down. Window focus loss
// releases only window-scoped holders; a global keybind keeps PTT until its own release.
const pttHolders = new Set();
const windowScopedHolder = (holder) => holder === 'key' || holder === 'button' || holder.endsWith(':local');
// Push-to-mute holders (official PushToMute = inputDeactivated): while any is held nothing is forwarded.
@@ -508,7 +508,7 @@ function onKeyUp(e) {
/**
* `source` names the holder: 'key', 'button', 'keybind:<id>:<scope>'. 'window-blur' releases every
* window-scoped holder (privacy reset) and leaves global/remote keybind holders down; 'reset'
* window-scoped holder (privacy reset) and leaves global keybind holders down; 'reset'
* (microphone connection lost) releases every holder.
*/
export function setPtt(down, source = 'key') {
+1 -1
View File
@@ -293,7 +293,7 @@ function keybindRows(list) {
const bindings = list && profile ? profile.bindings.filter((b) => b.action === 'whisper_list' && b.target === list.list_uuid) : [];
const rows = bindings.map((b) => h('div', { class: 'tsv-item ts-whisper-keybind' },
h('span', { class: 'tsv-item-text tsv-text-truncate', text: t('settings.hotkey.whisper.to_list') }),
h('span', { class: 'ts-whisper-keybind-key', text: b.remote ? b.remote.remoteButton : chordLabel(b, keyLabel) })));
h('span', { class: 'ts-whisper-keybind-key', text: chordLabel(b, keyLabel) })));
if (!rows.length) rows.push(h('div', { class: 'tsv-item ts-whisper-keybind' },
h('span', { class: 'tsv-item-text tsv-text-truncate', text: t('settings.hotkey.whisper.to_list') }),
h('span', { class: 'ts-whisper-keybind-key', text: keyLabel('') })));
+8 -52
View File
@@ -798,7 +798,7 @@
"recording.track.gone": "Left",
"notify.title": "Sound Notifications",
"notify.group.messaging": "Messaging",
"notify.group.connection": "Connection",
"notify.group.connection": "Connections",
"notify.group.channel_switch": "Channel Switching",
"notify.group.status": "Status",
"notify.group.moderation": "Moderation",
@@ -1004,8 +1004,6 @@
"appearance.detailed": "Detailed",
"recording.mute_client": "Mute or unmute {name}",
"recording.client_gain": "Volume for {name}",
"notify.listen": "Listen",
"notify.advanced": "Advanced event settings",
"notify.event.poked": "Poke received",
"notify.event.text_client": "Private message received",
"notify.event.text_channel": "Channel message received",
@@ -1550,9 +1548,6 @@
"clientMenu.confirmAvatarDelete": "Delete the avatar of the client shown above",
"clientMenu.whispering": "Whispering",
"ui.layout.channel.view": "Channel view",
"notify.output.voice": "Follow voice output device",
"notify.output.default": "System default",
"notify.output.none": "No sound",
"notify.output.saved": "Saved output device",
"files.settings.folder_unset": "No download folder selected",
"streamExtras.popout": "Pop Out Stream",
@@ -1852,46 +1847,7 @@
"server.privilege_keys.delete.warning": "Are you sure you want to delete this privilege key?",
"server.temp_passwords.delete.confirm": "Are you sure you want to delete this temporary password?",
"filetransfer.confirm.clear_transfer_history": "Are you sure you want to remove all completed/aborted transfers from history?",
"settings.categories.customization": "Extensions",
"settings.remote_apps.title": "Remote Apps",
"universal.global": "Global",
"universal.enabled": "Enabled",
"universal.port": "Port",
"universal.coming_soon": "Coming Soon",
"universal.accept": "Accept",
"universal.reject": "Reject",
"universal.open_settings": "Open Settings",
"universal.close": "Close",
"settings.remote_apps.app.allow": "Allow",
"settings.remote_apps.app.deny": "Deny",
"settings.remote_apps.app_requires_auth": "{name} requests Authorization",
"settings.remote_apps.documentation.tooltip": "Show Documentation",
"settings.remote_apps.enabled.info": "Toggle the TeamSpeak WebSockets server on or off.",
"settings.remote_apps.error.start": "Remote applications failed to start. Make sure the configured port is not already in use on your system, or change to a different port.",
"settings.remote_apps.installed.empty": "No apps registered",
"settings.remote_apps.installed.title": "Apps",
"settings.remote_apps.permissions.empty": "No permission request pending",
"settings.remote_apps.permissions.title": "Permission Requests",
"settings.remote_apps.port.info": "Third party applications can connect to TeamSpeak on this port.",
"settings.remote_apps.remote_access.info": "Shall we only accept connections from your local computer?",
"settings.remote_apps.remote_access.title": "Allow LAN Access",
"settings.remote_apps.remove": "Remove App",
"remote_apps.error.start_failed": "Remote applications failed to start",
"remote_apps.error.start_failed.info": "Make sure the configured port is not in use already, or choose a different port in the settings",
"remote_apps.error.action": "The Remote Apps setting could not be changed",
"remote_apps.unavailable.test_mode": "Remote applications are not started in automated test mode.",
"remote_apps.request.version": "Version {version}",
"remote_apps.request.identifier": "Identifier: {identifier}",
"remote_apps.request.origin": "Web page: {origin}",
"remote_apps.request.reauth": "Already registered, but this connection has no valid key. Allowing it replaces the previous key and binds it to this connection's origin.",
"remote_apps.notice.review": "Review this request in Settings → Remote Apps before allowing it.",
"remote_apps.docs.title": "TeamSpeak Remote Applications API",
"remote_apps.docs.intro": "Applications on this computer can connect over a WebSocket, receive information about servers, channels and clients, and send key presses that can be bound as hotkeys. Each application must be allowed once under Permission Requests; removing it revokes its key.",
"remote_apps.docs.connect": "Connect to {url} and send:",
"remote_apps.docs.auth_reply": "Once allowed, the application receives an API key and the current connections. It must store the key and send it in content.apiKey on later connections from the same web page origin (or, for programs, without one); an empty key asks for permission again, a wrong key or origin is refused.",
"remote_apps.docs.keypress": "Send key presses (state true = down, false = up) and bind them in Settings → Key Bindings:",
"remote_apps.docs.events": "Events: connectStatusChanged, channels, channelCreated, clientMoved, clientPropertiesUpdated, clientSelfPropertyUpdated, talkStatusChanged.",
"remote_apps.docs.loopback": "Only connections from this computer are accepted.",
"bookmarks.action.duplicate": "Duplicate",
"bookmarks.create.folder.placeholder": "Folder Name",
"bookmarks.create.placeholder": "Bookmark Address",
@@ -1930,7 +1886,6 @@
"keybind.mode.grant_next_talk_power": "Grant Next User Talk Power",
"keybind.mode.request_talk_power": "Request Talk Power",
"keybind.mode.toggle_with_message": "Toggle with Message",
"keybind.remote.single_button": "Press a single Remote App button",
"keybind.variants_partial": "Only {registered} of {wanted} extra-modifier combinations could be registered globally; the rest trigger only with the exact combination",
"settings.hotkey.activate": "Activate",
"settings.hotkey.add_hotkey_aria": "Add another hotkey",
@@ -1960,17 +1915,11 @@
"settings.hotkey.push_to_talk": "Push to Talk (PTT)",
"settings.hotkey.recording.off": "not recording",
"settings.hotkey.recording.on": "recording",
"settings.hotkey.remote_app.badge_tooltip": "This hotkey is bound to a button on a connected Remote App",
"settings.hotkey.remote_app.capture_action": "Capture from Remote App",
"settings.hotkey.remote_app.guidance": "Connect your Remote App and press the button you want to use",
"settings.hotkey.remote_app.unregistered": "This hotkey belongs to a Remote App that isn't currently registered",
"settings.hotkey.remove_hotkey_aria": "Remove hotkey",
"settings.hotkey.required_exact_match": "Require exact key match when triggering hotkeys",
"settings.hotkey.required_exact_match.disabled": "Hotkeys will trigger even when other keys are pressed.",
"settings.hotkey.required_exact_match.enabled": "Hotkeys will only trigger when exactly the combination is pressed without additional keys.",
"settings.hotkey.stream.current_active": "Stream current focused application",
"settings.hotkey.system_shortcut.action": "System shortcut",
"settings.hotkey.system_shortcut.guidance": "A standard key or key combination, handled by your desktop",
"settings.hotkey.whisper.quick": "Quick whisper to selected",
"settings.hotkey.whisper.reply": "Reply last whisperer",
"settings.hotkey.whisper.to_list": "Whisper to List",
@@ -2176,6 +2125,13 @@
"identity.target.increase": "Increase target security level",
"settings.identity.session_nickname.title": "Current Server Nickname",
"settings.identity.session_nickname.info": "Renames you now on the viewed connected server and saves it to the identity that connection uses. Without a connected server it saves the default identity's nickname. 3–30 characters.",
"audio.use_playback_device": "Use Playback Device",
"universal.listen": "Listen",
"universal.show.advanced": "Show Advanced",
"universal.hide_advanced": "Hide Advanced",
"universal.no_actions": "No Actions",
"settings.notifications.advanced.editing.info": "Editing advanced options for this setting…",
"settings.notifications.advanced.close.warning": "Any changes made won't remain active if you close this section",
"server.icons.storage_unsupported": "This server stores icons in HTTP/S3 storage, which is not supported"
});
if (typeof module === 'object' && module.exports) module.exports = messages;
+7 -51
View File
@@ -1006,8 +1006,6 @@
"appearance.detailed": "Подробнее",
"recording.mute_client": "Заглушить или включить {name}",
"recording.client_gain": "Громкость {name}",
"notify.listen": "Прослушать",
"notify.advanced": "Настройки отдельных событий",
"notify.event.poked": "Получен толчок",
"notify.event.text_client": "Получено личное сообщение",
"notify.event.text_channel": "Сообщение канала",
@@ -1552,9 +1550,6 @@
"clientMenu.confirmAvatarDelete": "Удалить аватар указанного выше клиента",
"clientMenu.whispering": "Шептание",
"ui.layout.channel.view": "Представление канала",
"notify.output.voice": "Устройство голосового вывода",
"notify.output.default": "Системное устройство",
"notify.output.none": "Без звука",
"notify.output.saved": "Сохранённое устройство вывода",
"files.settings.folder_unset": "Папка загрузок не выбрана",
"streamExtras.popout": "Открыть трансляцию в отдельном окне",
@@ -1854,46 +1849,7 @@
"server.privilege_keys.delete.warning": "Действительно удалить этот ключ привилегий?",
"server.temp_passwords.delete.confirm": "Действительно удалить этот временный пароль?",
"filetransfer.confirm.clear_transfer_history": "Действительно удалить все завершенные/прерванные передачи из истории?",
"settings.categories.customization": "Расширения",
"settings.remote_apps.title": "Удаленные приложения",
"universal.global": "Глобальные",
"universal.enabled": "Включено",
"universal.port": "Порт",
"universal.coming_soon": "Скоро!",
"universal.accept": "Принять",
"universal.reject": "Отклонить",
"universal.open_settings": "Открыть настройки",
"universal.close": "Закрыть",
"settings.remote_apps.app.allow": "Разрешить",
"settings.remote_apps.app.deny": "Отклонить",
"settings.remote_apps.app_requires_auth": "{name} запрашивает авторизацию",
"settings.remote_apps.documentation.tooltip": "Показать документацию",
"settings.remote_apps.enabled.info": "Включить или выключить сервер TeamSpeak WebSockets.",
"settings.remote_apps.error.start": "Не удалось запустить удаленные приложения. Убедись, что настроенный порт уже не используется в твоей системе или измени его на другой порт.",
"settings.remote_apps.installed.empty": "Приложения не зарегистрированы",
"settings.remote_apps.installed.title": "Приложения",
"settings.remote_apps.permissions.empty": "Нет ожидающих запросов разрешений",
"settings.remote_apps.permissions.title": "Запросы разрешений",
"settings.remote_apps.port.info": "Сторонние приложения могут подключаться к TeamSpeak через этот порт.",
"settings.remote_apps.remote_access.info": "Должны ли мы принимать подключения только с твоего локального компьютера?",
"settings.remote_apps.remote_access.title": "Разрешить доступ к локальной сети",
"settings.remote_apps.remove": "Удалить приложение",
"remote_apps.error.start_failed": "Не удалось запустить удаленные приложения",
"remote_apps.error.start_failed.info": "Убедись, что настроенный порт не используется другим процессом или выбери другой порт в настройках",
"remote_apps.error.action": "Не удалось изменить настройку удаленных приложений",
"remote_apps.unavailable.test_mode": "В режиме автоматических тестов удаленные приложения не запускаются.",
"remote_apps.request.version": "Версия {version}",
"remote_apps.request.identifier": "Идентификатор: {identifier}",
"remote_apps.request.origin": "Веб-страница: {origin}",
"remote_apps.request.reauth": "Уже зарегистрировано, но у этого подключения нет действительного ключа. Если разрешить, предыдущий ключ будет заменен и привязан к источнику этого подключения.",
"remote_apps.notice.review": "Проверь этот запрос в «Настройки → Удаленные приложения», прежде чем разрешить его.",
"remote_apps.docs.title": "API удаленных приложений TeamSpeak",
"remote_apps.docs.intro": "Приложения на этом компьютере могут подключаться по WebSocket, получать сведения о серверах, каналах и клиентах и отправлять нажатия клавиш, которые можно назначить горячими клавишами. Каждое приложение нужно один раз разрешить в разделе «Запросы разрешений»; удаление приложения отзывает его ключ.",
"remote_apps.docs.connect": "Подключись к {url} и отправь:",
"remote_apps.docs.auth_reply": "После разрешения приложение получает API-ключ и текущие подключения. Ключ нужно сохранить и отправлять в content.apiKey при следующих подключениях с того же источника веб-страницы (для программ — без него); пустой ключ снова запрашивает разрешение, неверный ключ или источник отклоняется.",
"remote_apps.docs.keypress": "Отправляй нажатия клавиш (state true — нажатие, false — отпускание) и назначай их в «Настройки → Привязки клавиш»:",
"remote_apps.docs.events": "События: connectStatusChanged, channels, channelCreated, clientMoved, clientPropertiesUpdated, clientSelfPropertyUpdated, talkStatusChanged.",
"remote_apps.docs.loopback": "Принимаются только подключения с этого компьютера.",
"bookmarks.action.duplicate": "Дублировать",
"bookmarks.create.folder.placeholder": "Имя папки",
"bookmarks.create.placeholder": "Адрес закладки",
@@ -1932,7 +1888,6 @@
"keybind.mode.grant_next_talk_power": "Дать право говорить следующему",
"keybind.mode.request_talk_power": "Запросить право говорить",
"keybind.mode.toggle_with_message": "Переключение с сообщением",
"keybind.remote.single_button": "Нажми одну кнопку Remote App",
"keybind.variants_partial": "Глобально зарегистрировано только {registered} из {wanted} комбинаций с дополнительными модификаторами; остальные срабатывают только при точной комбинации",
"settings.hotkey.activate": "Активировать",
"settings.hotkey.add_hotkey_aria": "Добавить еще одну горячую клавишу",
@@ -1962,17 +1917,11 @@
"settings.hotkey.push_to_talk": "Нажми и говори (PTT)",
"settings.hotkey.recording.off": "выключить запись",
"settings.hotkey.recording.on": "запись",
"settings.hotkey.remote_app.badge_tooltip": "Эта горячая клавиша привязана к кнопке подключенного Remote App",
"settings.hotkey.remote_app.capture_action": "Захватить из Remote App",
"settings.hotkey.remote_app.guidance": "Подключи Remote App и нажми нужную кнопку",
"settings.hotkey.remote_app.unregistered": "Эта горячая клавиша принадлежит Remote App, который сейчас не зарегистрирован",
"settings.hotkey.remove_hotkey_aria": "Удалить горячую клавишу",
"settings.hotkey.required_exact_match": "Комбинации горячих клавиш работают только при точном совпадении",
"settings.hotkey.required_exact_match.disabled": "Горячие клавиши будут срабатывать даже при нажатии других клавиш.",
"settings.hotkey.required_exact_match.enabled": "Горячие клавиши срабатывают только при нажатии конкретной комбинации без лишних клавиш.",
"settings.hotkey.stream.current_active": "Транслировать текущее активное приложение",
"settings.hotkey.system_shortcut.action": "Системное сочетание",
"settings.hotkey.system_shortcut.guidance": "Обычная клавиша или комбинация клавиш, обрабатываемая рабочим столом",
"settings.hotkey.whisper.quick": "Быстрый шепот выбранным контактам",
"settings.hotkey.whisper.reply": "Ответить автору последнего шепота",
"settings.hotkey.whisper.to_list": "Шептать списку",
@@ -2178,6 +2127,13 @@
"identity.target.increase": "Увеличить целевой уровень безопасности",
"settings.identity.session_nickname.title": "Ник на текущем сервере",
"settings.identity.session_nickname.info": "Сразу меняет ваш ник на просматриваемом подключённом сервере и сохраняет его в идентификаторе этого подключения. Без подключения к серверу сохраняет ник идентификатора по умолчанию. От 3 до 30 символов.",
"audio.use_playback_device": "Использовать устройство воспроизведения",
"universal.listen": "Слушать",
"universal.show.advanced": "Показать дополнительные",
"universal.hide_advanced": "Скрыть дополнительные",
"universal.no_actions": "Нет действий",
"settings.notifications.advanced.editing.info": "Изменение дополнительных настроек для этого параметра…",
"settings.notifications.advanced.close.warning": "Если ты закроешь этот раздел, внесенные изменения не останутся активными",
"server.icons.storage_unsupported": "Сервер хранит значки в HTTP/S3-хранилище, которое пока не поддерживается"
});
if (typeof module === 'object' && module.exports) module.exports = messages;
+10 -5
View File
@@ -809,7 +809,8 @@ body.is-resizing[data-resize-axis="y"], body.is-resizing[data-resize-axis="y"] *
background: var(--tsv-servertree-bg-gradient);
}
/* TSServerHeader: 92px slot, 74px card at 18px, 10px radius, view-header gradient @ .9 */
.server-head { flex: none; padding: 0 19px 8px; }
/* .ts-server-tree-wrapper is its own will-change:transform layer (css@628172): tree and header text rasterise grayscale */
.server-head { flex: none; padding: 0 19px 8px; will-change: transform; }
.server-card {
--banner-top: calc(var(--tsv-padding-v-large) + var(--tsv-padding-v-minimal));
--banner-height: calc(var(--banner-top) + var(--tsv-icon-size-xlarge) + 2 * var(--tsv-padding-v) + 3px);
@@ -825,14 +826,14 @@ body.is-resizing[data-resize-axis="y"], body.is-resizing[data-resize-axis="y"] *
overflow: hidden;
background: transparent;
}
.server-card::before, .server-card::after { content: ""; position: absolute; inset: var(--banner-top) 0 0; z-index: -1; border-radius: inherit; background: var(--tsv-view-header-bg); opacity: 0.9; }
.server-card::before { z-index: -3; opacity: 1; background: var(--tsv-contrast-bg); }
/* theme D/L@39790: only ::after paints (gradient @ .9 over the tree); ::before is display:none (D/L@40030) */
.server-card::after { content: ""; position: absolute; inset: var(--banner-top) 0 0; z-index: -1; border-radius: inherit; background: var(--tsv-view-header-bg); opacity: 0.9; }
.server-card > :not(.host-banner) { position: relative; z-index: 1; }
.host-banner { position: absolute; inset: var(--banner-top) 0 0; z-index: -2; width: 100%; height: calc(100% - var(--banner-top)); object-fit: cover; object-position: 0 0; border-radius: inherit; pointer-events: none; }
.server-icon { flex: none; display: grid; place-items: center; width: var(--tsv-icon-size-xlarge); height: var(--tsv-icon-size-xlarge); margin-top: var(--banner-content-offset); color: var(--tsv-font-color); filter: drop-shadow(0 0 2px var(--tsv-shadow-color)); }
.server-icon .icon { width: var(--tsv-icon-size-xlarge); height: var(--tsv-icon-size-xlarge); }
.server-title { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: flex-start; margin-top: var(--banner-content-offset); margin-bottom: 4px; padding: 0 20px; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; }
.server-name { font-size: var(--tsv-font-size-large); line-height: 28px; font-weight: var(--tsv-font-weight-bold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.server-name { max-width: 100%; font-size: var(--tsv-font-size-large); line-height: 28px; font-weight: var(--tsv-font-weight-bold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.conn-badge { display: inline-flex; align-items: center; gap: 5px; font-size: var(--tsv-font-size-small); line-height: var(--tsv-line-height-small); color: var(--tsv-font-subtitle-color); }
.conn-badge::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--tsv-font-subtitle-color); }
.conn-badge[data-state="connected"] { display: none; }
@@ -854,6 +855,7 @@ body.is-resizing[data-resize-axis="y"], body.is-resizing[data-resize-axis="y"] *
overflow-x: hidden;
overflow-y: auto;
scrollbar-gutter: stable;
will-change: transform;
}
/* indent(d) = min(d,4)·10px + max(d−4,0)·5px (js@4152551) */
.tree-row { --indent: calc(min(var(--depth, 0), 4) * 10px + max(var(--depth, 0) - 4, 0) * 5px); position: relative; white-space: nowrap; }
@@ -960,7 +962,8 @@ body.is-resizing[data-resize-axis="y"], body.is-resizing[data-resize-axis="y"] *
width: var(--tsv-icon-size-large);
height: var(--tsv-icon-size-large);
}
.avatar > .icon { position: absolute; left: 50%; top: 0; width: calc(100% * 51 / 33); height: 100%; transform: translateX(-50%); }
/* portrait icon overhangs the square slot by (portrait − size) / 2 each side (css@112135), no fractional centring */
.avatar > .icon { position: absolute; left: calc((100% - 100% * 51 / 33) / 2); top: 0; width: calc(100% * 51 / 33); height: 100%; }
.avatar img { position: absolute; inset: 0; z-index: 1; width: 100%; height: 100%; object-fit: cover; mask: url("../assets/icons/client_detailed_mask.svg") center / 100% 100% no-repeat; }
.avatar .avatar-talking { z-index: 2; opacity: 0; transition: opacity .15s; }
.member-row[data-talking="true"] .avatar-talking, .avatar[data-talking="true"] .avatar-talking { opacity: 1; transition-duration: 5ms; }
@@ -1717,6 +1720,8 @@ html[data-tree-style="compact"] .member-row .row-label { font-size: var(--tsv-fo
.server-pane:has(> .room-side) { container: server-pane / inline-size; }
@container server-pane (max-width: 439px) {
.tree { padding-inline: 10px; }
/* header sits inside the official scroller: 10px scroller padding (+8px gutter) + 10px banner margin */
.server-head { padding-inline: 20px 28px; }
.server-status-bar { padding-inline: 10px; }
.server-status-bar .create-channel-action { padding-inline: 10px; }
.server-status-bar .create-channel-action > span { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
+2 -3
View File
@@ -53,7 +53,7 @@
:where(.settings-scroll) .ts-keybinds-hotkeys-entry-status { display: inline-grid; place-items: center; width: 22px; height: 22px; }
:where(.settings-scroll) .ts-keybinds-hotkeys-status { display: inline-grid; place-items: center; width: 22px; height: 22px; color: var(--tsv-error-light-color); }
:where(.settings-scroll) .ts-keybinds-hotkeys-status .icon { width: 18px; height: 18px; --tsv-icon-base: currentColor; }
:where(.settings-scroll) :is(.ts-keybinds-hotkeys-status-recording, .ts-keybinds-hotkeys-status-remoteapp) { color: var(--tsv-tint); }
:where(.settings-scroll) .ts-keybinds-hotkeys-status-recording { color: var(--tsv-tint); }
:where(.settings-scroll) .ts-keybind-hotkeys-entry-actions { display: flex; justify-content: flex-end; }
:where(.settings-scroll) .ts-keybind-hotkeys-entry-actions .ts-button.tsv-action-subtle { width: 22px; height: 22px; }
:where(.settings-scroll) .ts-keybinds-hidden-input { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
@@ -62,8 +62,7 @@
:where(.settings-scroll) .ts-keybinds-hotkeys-entry { grid-template-columns: minmax(0, 1fr) auto 22px 44px; }
}
/* ---------- Choose / profile list menus ---------- */
/* ---------- profile list menu ---------- */
.keybind-menu .menu-label { display: flex; flex-direction: column; white-space: normal; }
.keybind-menu .menu-subtitle { color: var(--tsv-font-subtitle-color); font-size: var(--tsv-font-size-small); }
.keybind-menu .menu-item.active { color: var(--tsv-tint); }
.keybind-menu .tsv-item-badge { flex: none; padding: 0 6px; border-radius: var(--tsv-border-radius-pill); background: var(--tsv-tint); color: var(--tsv-bg); font-size: var(--tsv-font-size-minimal); line-height: 18px; }
+47
View File
@@ -0,0 +1,47 @@
/* Settings > Notifications rows (installed client module 186: list component render@4925679, page
render@4930444). main.css: .tsv-notifications-content-item @675663-676361, .ts-notifications-item
@676629-677575, .tsv-item @71541, .tsv-item-container @76256, .tsv-item-content @76421, .tsv-item-text
@72296, .tsv-item-highlight @74089 (inside cards tsv-bg, @21945), .tsv-segmented-control @162911-163140.
Section cards, toggles, the select field and its device caption come from settings.css; the row menu is
the shared .client-menu. */
#settings-notifications-events .ts-notifications-item { min-width: 0; margin: 0; padding: 0; list-style: none; }
/* ContentItemCell: 10px side padding (.tsv-no-padding), sub settings 40px in (.tsv-inset-right) with the
highlight starting at 30px; the hover highlight is inset 2px vertically behind the row. */
#settings-notifications-events .ts-notifications-item > .tsv-item { position: relative; isolation: isolate; display: flex; min-width: 0; min-height: var(--tsv-row-height); padding: 0 var(--tsv-padding-h-small); }
#settings-notifications-events .ts-notifications-item > .tsv-inset-right { padding-left: var(--tsv-padding-h-large); }
#settings-notifications-events .ts-notifications-item > .tsv-item::before { content: ""; position: absolute; top: var(--tsv-padding-v-minimal); right: 0; bottom: var(--tsv-padding-v-minimal); left: 0; z-index: -1; display: none; border-radius: var(--tsv-border-radius); background: var(--tsv-bg); pointer-events: none; }
#settings-notifications-events .ts-notifications-item > .tsv-inset-right::before { left: 30px; }
#settings-notifications-events .ts-notifications-item > .tsv-item:hover::before { display: block; }
/* List component: title row, then Listen (or the advanced-editing note); 8px vertical padding, body type. */
#settings-notifications-events .tsv-notifications-content-item { display: flex; flex-direction: row; justify-content: space-between; width: 100%; min-width: 0; padding: var(--tsv-padding-v) 0; color: var(--tsv-font-color); font-size: var(--tsv-font-size); line-height: var(--tsv-line-height); }
#settings-notifications-events .ts-notifications-item .tsv-item-container { display: flex; flex-direction: column; flex-grow: 1; min-width: 0; min-height: var(--tsv-row-height); }
#settings-notifications-events .ts-notifications-item .tsv-item-content { position: relative; z-index: 1; display: flex; align-items: center; min-width: 0; }
#settings-notifications-events .ts-notifications-item .tsv-item-text { display: flex; flex-direction: row; align-items: center; min-width: 0; margin-left: var(--tsv-padding-h-small); }
#settings-notifications-events .ts-notifications-item .tsv-flex-grow { flex-grow: 1; min-width: 0; }
#settings-notifications-events .ts-notifications-item .tsv-text-truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#settings-notifications-events .tsv-notifications-content-item-disabled { color: var(--tsv-font-subtitle-color); }
#settings-notifications-events .ts-notifications-content-item-subtitle { color: var(--tsv-font-subtitle-color); font-size: var(--tsv-font-size-small); }
/* Listen / Hide Advanced: 22px glyph in the text colour, label 10px after it in tint2 at .9em; 50% on hover. */
#settings-notifications-events .ts-notifications-content-item-button { margin-top: var(--tsv-padding-v-minimal); padding: 0; border: 0; border-radius: var(--tsv-border-radius); background: transparent; color: var(--tsv-font-color); font: inherit; text-align: start; cursor: pointer; --tsv-icon-base: var(--tsv-font-color); }
#settings-notifications-events .ts-notifications-content-item-button .icon { flex: none; width: var(--tsv-icon-size); height: var(--tsv-icon-size); }
#settings-notifications-events .ts-notifications-content-item-button span { margin-left: var(--tsv-padding-h-small); color: var(--tsv-tint2); font-size: .9em; white-space: nowrap; }
#settings-notifications-events .ts-notifications-content-item-button:hover { opacity: .5; }
#settings-notifications-events .ts-notifications-content-item-button:focus-visible { outline: 2px solid var(--tsv-tint2); outline-offset: 1px; }
/* Control column (.tsv-bar-item in .ts-notifications-item): no right padding, never shrinks. */
#settings-notifications-events .ts-notifications-item .tsv-bar-item { position: relative; display: flex; flex-shrink: 0; align-items: center; justify-content: center; min-width: 0; padding: 0 0 0 var(--tsv-padding-h-small); }
/* SegmentedControl: icon-only buttons padded 0 4px around the 22px glyph; shaded while the row is hovered. */
#settings-notifications-events .segmented > button { gap: 0; padding: 0 var(--tsv-padding-v-small); }
#settings-notifications-events .segmented > button .icon { width: var(--tsv-icon-size); height: var(--tsv-icon-size); }
#settings-notifications-events .tsv-notifications-content-item:hover .segmented { background: var(--tsv-shaded-bg); }
@media (forced-colors: active) {
#settings-notifications-events .ts-notifications-item > .tsv-item:hover::before { outline: 1px solid Highlight; }
#settings-notifications-events .ts-notifications-content-item-button span { color: LinkText; }
#settings-notifications-events .ts-notifications-content-item-button:focus-visible { outline-color: Highlight; }
}
-23
View File
@@ -1,23 +0,0 @@
/* Settings > Remote Apps (installed client render@4957240, main.css .ts-apps-info-button[data-v-17dc06a2],
.ts-notification-body[data-v-17dc06a2]); sections/toggles come from settings.css, the menu from .files-menu. */
:where(.settings-scroll) .ts-apps-settings .ts-widget-section-header { display: flex; align-items: center; gap: var(--tsv-padding-h-small); }
:where(.settings-scroll) .ts-apps-info-button { align-self: start; transform: translateY(-10%); }
:where(.settings-scroll) .ts-apps-settings .ts-notification-body { display: flex; flex-direction: row; flex-wrap: nowrap; align-items: center; }
:where(.settings-scroll) .ts-apps-settings .ts-notification-text { color: var(--tsv-font-subtitle-color); font-size: var(--tsv-font-size-minimal); width: 100%; }
:where(.settings-scroll) .ts-apps-settings small { color: var(--tsv-font-color); font-size: var(--tsv-font-size-minimal); }
/* ts-list with useLargeCells: icon, name + subtitle column, trailing controls */
:where(.settings-scroll) .remote-apps-list { margin: 0; padding: 0; list-style: none; }
:where(.settings-scroll) .remote-apps-cell { display: flex; align-items: center; gap: var(--tsv-padding-h-small); min-height: 44px; padding: var(--tsv-padding-v-small) var(--tsv-padding-h-small); border-radius: var(--tsv-border-radius); }
:where(.settings-scroll) .remote-apps-cell:focus-visible { outline: 2px solid var(--tsv-tint2); outline-offset: -2px; }
:where(.settings-scroll) .remote-apps-cell .icon-container { display: inline-grid; place-items: center; flex: none; width: var(--tsv-icon-size-large); height: var(--tsv-icon-size-large); }
:where(.settings-scroll) .remote-apps-cell-text { flex: 1 1 auto; min-width: 0; }
:where(.settings-scroll) .remote-apps-cell-name { color: var(--tsv-font-color); font-size: var(--tsv-font-size-content); overflow-wrap: anywhere; }
:where(.settings-scroll) .remote-apps-cell-controls { display: flex; flex: none; align-items: center; gap: var(--tsv-padding-h-small); }
.remote-apps-notice .ts-notification-body { display: flex; flex-direction: column; align-items: flex-start; }
.remote-apps-notice .ts-notification-subtitle { margin: 2px 0 4px; color: var(--tsv-font-subtitle-color); font-size: var(--tsv-font-size-minimal); overflow-wrap: anywhere; }
.remote-apps-notice-actions { display: flex; flex-wrap: wrap; gap: 6px; }
.remote-apps-doc .client-dialog-body p { margin: 0 0 8px; }
.remote-apps-doc-code { margin: 0 0 8px; padding: 8px; overflow: auto; border-radius: var(--tsv-border-radius); background: var(--tsv-input-background, rgba(0, 0, 0, 0.2)); font-size: var(--tsv-font-size-minimal); user-select: text; }
-10
View File
@@ -621,16 +621,6 @@ body:has(#self-dot[data-talking="true"]) .ts-vad-header .avatar-talking { opacit
/* ---------- module-built lists (whispers, notifications, trusted hosts); key bindings: keybinds.css ---------- */
:where(.settings-scroll) .whisper-list-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--tsv-padding-h-minimal) var(--tsv-padding-h-small); min-height: var(--tsv-row-height-large); }
:where(.settings-scroll) .whisper-list-row > span { flex: 1; min-width: 0; overflow-wrap: anywhere; }
/* .ts-notifications-item ContentItemCell: title, "Listen" (tint2, .9em) below, state control right */
:where(.settings-scroll) .ts-notifications-item { margin: 0; padding: 0; list-style: none; }
:where(.settings-scroll) .notify-row { display: flex; align-items: center; justify-content: space-between; gap: var(--tsv-padding-v-small) var(--tsv-padding-h); padding: var(--tsv-padding-v) var(--tsv-padding-h-small); font-size: var(--tsv-font-size-content); }
:where(.settings-scroll) .notify-row-inset { padding-left: calc(2 * var(--tsv-padding-h)); }
:where(.settings-scroll) .notify-text { display: flex; flex-direction: column; align-items: flex-start; min-width: 0; }
:where(.settings-scroll) .notify-row .row-name { min-width: 0; overflow-wrap: anywhere; }
:where(.settings-scroll) .notify-listen { display: inline-flex; align-items: center; gap: var(--tsv-padding-h-minimal); padding: 0; border: 0; background: transparent; color: var(--tsv-tint2); font: inherit; font-size: .9em; cursor: pointer; }
:where(.settings-scroll) .notify-listen:hover { opacity: .5; }
:where(.settings-scroll) .notify-listen .icon { width: var(--tsv-icon-size-small); height: var(--tsv-icon-size-small); }
:where(.settings-scroll) .notify-advanced > summary { padding: 0 var(--tsv-padding-h-small) var(--tsv-padding-v); color: var(--tsv-font-subtitle-color); font-size: var(--tsv-font-size-small); cursor: pointer; }
:where(.settings-scroll) .segmented .segment .icon { width: var(--tsv-icon-size-small); height: var(--tsv-icon-size-small); }
:where(.settings-scroll) .segmented.only-active-highlight > button:not([aria-checked="true"]) { color: var(--tsv-font-subtitle-color); --tsv-icon-base: var(--tsv-font-subtitle-color); }
:where(.settings-scroll) .segmented > button[aria-checked="true"] { --tsv-icon-base: var(--tsv-tint); }
+1 -1
View File
@@ -1945,7 +1945,7 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"
[[package]]
name = "teamspeach-core"
version = "0.1.4"
version = "0.1.5"
dependencies = [
"audiopus",
"base64 0.22.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "teamspeach-core"
version = "0.1.4"
version = "0.1.5"
edition = "2021"
rust-version = "1.89"
description = "TeamsPeach native TeamSpeak protocol core (stdio JSON bridge)"
@@ -36,6 +36,11 @@ navigation composition and remaining geometry are not masked or reclassified as
### Additional original subpages and icon-manager runtime proof
`C:/Users/Admin/tmp/teamspeach-all-panels-20261101/remoteapps-populated/` captures the installed
frontend with a synthetic pending `auth` event and registered application metadata. Pending and authorized
rows, Allow/Deny and the registered toggle were inspected; no original native WebSocket was used and
the undocumented event payload compatibility remains unverified.
`C:/Users/Admin/tmp/teamspeach-all-panels-20261101/video-populated/` contains the original frontend's
expanded hardware-backend list and typed codec-options page. A clearly labelled synthetic
`ffmpegCodersChanged` event supplied one H.264 encoder/decoder and bounded integer/boolean/string options;
+3 -25
View File
@@ -1,17 +1,16 @@
{
"name": "teamspeach",
"version": "0.1.4",
"version": "0.1.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "teamspeach",
"version": "0.1.4",
"version": "0.1.5",
"license": "UNLICENSED",
"dependencies": {
"electron-updater": "6.8.11",
"semver": "7.7.4",
"ws": "8.22.1"
"semver": "7.7.4"
},
"devDependencies": {
"electron": "44.9.3",
@@ -3547,27 +3546,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/ws": {
"version": "8.22.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz",
"integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
+2 -3
View File
@@ -1,7 +1,7 @@
{
"name": "teamspeach",
"productName": "TeamsPeach",
"version": "0.1.4",
"version": "0.1.5",
"description": "Desktop TeamSpeak 6 client: voice, chat and TS6 screenshare viewing",
"main": "app/main/main.js",
"private": true,
@@ -106,7 +106,6 @@
},
"dependencies": {
"electron-updater": "6.8.11",
"semver": "7.7.4",
"ws": "8.22.1"
"semver": "7.7.4"
}
}
@@ -0,0 +1,115 @@
// Notification advanced options through the real settings page, preference bridge and warning popup in the
// hidden, nonfocusable, muted offscreen window (launchApp). Disposable profile; no server, no device capture,
// no native dialog, no OS input and no Listen click, so no sound is requested.
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { tmpdir } from 'node:os';
import { launchApp, waitForAsync } from './lib/electron-app.mjs';
const args = process.argv.slice(2);
const option = key => args.includes(`--${key}`) ? args[args.indexOf(`--${key}`) + 1] : undefined;
const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-notification-advanced-qa-'));
const out = path.resolve(option('out') ?? 'smoke-out/notification-advanced');
mkdirSync(out, { recursive: true });
const result = { checks: [], errors: [], scope: 'Row context menu, Show/Hide Advanced with cancel and confirm, persisted overrides; no Listen click or audible output' };
let app, page;
const states = () => waitForAsync(page, async () => (await window.teamspeach.getPrefs()).notificationStates);
const statesMatch = (expected) => waitForAsync(page, async (want) => {
const got = (await window.teamspeach.getPrefs()).notificationStates;
return Object.entries(want).every(([key, value]) => got[key] === value);
}, expected);
const openNotifications = async () => {
await page.click('#btn-settings');
await page.click('#settings-nav [data-panel="notifications"]');
await page.waitForSelector('[data-notification-group="connection"] [data-setting="disconnected"]');
};
try {
app = await launchApp({ profile, exe: option('exe') });
page = await app.firstWindow();
page.on('pageerror', error => result.errors.push(error.message));
await page.waitForSelector('#view-onboarding', { state: 'visible' });
await page.fill('#onboarding-nick', 'Notification Advanced QA');
await page.click('#onboarding-submit');
await page.waitForSelector('#view-app', { state: 'visible' });
await openNotifications();
const sound = page.locator('#settings-notifications-events > section').first();
assert.equal(await sound.locator('.ts-card-setting-container').count(), 2, 'Sound Notifications holds only the device and volume settings');
assert.deepEqual(await sound.locator('#notification-device option').evaluateAll(nodes => nodes.slice(0, 3).map(node => node.value)), ['voice', '', 'none']);
assert.equal(await page.locator('#settings-notifications-events details').count(), 0, 'no always-visible advanced summaries');
result.checks.push('Sound section has no empty status container; options follow audio-device-selector order; no <details> rows');
const group = page.locator('[data-notification-group="connection"]');
const row = group.locator('[data-setting="disconnected"]');
await row.locator('.tsv-text-truncate').click({ button: 'right' });
const menu = page.locator('.notification-row-menu');
await menu.waitFor();
assert.equal(await menu.getByRole('menuitem').getAttribute('aria-disabled'), null);
await page.keyboard.press('Escape');
await menu.waitFor({ state: 'detached' });
assert.equal(await group.locator('[data-event]').count(), 0);
result.checks.push('Context menu opens on the coalesced row and Escape closes it without changes');
await row.locator('.tsv-text-truncate').click({ button: 'right' });
await menu.getByRole('menuitem').click();
await statesMatch({ advanced_disconnected: 1 });
await group.locator('[data-event="connection_lost"]').waitFor();
assert.equal(await row.locator('[role="radio"]').count(), 0, 'coalesced control replaced while advanced');
assert.equal(await row.locator('.tsv-notifications-content-item-disabled').count(), 1);
assert.equal(await row.locator('.ts-notifications-content-item-subtitle').count(), 1);
assert.deepEqual(await group.locator('[data-event]').evaluateAll(nodes => nodes.map(node => node.dataset.event)), ['disconnected', 'connection_lost']);
result.checks.push('Show Advanced persists, disables the coalesced row and lists its event rows');
await group.locator('[data-event="connection_lost"] [role="radio"]').nth(0).click();
await statesMatch({ event_disconnected_connection_lost: 0 });
await group.locator('[data-event="connection_lost"] .tsv-text-truncate').click({ button: 'right' });
await menu.waitFor();
assert.equal(await menu.getByRole('menuitem').getAttribute('aria-disabled'), 'true');
await page.keyboard.press('Escape');
await menu.waitFor({ state: 'detached' });
result.checks.push('Event rows save their own state; their menu offers only the disabled No Actions entry');
const dialog = page.locator('dialog.warning-dialog');
await row.locator('.tsv-bar-item button').click();
await dialog.waitFor();
await dialog.locator('.tsv-user-input-dialog-cancel').click();
await dialog.waitFor({ state: 'detached' });
assert.deepEqual(await states().then(s => [s.advanced_disconnected, s.event_disconnected_connection_lost]), [1, 0]);
assert.equal(await group.locator('[data-event="connection_lost"] [role="radio"]').nth(0).getAttribute('aria-checked'), 'true');
result.checks.push('Hide Advanced cancel keeps the section and its event override');
await row.locator('.tsv-bar-item button').click();
await dialog.waitFor();
await dialog.locator('.tsv-user-input-dialog-confirm').click();
await statesMatch({ advanced_disconnected: 0, event_disconnected_connection_lost: 0 });
await group.locator('[data-event]').first().waitFor({ state: 'detached' });
assert.equal(await row.locator('[role="radio"]').count(), 3);
const inactive = await page.evaluate(async () => {
const n = await import('./js/notifications.js');
return [n.isAdvanced('disconnected'), n.eventState('disconnected', 'connection_lost') === n.settingState('disconnected')];
});
assert.deepEqual(inactive, [false, true]);
result.checks.push('Confirmed hide deactivates the stored override without deleting it');
await row.locator('.tsv-text-truncate').click({ button: 'right' });
await menu.getByRole('menuitem').click();
await statesMatch({ advanced_disconnected: 1 });
await group.locator('[data-event="connection_lost"]').waitFor();
assert.equal(await group.locator('[data-event="connection_lost"] [role="radio"]').nth(0).getAttribute('aria-checked'), 'true');
await page.screenshot({ path: path.join(out, 'advanced-restored.png') });
result.checks.push('Show Advanced again restores the saved event choice');
const single = page.locator('[data-setting="connected"]');
await single.locator('.tsv-text-truncate').click({ button: 'right' });
await menu.getByRole('menuitem').click();
await statesMatch({ advanced_connected: 1 });
await page.locator('[data-event="connected"]').waitFor();
await page.locator('[data-event="connected"] [role="radio"]').nth(2).click();
await statesMatch({ event_connected_connected: 2 });
assert.equal(await page.evaluate(async () => (await import('./js/notifications.js')).eventState('connected', 'connected')), 2);
result.checks.push('Single-event settings also expose real advanced controls and persist their independent choice');
assert.deepEqual(result.errors, []);
result.ok = true;
} catch (error) { result.ok = false; result.error = error.stack; process.exitCode = 1; if (page) await page.screenshot({ path: path.join(out, 'failure.png') }).catch(() => {}); }
finally { if (app) await app.close(); rmSync(profile, { recursive: true, force: true }); writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2)); }
-2
View File
@@ -49,8 +49,6 @@ try {
const listGroup = page.locator('#keybind-settings .ts-keybinds-hotkeys-group').nth(7); // Whisper to List
await listGroup.locator('select').selectOption(uuid);
await listGroup.locator('.ts-keybinds-hotkeys-entry-unset button').click({ force: true });
const systemShortcut = page.locator('.keybind-menu .menu-item').first();
if (await systemShortcut.count()) await systemShortcut.click();
await page.keyboard.down('F9'); await page.keyboard.up('F9');
await waitForAsync(page, async () => (await window.teamspeach.getKeybinds()).profiles[0]?.bindings.length === 1);
await page.locator('#keybind-settings .ts-keybinds-scope').click(); // Global → In this window
+2 -16
View File
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { KeyTracker, KeyChordRecorder, RemoteChordRecorder, matchKeydown, keyupReleases, matchRemote } from '../app/renderer/js/keybind-match.js';
import { KeyTracker, KeyChordRecorder, matchKeydown, keyupReleases } from '../app/renderer/js/keybind-match.js';
const require = createRequire(import.meta.url);
const schema = require('../app/main/keybind-schema.js');
@@ -24,10 +24,9 @@ test('non-exact match fires despite other keys, and only the most specific bindi
const bindings = [bind('f9', 'F9'), bind('cf9', 'F9', { ctrl: true })];
assert.deepEqual(matchKeydown(bindings, key('F9', { shiftKey: true }), { exact: false, pressed }).map((b) => b.id), ['f9']);
assert.deepEqual(matchKeydown(bindings, key('F9', { ctrlKey: true, shiftKey: true }), { exact: false, pressed }).map((b) => b.id), ['cf9']);
assert.deepEqual(matchKeydown([{ ...bind('r', 'F9'), code: undefined, remote: { remoteApp: 'a', remoteButton: 'F9' } }], key('F9'), { exact: false, pressed }), []);
});
test('held physical bindings release on their key or any of their modifiers going up', () => {
test('held bindings release on their key or any of their modifiers going up', () => {
const b = bind('x', 'F9', { ctrl: true });
assert.equal(keyupReleases(b, key('KeyW', { ctrlKey: true })), false);
assert.equal(keyupReleases(b, key('ControlLeft')), true);
@@ -46,19 +45,6 @@ test('keyboard recorder completes on a full down/up chord and cancels on Escape'
assert.equal(modifiersOnly.keyup(key('ShiftLeft')).kind, 'update', 'a modifier alone is not a binding');
});
test('remote recorder needs one complete button press and ignores releases from before capture', () => {
const r = new RemoteChordRecorder();
assert.equal(r.feed({ identifier: 'app', button: 'old', state: false }).kind, 'none');
r.feed({ identifier: 'app', button: 'b1', state: true });
assert.deepEqual(r.feed({ identifier: 'app', button: 'b1', state: false }), { kind: 'complete', remote: { remoteApp: 'app', remoteButton: 'b1' } });
r.feed({ identifier: 'app', button: 'b1', state: true });
r.feed({ identifier: 'app', button: 'b2', state: true });
r.feed({ identifier: 'app', button: 'b1', state: false });
assert.deepEqual(r.feed({ identifier: 'app', button: 'b2', state: false }), { kind: 'reject', reason: 'single_button' });
const bindings = [{ id: 'm', remote: { remoteApp: 'app', remoteButton: 'b1' } }, { id: 'n', remote: { remoteApp: 'other', remoteButton: 'b1' } }];
assert.deepEqual(matchRemote(bindings, { identifier: 'app', button: 'b1' }).map((b) => b.id), ['m']);
});
test('variant expansion never takes another binding\'s exact chord and respects the helper limit', () => {
const a = { id: 'a', code: 'F9', ctrl: false, alt: false, shift: false, meta: false };
const b = { id: 'b', code: 'F9', ctrl: true, alt: false, shift: false, meta: false };
+33
View File
@@ -237,6 +237,39 @@ test('advanced event state overrides only that event, not its group or siblings'
assert.equal(settingState('message_received'), 0);
});
test('advanced options: upgrades keep overrides active, Hide needs confirmation and keeps them for Show Advanced', async () => {
const { isAdvanced, showAdvanced, hideAdvanced, eventState } = notifications;
const legacy = { message_received: 0, event_message_received_poked: 2 };
prefs.notificationStates = structuredClone(legacy);
S.prefs = { notificationStates: structuredClone(legacy) };
const flags = { away: true, outputMuted: true };
// Saved before the advanced flag existed: the override stays active instead of being discarded.
assert.equal(isAdvanced('message_received'), true);
assert.equal(eventState('message_received', 'poked'), STATE.IMPORTANT);
assert.equal(soundAllowed('message_received', eventState('message_received', 'poked'), flags, 'TextMessage.PokedFromAnotherClient'), true);
const asked = [];
const reply = (confirmed) => async (anchor, data) => { asked.push(data); return { confirmed, skipInFuture: false }; };
assert.equal(await hideAdvanced('message_received', null, reply(false)), false);
assert.equal(asked.length, 1);
assert.equal(asked[0].requiresConfirmationCheckbox, false);
assert.deepEqual(S.prefs.notificationStates, legacy, 'cancel writes nothing');
assert.equal(eventState('message_received', 'poked'), STATE.IMPORTANT);
assert.equal(await hideAdvanced('message_received', null, reply(true)), true);
assert.equal(isAdvanced('message_received'), false);
assert.deepEqual(S.prefs.notificationStates, { ...legacy, advanced_message_received: 0 }, 'the event state stays stored, as in the original');
assert.equal(eventState('message_received', 'poked'), STATE.DISABLED, 'confirmed hide makes the coalesced state decide');
assert.equal(soundAllowed('message_received', eventState('message_received', 'poked'), flags, 'TextMessage.PokedFromAnotherClient'), false);
await showAdvanced('message_received');
assert.equal(isAdvanced('message_received'), true);
assert.equal(eventState('message_received', 'poked'), STATE.IMPORTANT, 'Show Advanced restores the stored choice');
assert.equal(eventState('message_received', 'text_client'), STATE.DISABLED, 'events without a choice follow the setting');
assert.deepEqual(prefs.notificationStates, S.prefs.notificationStates, 'every change went through the preference bridge');
});
test('appearance defaults and exact dataset choices do not use page zoom', async () => {
const { applyAppearance } = await import('../app/renderer/js/appearance.js');
assert.deepEqual(applyAppearance({}), { displaySize: 'medium', treeStyle: 'detailed', chatStyle: 'detailed' });
-521
View File
@@ -1,521 +0,0 @@
'use strict';
// Remote Apps: a real loopback WebSocket server (ws) driven by real ws clients against a temporary profile file.
// Nothing here talks to the official client or a TeamSpeak server.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const net = require('node:net');
const path = require('node:path');
const { WebSocket } = require('ws');
const { RemoteAppsService, registerRemoteAppsIpc } = require('../app/main/remote-apps');
const { RemoteAppStore, hashKey } = require('../app/main/remote-app-state');
const snapshot = require('../app/main/remote-app-snapshot');
const APP = Object.freeze({ identifier: 'net.example.myapp', version: '1.0.0', name: 'Example Application', description: 'An example application that does things' });
const SNAP = Object.freeze({
event: 'snapshot', rev: 1, own_client_id: 7, own_channel_id: 1,
server: { name: 'Fixture' },
channels: [
{ id: 1, parent_id: 0, order: 0, name: 'Lobby', topic: '', has_password: false, is_default: true, max_clients: null, needed_talk_power: 0, codec: 'opus_voice', codec_quality: 6, icon_id: null, banner_url: null, banner_mode: null, depth: 0 },
{ id: 2, parent_id: 1, order: 0, name: 'Sub', topic: 'T', has_password: true, is_default: false, max_clients: 5, needed_talk_power: 10, codec: 'opus_music', codec_quality: 10, icon_id: 100, banner_url: null, banner_mode: null, depth: 1 },
],
clients: [
{ id: 7, uid: 'U7=', nickname: 'Alice', channel_id: 1, is_self: true, client_type: 'normal', input_muted: false, output_muted: false, input_hardware: true, output_hardware: true, away: false, away_message: null, talk_power: 0, is_talker: false, is_channel_commander: false, is_priority_speaker: false, is_recording: false, description: null, country: 'RU', server_groups: [7, 10], channel_group_id: 8, channel_group_inherited_from: 1, icon_id: null, badges: null },
{ id: 9, uid: 'U9=', nickname: 'Bob', channel_id: 2, is_self: false, client_type: 'normal', input_muted: true, output_muted: false, input_hardware: true, output_hardware: true, away: true, away_message: 'brb', talk_power: 5, is_talker: false, is_channel_commander: true, is_priority_speaker: false, is_recording: false, description: 'desc', country: null, server_groups: [8], channel_group_id: 9, channel_group_inherited_from: 2, icon_id: 3, badges: null },
],
});
function freePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
server.close(() => resolve(port));
});
});
}
async function waitFor(condition, label = 'condition', timeout = 3000) {
const start = Date.now();
while (!condition()) {
if (Date.now() - start > timeout) throw new Error(`timed out waiting for ${label}`);
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
const settle = () => new Promise((resolve) => setTimeout(resolve, 100));
function tempDir(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'teamspeach-remote-apps-'));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
return dir;
}
async function startService(t, { file, port, limits, listen = true } = {}) {
if (!file) file = path.join(tempDir(t), 'remote-apps.json');
if (!fs.existsSync(file)) {
port ??= await freePort();
fs.writeFileSync(file, JSON.stringify({ version: 1, enabled: true, port, apps: {} }));
}
const keys = [];
const logs = [];
const store = new RemoteAppStore(file);
const service = new RemoteAppsService({ store, listen, limits, onKey: (key) => keys.push(key), log: (level, message) => logs.push(`${level}: ${message}`) });
t.after(() => service.dispose());
await service.start();
return { service, store, keys, logs, file, port: store.port };
}
/** `origin` set = a browser page (Origin header); omitted = a native client (no Origin header). */
function connect(port, origin) {
const ws = new WebSocket(`ws://127.0.0.1:${port}`, origin === undefined ? {} : { origin });
const messages = [];
ws.on('message', (data) => messages.push(JSON.parse(data.toString('utf8'))));
ws.on('error', () => {});
const closed = new Promise((resolve) => ws.on('close', (code, reason) => resolve({ code, reason: reason.toString('utf8') })));
const opened = new Promise((resolve, reject) => {
ws.once('open', resolve);
ws.once('unexpected-response', () => reject(new Error('upgrade refused')));
ws.once('error', reject);
});
const client = {
ws, messages, closed, opened,
send: (value) => ws.send(typeof value === 'string' ? value : JSON.stringify(value)),
auth: (apiKey = '', meta = APP) => client.send({ type: 'auth', payload: { ...meta, content: { apiKey } } }),
key: (button, state) => client.send({ type: 'keyPress', payload: { button, state } }),
async next(type) {
await waitFor(() => messages.some((m) => m.type === type), `message ${type}`);
return messages.find((m) => m.type === type);
},
};
return client;
}
async function request(f, meta = APP, apiKey = '', origin) {
const c = connect(f.port, origin);
await c.opened;
c.auth(apiKey, meta);
await waitFor(() => f.service.status().requests.some((r) => r.identifier === meta.identifier), 'permission request');
return { c, req: f.service.status().requests.find((r) => r.identifier === meta.identifier) };
}
async function approved(f, meta = APP, origin) {
const { c, req } = await request(f, meta, '', origin);
assert.deepEqual(f.service.respond(req.id, true), { ok: true });
const reply = await c.next('auth');
return { c, reply, apiKey: reply.payload.apiKey };
}
/** Authenticates with `apiKey` from `origin`; resolves to the auth reply or the close frame. */
async function tryKey(f, apiKey, origin, meta = APP) {
const c = connect(f.port, origin);
await c.opened;
let closed = null;
c.closed.then((frame) => { closed = frame; });
c.auth(apiKey, meta);
await waitFor(() => closed !== null || c.messages.some((m) => m.type === 'auth'), 'auth outcome');
const reply = c.messages.find((m) => m.type === 'auth');
return reply ? { c, reply } : { c, closed };
}
test('nothing is published before the user approves; the approval reply carries the key and the live server view', async (t) => {
const f = await startService(t);
f.service.handleCoreEvent('c1', { event: 'state', state: 'connected' });
f.service.handleCoreEvent('c1', SNAP);
const { c, req } = await request(f);
assert.deepEqual({ ...req, id: undefined }, { ...APP, id: undefined, origin: null, reauth: false });
// Events while pending (talking, snapshot changes, keys) never reach the waiting socket.
f.service.handleCoreEvent('c1', { event: 'talking', client_id: 9, talking: true });
f.service.handleCoreEvent('c1', { ...SNAP, rev: 2, clients: SNAP.clients.slice(0, 1) });
c.key('pending.button', true);
await settle();
assert.deepEqual(c.messages, []);
assert.deepEqual(f.keys, []);
f.service.handleCoreEvent('c1', SNAP);
assert.deepEqual(f.service.respond(req.id, true), { ok: true });
const reply = await c.next('auth');
assert.deepEqual(reply.status, { code: 0, message: 'ok' });
assert.match(reply.payload.apiKey, /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
assert.equal(reply.payload.connections.length, 1);
const [conn] = reply.payload.connections;
assert.equal(conn.id, 1);
assert.equal(conn.clientId, 7);
assert.deepEqual(conn.channelInfos.rootChannels.map((ch) => ch.id), [1]);
assert.deepEqual(conn.channelInfos.subChannels['1'].map((ch) => [ch.id, ch.parentId, ch.properties.name, ch.properties.maxclients, ch.properties.flagPassword, ch.properties.codec]), [[2, '1', 'Sub', 5, true, 5]]);
assert.deepEqual(conn.clientInfos.map((ci) => [ci.id, ci.channelId, ci.properties.nickname, ci.properties.uniqueIdentifier]), [[7, 1, 'Alice', 'U7='], [9, 2, 'Bob', 'U9=']]);
assert.equal(Object.hasOwn(conn, 'properties'), false, 'server properties are not invented');
// The key is never in status (renderer) or at rest in plaintext.
assert.equal(JSON.stringify(f.service.status()).includes(reply.payload.apiKey), false);
assert.equal(fs.readFileSync(f.file, 'utf8').includes(reply.payload.apiKey), false);
assert.deepEqual(f.service.status().apps, [{ ...APP, allowed: true, origin: null, connected: true }]);
});
test('a stored key re-authenticates after a restart; wrong keys are rejected without a permission request', async (t) => {
const first = await startService(t);
const { c, apiKey } = await approved(first);
await first.service.dispose();
assert.equal((await c.closed).code, 1001);
const second = await startService(t, { file: first.file });
const again = connect(second.port);
await again.opened;
again.auth(apiKey);
const reply = await again.next('auth');
assert.equal(reply.payload.apiKey, apiKey);
assert.deepEqual(reply.payload.connections, []);
const forged = connect(second.port);
await forged.opened;
forged.auth('aef57c76-123a-acdc-5325-e33fe5c4fa27');
assert.deepEqual(await forged.closed, { code: 1008, reason: 'invalid_api_key' });
assert.deepEqual(forged.messages, []);
assert.deepEqual(second.service.status().requests, []);
});
test('an empty key for a registered app asks again; approval rotates the key and drops the old sockets', async (t) => {
const f = await startService(t);
const old = await approved(f);
const { c, req } = await request(f);
assert.equal(req.reauth, true);
f.service.respond(req.id, true);
const reply = await c.next('auth');
assert.notEqual(reply.payload.apiKey, old.apiKey);
assert.deepEqual(await old.c.closed, { code: 1008, reason: 'key_revoked' });
const stale = connect(f.port);
await stale.opened;
stale.auth(old.apiKey);
assert.deepEqual(await stale.closed, { code: 1008, reason: 'invalid_api_key' });
});
test('a pending request cannot be replaced by another socket; closing the requester withdraws it', async (t) => {
const f = await startService(t);
const { c, req } = await request(f);
const imposter = connect(f.port);
await imposter.opened;
imposter.auth('', { ...APP, name: 'Trusted Name', description: 'replaced' });
assert.deepEqual(await imposter.closed, { code: 1013, reason: 'auth_pending' });
assert.deepEqual(f.service.status().requests.map(({ id, name, description }) => ({ id, name, description })), [{ id: req.id, name: APP.name, description: APP.description }]);
c.ws.close();
await waitFor(() => f.service.status().requests.length === 0, 'request withdrawn');
assert.equal(f.service.respond(req.id, true).ok, false);
assert.deepEqual(f.service.status().apps, []);
});
test('deny registers the app as not allowed and later attempts are refused without asking', async (t) => {
const f = await startService(t);
const { c, req } = await request(f);
f.service.respond(req.id, false);
assert.deepEqual(await c.closed, { code: 1008, reason: 'denied' });
assert.deepEqual(c.messages, []);
assert.deepEqual(f.service.status().apps, [{ ...APP, allowed: false, origin: null, connected: false }]);
const retry = connect(f.port);
await retry.opened;
retry.auth('');
assert.deepEqual(await retry.closed, { code: 1008, reason: 'denied' });
assert.deepEqual(f.service.status().requests, []);
});
test('key presses report only approved transitions and every held button is released on close', async (t) => {
const f = await startService(t);
const early = connect(f.port);
await early.opened;
early.key('early', true);
assert.deepEqual(await early.closed, { code: 1008, reason: 'auth_required' });
const { c } = await approved(f);
c.key('a', true);
c.key('a', true);
c.key('a', false);
c.key('a', false);
c.send({ type: 'keyPress', payload: { button: 'b', state: 'yes' } });
c.key('b', true);
await waitFor(() => f.keys.length >= 3, 'key b');
assert.deepEqual(f.keys, [
{ identifier: APP.identifier, button: 'a', state: true },
{ identifier: APP.identifier, button: 'a', state: false },
{ identifier: APP.identifier, button: 'b', state: true },
]);
c.ws.close();
await waitFor(() => f.keys.length === 4, 'release on close');
assert.deepEqual(f.keys[3], { identifier: APP.identifier, button: 'b', state: false, synthetic: true });
});
test('two sockets of one app share a button: one down, released only when both are up', async (t) => {
const f = await startService(t);
const { c: one, apiKey } = await approved(f);
const two = connect(f.port);
await two.opened;
two.auth(apiKey);
await two.next('auth');
one.key('x', true);
await waitFor(() => f.keys.length === 1, 'down');
two.key('x', true);
one.key('x', false);
await settle();
assert.equal(f.keys.length, 1);
two.key('x', false);
await waitFor(() => f.keys.length === 2, 'release');
assert.deepEqual(f.keys, [{ identifier: APP.identifier, button: 'x', state: true }, { identifier: APP.identifier, button: 'x', state: false }]);
});
for (const [name, revoke, reason, code] of [
['toggling the app off', (f) => f.service.setAllowed(APP.identifier, false), 'denied', 1008],
['removing the app', (f) => f.service.removeApp(APP.identifier), 'removed', 1008],
['disabling remote apps', (f) => f.service.setEnabled(false), 'disabled', 1001],
['changing the port', async (f) => f.service.setPort(await freePort()), 'port_changed', 1001],
]) {
test(`${name} closes the app's sockets and releases held buttons`, async (t) => {
const f = await startService(t);
const { c } = await approved(f);
c.key('held', true);
await waitFor(() => f.keys.length === 1, 'down');
await revoke(f);
assert.deepEqual(await c.closed, { code, reason });
assert.deepEqual(f.keys, [{ identifier: APP.identifier, button: 'held', state: true }, { identifier: APP.identifier, button: 'held', state: false, synthetic: true }]);
});
}
test('removal forgets the key: the old key no longer authenticates', async (t) => {
const f = await startService(t);
const { apiKey } = await approved(f);
assert.deepEqual(f.service.removeApp(APP.identifier), { ok: true });
const c = connect(f.port);
await c.opened;
c.auth(apiKey);
assert.deepEqual(await c.closed, { code: 1008, reason: 'invalid_api_key' });
assert.deepEqual(f.service.status().apps, []);
});
test('authenticated apps receive connect, channel, move, property and talk events derived from snapshots', async (t) => {
const f = await startService(t);
const { c } = await approved(f);
f.service.handleCoreEvent('c3', { event: 'state', state: 'connected' });
f.service.handleCoreEvent('c3', SNAP);
const moved = { ...SNAP, rev: 2, clients: [SNAP.clients[0], { ...SNAP.clients[1], channel_id: 1, nickname: 'Bobby' }] };
f.service.handleCoreEvent('c3', moved);
f.service.handleCoreEvent('c3', { event: 'talking', client_id: 9, talking: true });
f.service.handleCoreEvent('c3', { event: 'audio_state', input_muted: false, output_muted: false, transmitting: true });
f.service.handleCoreEvent('c3', { event: 'audio_state', input_muted: false, output_muted: false, transmitting: true });
f.service.handleCoreEvent('c3', { event: 'state', state: 'disconnected' });
await waitFor(() => c.messages.filter((m) => m.type === 'connectStatusChanged').length === 2, 'disconnect event');
const events = c.messages.slice(1).map((m) => [m.type, m.payload.clientId ?? null]);
assert.deepEqual(events, [
['connectStatusChanged', null],
['channels', null],
['clientMoved', 7],
['clientMoved', 9],
['clientMoved', 9],
['clientPropertiesUpdated', 9],
['talkStatusChanged', 9],
['talkStatusChanged', 7],
['connectStatusChanged', null],
]);
const byType = (type) => c.messages.filter((m) => m.type === type).map((m) => m.payload);
assert.deepEqual(byType('connectStatusChanged'), [{ connectionId: 3, status: 4, info: { clientId: 7 } }, { connectionId: 3, status: 0, info: { clientId: 7 } }]);
const moves = byType('clientMoved');
assert.deepEqual(moves.map(({ clientId, oldChannelId, newChannelId }) => [clientId, oldChannelId, newChannelId]), [[7, 0, 1], [9, 0, 2], [9, 2, 1]]);
assert.deepEqual(byType('talkStatusChanged'), [{ connectionId: 3, clientId: 9, status: 1 }, { connectionId: 3, clientId: 7, status: 1 }]);
assert.equal(byType('clientPropertiesUpdated')[0].properties.nickname, 'Bobby');
});
test('core restarts and closed tabs end the cached view', async (t) => {
const f = await startService(t);
f.service.handleCoreEvent('c1', SNAP);
f.service.handleCoreEvent('c2', SNAP);
f.service.handleCoreStatus('c1', { status: 'exited' });
f.service.updateConnectionList([{ id: 'c1', state: 'disconnected' }]);
const { reply } = await approved(f);
assert.deepEqual(reply.payload.connections, []);
});
test('limits: oversized frames, floods, idle unauthenticated sockets and malformed auth are closed', async (t) => {
const f = await startService(t, { limits: { maxPayload: 1024, authTimeoutMs: 200, messageBurst: 3, messagesPerSecond: 1 } });
const big = connect(f.port);
await big.opened;
big.send({ type: 'auth', payload: { ...APP, description: 'x'.repeat(2048), content: { apiKey: '' } } });
assert.equal((await big.closed).code, 1009);
const idle = connect(f.port);
await idle.opened;
assert.deepEqual(await idle.closed, { code: 1008, reason: 'auth_timeout' });
const bad = connect(f.port);
await bad.opened;
bad.auth('', { ...APP, identifier: 'Net.Example-App' });
assert.deepEqual(await bad.closed, { code: 1008, reason: 'invalid_auth' });
const { c } = await approved(f);
for (let i = 0; i < 6; i++) c.key(`k${i}`, true);
assert.deepEqual(await c.closed, { code: 1008, reason: 'rate_limited' });
await waitFor(() => f.keys.filter((k) => !k.state).length === f.keys.filter((k) => k.state).length, 'all released');
assert.equal(f.service.status().requests.length, 0);
});
test('without the explicit listen permission no port is bound', async (t) => {
const port = await freePort();
const f = await startService(t, { port, listen: false });
assert.deepEqual({ available: f.service.status().available, listening: f.service.status().listening, failure: f.service.status().failure }, { available: false, listening: false, failure: 'test_safety' });
const c = connect(port);
await assert.rejects(c.opened);
});
test('a port already in use is reported as a start failure', async (t) => {
const blocker = net.createServer();
await new Promise((resolve) => blocker.listen(0, '127.0.0.1', resolve));
t.after(() => blocker.close());
const f = await startService(t, { port: blocker.address().port });
assert.equal(f.service.status().listening, false);
assert.equal(f.service.status().failure, 'address_in_use');
});
test('IPC accepts only the trusted window and validated values, and never returns keys', async (t) => {
const dir = tempDir(t);
const handlers = new Map();
const sent = [];
const service = registerRemoteAppsIpc({
ipcMain: { handle: (name, fn) => handlers.set(name, fn) },
trustedSender: (event) => event.trusted === true,
file: path.join(dir, 'remote-apps.json'),
listen: false,
sendToRenderer: (channel, payload) => sent.push([channel, payload]),
});
t.after(() => service.dispose());
const trusted = { trusted: true };
assert.equal(await handlers.get('remote-apps:get')({}), null);
assert.equal((await handlers.get('remote-apps:set-port')({}, 6000)).error.code, 'forbidden');
assert.equal((await handlers.get('remote-apps:set-port')(trusted, 80)).error.code, 'bad_request');
assert.equal((await handlers.get('remote-apps:set-enabled')(trusted, 'yes')).error.code, 'bad_request');
assert.equal((await handlers.get('remote-apps:set-allowed')(trusted, 'Bad Id', true)).error.code, 'bad_request');
assert.equal((await handlers.get('remote-apps:respond')(trusted, 'missing', true)).error.code, 'not_found');
const result = await handlers.get('remote-apps:set-port')(trusted, 6000);
assert.equal(result.ok, true);
assert.equal(result.status.port, 6000);
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'remote-apps.json'), 'utf8')).port, 6000);
const status = await handlers.get('remote-apps:get')(trusted);
assert.deepEqual(Object.keys(status).sort(), ['allowLanAccess', 'apps', 'available', 'enabled', 'failure', 'listening', 'port', 'requests']);
assert.ok(sent.every(([channel]) => channel === 'remote-apps:status'));
});
test('a corrupt configuration fails closed and is kept aside', (t) => {
const file = path.join(tempDir(t), 'remote-apps.json');
fs.writeFileSync(file, '{not json');
const store = new RemoteAppStore(file);
assert.equal(store.loadError, 'corrupt');
assert.equal(store.enabled, true);
assert.equal(store.port, 5899);
assert.deepEqual(store.list(), []);
assert.equal(fs.existsSync(`${file}.corrupt`), true);
});
test('snapshot mapping omits fields the core does not know', () => {
const view = snapshot.indexSnapshot(SNAP);
const bob = view.clients.get(9).properties;
assert.deepEqual(bob, {
nickname: 'Bob', uniqueIdentifier: 'U9=', type: 0, inputMuted: true, outputMuted: false, inputHardware: true, outputHardware: true,
away: true, isTalker: false, isChannelCommander: true, isPrioritySpeaker: false, isRecording: false,
awayMessage: 'brb', description: 'desc', country: '', badges: '', talkPower: 5,
serverGroups: '8', channelGroupId: '9', channelGroupInheritedChannelId: '2', iconId: 3,
});
const selfFlag = snapshot.diffEvents(1, view, snapshot.indexSnapshot({ ...SNAP, clients: [{ ...SNAP.clients[0], input_hardware: false }, SNAP.clients[1]] }));
assert.deepEqual(selfFlag.find((e) => e.type === 'clientSelfPropertyUpdated').payload, { connectionId: 1, flag: 'inputHardware', oldValue: true, newValue: false });
const created = snapshot.diffEvents(1, view, snapshot.indexSnapshot({ ...SNAP, channels: [...SNAP.channels, { ...SNAP.channels[0], id: 3, parent_id: 2, order: 0, name: 'New' }] }));
assert.deepEqual(created.map((e) => [e.type, e.payload.channelId, e.payload.parentId]), [['channelCreated', 3, '2']]);
assert.equal(snapshot.connectionNumber('c12'), 12);
assert.equal(snapshot.connectionNumber('x1'), null);
});
test('a key is bound to the origin it was approved for; re-authorization from another origin rebinds it', async (t) => {
const f = await startService(t);
const web = 'http://localhost:3000';
const first = await approved(f, APP, web);
assert.equal(f.service.status().apps[0].origin, web);
const sameOrigin = await tryKey(f, first.apiKey, web);
assert.ok(sameOrigin.reply, 'same origin authenticates');
for (const origin of [undefined, 'http://evil.example', 'null']) {
const attempt = await tryKey(f, first.apiKey, origin);
assert.deepEqual(attempt.closed, { code: 1008, reason: 'invalid_api_key' }, `origin ${origin ?? 'native'}`);
assert.deepEqual(attempt.c.messages, []);
}
assert.deepEqual(f.service.status().requests, [], 'a wrong-origin key never becomes a request');
// Empty key from a native client: explicit user approval is required, then the key moves to the new origin.
const { c, req } = await request(f);
assert.deepEqual({ origin: req.origin, reauth: req.reauth }, { origin: null, reauth: true });
f.service.respond(req.id, true);
const reply = await c.next('auth');
assert.notEqual(reply.payload.apiKey, first.apiKey);
assert.deepEqual(await first.c.closed, { code: 1008, reason: 'key_revoked' });
assert.deepEqual(await sameOrigin.c.closed, { code: 1008, reason: 'key_revoked' });
assert.equal(f.service.status().apps[0].origin, null);
assert.deepEqual((await tryKey(f, reply.payload.apiKey, web)).closed, { code: 1008, reason: 'invalid_api_key' });
assert.ok((await tryKey(f, reply.payload.apiKey)).reply);
});
test('records saved before origin binding are native-only', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'remote-apps.json');
const port = await freePort();
const key = '0b5e7a1c-4d2f-4b8e-9c3a-6f1d2e3c4b5a';
fs.writeFileSync(file, JSON.stringify({ version: 1, enabled: true, port, apps: { [APP.identifier]: { ...APP, allowed: true, keyHash: hashKey(key) } } }));
const f = await startService(t, { file });
assert.equal(f.service.status().apps[0].origin, null);
assert.deepEqual((await tryKey(f, key, 'http://localhost:8080')).closed, { code: 1008, reason: 'invalid_api_key' });
assert.ok((await tryKey(f, key)).reply);
});
test('a metadata write failure neither crashes nor blocks a valid key', async (t) => {
const f = await startService(t);
const { apiKey } = await approved(f);
// The atomic write goes through `<file>.tmp`; a directory there makes every write fail.
fs.mkdirSync(`${f.file}.tmp`);
const { c, reply } = await tryKey(f, apiKey, undefined, { ...APP, name: 'Renamed Application' });
assert.equal(reply.status.code, 0);
assert.equal(f.service.status().apps[0].name, APP.name);
assert.ok(f.logs.some((line) => line.includes('application details not saved')));
assert.ok(f.logs.every((line) => !line.includes(apiKey)));
c.key('still.works', true);
await waitFor(() => f.keys.length === 1, 'key after failed write');
// A decision that cannot be saved is reported and leaves the request pending.
const { req } = await request(f, { ...APP, identifier: 'net.example.other' });
assert.throws(() => f.service.respond(req.id, true));
assert.equal(f.service.status().requests.length, 1);
});
test('unanswered permission requests expire', async (t) => {
const f = await startService(t, { limits: { pendingTimeoutMs: 200 } });
const { c } = await request(f);
assert.deepEqual(await c.closed, { code: 1008, reason: 'auth_expired' });
assert.deepEqual(f.service.status().requests, []);
assert.deepEqual(f.service.status().apps, []);
});
test('web origins have socket and request quotas; native clients keep their slots', async (t) => {
const f = await startService(t);
const a = 'http://a.localhost';
const sockets = [];
for (let i = 0; i < 4; i++) {
const c = connect(f.port, a);
await c.opened;
sockets.push(c);
}
await assert.rejects(connect(f.port, a).opened, /upgrade refused/);
await assert.rejects(connect(f.port, 'x'.repeat(300)).opened, /upgrade refused/);
for (const c of sockets) c.ws.close();
await waitFor(() => f.service.clients.size === 0, 'sockets closed');
await request(f, { ...APP, identifier: 'a.one' }, '', a);
await request(f, { ...APP, identifier: 'a.two' }, '', a);
const third = connect(f.port, a);
await third.opened;
third.auth('', { ...APP, identifier: 'a.three' });
assert.deepEqual(await third.closed, { code: 1013, reason: 'too_many_requests' });
const other = await request(f, { ...APP, identifier: 'b.one' }, '', 'http://b.localhost');
const native = await request(f, { ...APP, identifier: 'native.one' });
assert.deepEqual([other.req.origin, native.req.origin], ['http://b.localhost', null]);
assert.equal(f.service.status().requests.length, 4);
});
+4 -8
View File
@@ -70,15 +70,13 @@ test('fresh store is "No Profile" with exact match off; profiles add/rename/acti
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('remote bindings carry no physical fields; at most six bindings per action group', () => {
test('bindings need a physical key; at most six bindings per action group', () => {
const dir = tempDir();
try {
const keys = new KeybindStore(dir);
const p = keys.addProfile('P');
keys.setBindings(p, [{ action: 'push_to_talk', remote: { remoteApp: 'com.example.deck', remoteButton: 'b1' } }]);
assert.deepEqual(keys.activeBindings()[0].remote, { remoteApp: 'com.example.deck', remoteButton: 'b1' });
assert.equal(keys.activeBindings()[0].code, undefined);
assert.throws(() => keys.setBindings(p, [{ action: 'push_to_talk', code: 'F1', remote: { remoteApp: 'a', remoteButton: 'b' } }]), /no physical/);
assert.throws(() => keys.setBindings(p, [{ action: 'push_to_talk' }]), /code/);
assert.throws(() => keys.setBindings(p, [{ action: 'push_to_talk', code: 'F1', remote: { remoteApp: 'a', remoteButton: 'b' } }]), /unknown field/);
const seven = ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7'].map((code) => ({ action: code === 'F1' ? 'microphone_mute' : 'microphone_toggle', code }));
assert.throws(() => keys.setBindings(p, seven), /at most 6/);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
@@ -91,7 +89,7 @@ test('global bindings default empty; offscreen helper cannot launch or register
assert.equal(spawned, 0); assert.equal(helper.status.global, false); assert.equal(helper.status.detail, 'test_offscreen');
});
test('binding conflicts include duplicate chords, duplicate remote buttons, the Audio PTT key and missing lists', () => {
test('binding conflicts include duplicate chords, the Audio PTT key and missing lists', () => {
const base = { code: 'F8', ctrl: false, alt: false, shift: false, meta: false, action: 'quick_whisper' };
const result = conflicts([{ ...base, id: 'a' }, { ...base, id: 'b' }], 'F8');
assert.deepEqual(new Set(result.map(value => value.id)), new Set(['a', 'b']));
@@ -100,8 +98,6 @@ test('binding conflicts include duplicate chords, duplicate remote buttons, the
assert.ok(result.some(value => value.id === id && value.reason === 'ptt'), `${id} cannot steal the push-to-talk chord`);
}
assert.deepEqual(conflicts([{ ...base, id: 'p', action: 'push_to_talk' }], 'F8'), [], 'a PTT binding on the PTT key is not a conflict');
const remote = { action: 'push_to_mute', remote: { remoteApp: 'x', remoteButton: 'y' } };
assert.equal(conflicts([{ ...remote, id: 'r1' }, { ...remote, id: 'r2' }], null).filter((c) => c.reason === 'duplicate').length, 2);
assert.deepEqual(conflicts([{ ...base, id: 'w', action: 'whisper_list', target: '' }], null, new Set()), [{ id: 'w', reason: 'select_list' }]);
});