Files
client/app/main/remote-apps.js
T

664 lines
27 KiB
JavaScript

'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 };