Files
client/app/main/main.js
T

720 lines
35 KiB
JavaScript

'use strict';
const path = require('node:path');
const fs = require('node:fs');
const {
app, BrowserWindow, ipcMain, protocol, session, nativeTheme, dialog, Menu, shell, clipboard, desktopCapturer, nativeImage, net,
} = require('electron');
// A disposable profile directory for tests/second instances. Set by whoever launches the app, never by the renderer.
const profileOverride = process.env.TEAMSPEACH_PROFILE_DIR;
const normalUserData = app.getPath('userData');
if (profileOverride) {
if (!path.isAbsolute(profileOverride)) {
console.error('TEAMSPEACH_PROFILE_DIR must be an absolute path');
process.exit(2);
}
app.setPath('userData', profileOverride);
}
// Automated UI checks must not steal focus from the owner's desktop.
if (process.env.TEAMSPEACH_TEST_OFFSCREEN === '1' && (!profileOverride || path.resolve(profileOverride).toLowerCase() === path.resolve(normalUserData).toLowerCase())) {
console.error('Offscreen tests require a separate absolute disposable profile');
process.exit(2);
}
const testOffscreen = Boolean(profileOverride) && process.env.TEAMSPEACH_TEST_OFFSCREEN === '1';
if (testOffscreen) {
// Tests may replace these with fixture answers; never open a native dialog from a hidden run.
for (const name of ['showOpenDialog', 'showSaveDialog', 'showMessageBox']) dialog[name] = async () => { throw new Error('Native dialogs are disabled in offscreen tests'); };
}
const { APP_ROOT, RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths');
const { ConnectionManager } = require('./connections');
const { validateRequest } = require('./ipc-validate');
const { permissionCheckAllowed, permissionRequestAllowed } = require('./permissions');
const { CaptureController } = require('./capture');
const { AppAudioController } = require('./appaudio-main');
// Same switch the core uses for its own verbosity (see docs/bridge.md).
const RENDERER_DEBUG_LOG = /\b(debug|trace)\b/.test(process.env.TEAMSPEACH_LOG ?? '');
const { Prefs } = require('./prefs');
const { createUpdateService } = require('./updates');
const { titlebarOptions, registerTitlebarIpc, bindTitlebar } = require('./titlebar');
const i18n = require('../renderer/shared/i18n.js');
const themes = require('./themes');
const { registerChatIpc } = require('./chat-main');
const { registerRecordingIpc, approvedRecordingDirectory } = require('./recording-main');
const { registerFilesIpc } = require('./files-main');
const { registerOsSettings, defaultIconPath } = require('./os-settings-main');
const { registerIdentityIpc } = require('./identities');
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');
const { BadgeCatalog, registerBadgesIpc, officialBadgeCacheDirs } = require('./badges');
const { registerServerIconsIpc } = require('./server-icons');
const APP_SCHEME = 'app';
const APP_HOST = 'teamspeach';
const APP_ORIGIN = `${APP_SCHEME}://${APP_HOST}`;
const MERMAID_FRAME_PATH = '/mermaid-frame.html';
const MERMAID_FRAME_CSP = [
"default-src 'none'",
`script-src ${APP_ORIGIN}/vendor/mermaid/mermaid.min.js ${APP_ORIGIN}/js/markdown/mermaid-frame.js`,
"style-src 'unsafe-inline'", 'img-src data: blob:', "connect-src 'none'",
"base-uri 'none'", "form-action 'none'", "frame-src 'none'", "object-src 'none'",
`frame-ancestors ${APP_ORIGIN}`, 'sandbox allow-scripts',
].join('; ');
const MERMAID_FRAME_PERMISSIONS = 'camera=(), microphone=(), display-capture=(), geolocation=(), fullscreen=(), clipboard-read=(), clipboard-write=(), autoplay=(), usb=(), serial=(), hid=(), midi=(), screen-wake-lock=(), encrypted-media=(), picture-in-picture=(), publickey-credentials-get=()';
const CSP = [
"default-src 'none'",
"script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' tsext:",
"img-src 'self' data: blob: tsext:",
"media-src 'self' blob: mediastream:",
"font-src 'self' tsext:",
"connect-src 'self'",
"worker-src 'self'",
"base-uri 'none'",
"form-action 'none'",
`frame-src ${APP_ORIGIN}${MERMAID_FRAME_PATH}`,
"frame-ancestors 'none'",
"object-src 'none'",
].join('; ');
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.wav': 'audio/wav',
};
// Chromium hides host candidates behind mDNS names when the page has no capture permission.
// The TS6 streamer is native libwebrtc; plain host candidates keep LAN viewing working even while the mic is off.
app.commandLine.appendSwitch('disable-features', 'WebRtcHideLocalIpsWithMdns');
// Hardware video decoding policy is a launch-time Chromium switch, so it is read from the saved
// preferences before the app is ready and only changes after a restart.
const hardwareVideoDecodeAtLaunch = new Prefs(prefsFile()).get().hardwareVideoDecode;
if (!hardwareVideoDecodeAtLaunch) app.commandLine.appendSwitch('disable-accelerated-video-decode');
protocol.registerSchemesAsPrivileged([
{ scheme: APP_SCHEME, privileges: { standard: true, secure: true, supportFetchAPI: true, codeCache: true } },
themes.SCHEME_PRIVILEGE,
]);
let mainWindow = null;
let connections = null;
let prefs = null;
let capture = null;
let appAudio = null;
let themeService = null;
let osSettings = null;
let identities = null;
let whisperIpc = null;
let filesController = null;
let streamPopout = null;
let remoteApps = null;
let phishingList = null;
let badgeCatalog = null;
const gotInstanceLock = app.requestSingleInstanceLock();
if (!gotInstanceLock) {
app.quit();
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
let updates = null;
let quitting = false;
let rendererLog = null;
let rendererLogBudget = { windowStart: 0, count: 0 };
function isAppUrl(url) {
return typeof url === 'string' && url.startsWith(`${APP_ORIGIN}/`);
}
function trustedSender(event) {
return Boolean(mainWindow && event.sender === mainWindow.webContents && event.senderFrame && event.senderFrame === mainWindow.webContents.mainFrame && isAppUrl(event.senderFrame.url));
}
function sendToRenderer(channel, payload) {
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(channel, payload);
}
// ---------- server connections (one core process each) ----------
function sendConnections(list) {
remoteApps?.updateConnectionList(list);
sendToRenderer('connections:changed', { connections: list, input: connections.inputId });
}
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 });
});
connections.on('event', onCoreEvent);
connections.on('changed', sendConnections);
// The first server tab exists from the start, like the official client's initial connection tab.
connections.create();
}
/** Media that belonged to a connection's server session is no longer reachable through it. */
function onConnectionInactive(id) {
externalMedia.delete(id);
filesController?.onClosed(id);
// Capture and app audio serve the one outgoing share; once no connection is active nothing can publish.
if (!connections.anyActive()) {
appAudio?.stopAll();
capture?.cancel();
}
}
function onCoreEvent(id, evt) {
remoteApps?.handleCoreEvent(id, evt);
filesController?.onEvent(id, evt);
if (evt.event === 'audio') {
if (typeof evt.pcm !== 'string') return;
const pcm = Buffer.from(evt.pcm, 'base64');
if (pcm.length !== 1920) return;
sendToRenderer('core:audio', { connectionId: id, pcm, speakers: Array.isArray(evt.speakers) ? evt.speakers : [] });
return;
}
if (evt.event === 'state' && (evt.state === 'disconnected' || evt.state === 'connecting')) onConnectionInactive(id);
if (evt.event === 'snapshot' && Array.isArray(evt.clients)) {
for (const c of evt.clients) {
if (Array.isArray(c.myts_avatars)) for (const v of c.myts_avatars) allowExternalMedia(id, v && v.url);
}
}
sendToRenderer('core:event', { ...evt, connectionId: id });
}
// ---------- shared profile ----------
// Only these go through profile:request; `rename` on a connection is a normal per-connection core:request.
const PROFILE_COMMANDS = new Set(['profile_get', 'profile_create', 'rename']);
const PROFILE_ONLY_COMMANDS = new Set(['profile_get', 'profile_create']);
/**
* Profile commands have one explicit owner instead of "whichever tab is on screen":
* - profile_get / profile_create: the oldest connection core that is ready (creation order); it reports the
* profile's default identity. Creating the identity is additionally single-writer in the core
* (profile.lock + re-check), so a second creator fails with profile_exists.
* - rename: saves the profile nickname WITHOUT renaming on any server, so it is only sent to a ready core that
* is not connected. Renaming on a server is the per-connection `rename` (core:request) and affects only that
* server; nothing ever renames on all servers implicitly.
*/
async function profileRequest(cmd, args) {
const ready = Array.from(connections.entries.values()).filter((e) => e.core && e.status.status === 'ready');
if (ready.length === 0) return { ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } };
if (cmd !== 'rename') return connections.request(ready[0].id, cmd, args);
const idle = ready.find((e) => e.state === 'disconnected');
if (!idle) return { ok: false, error: { code: 'connected', message: 'Every server tab is connected; rename on a server instead' } };
return connections.request(idle.id, cmd, args);
}
async function onIdentityChanged() {
// Vault edits affect future connections; active server nicknames change only through explicit rename.
const profile = await profileRequest('profile_get');
if (profile.ok) sendToRenderer('profile:changed', profile.result);
}
function appendLog(file, text) {
try {
fs.mkdirSync(logsDir(), { recursive: true });
fs.appendFileSync(path.join(logsDir(), file), `${new Date().toISOString()} ${text}\n`);
} catch {
// logging must never break the app
}
}
// ---------- external images announced by the server (http/https only) ----------
const EXTERNAL_MEDIA_LIMIT = 4 * 1024 * 1024;
/** connection id → URLs announced by that connection's server. */
const externalMedia = new Map();
let mediaSession = null;
/** Only URLs a core reported from server data may be fetched; the renderer cannot add its own. */
function allowExternalMedia(id, url) {
if (typeof url !== 'string' || url.length > 2048) return;
try {
const u = new URL(url);
if (u.protocol !== 'https:' && u.protocol !== 'http:') return;
} catch {
return;
}
let urls = externalMedia.get(id);
if (!urls) externalMedia.set(id, (urls = new Set()));
if (urls.size >= 512) urls.clear();
urls.add(url);
}
function sniffImage(b) {
if (b.length >= 8 && b.readUInt32BE(0) === 0x89504e47) return 'image/png';
if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'image/jpeg';
if (b.length >= 6 && b.toString('latin1', 0, 4) === 'GIF8') return 'image/gif';
if (b.length >= 12 && b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP') return 'image/webp';
if (b.length >= 4 && b.readUInt32BE(0) === 0x00000100) return 'image/x-icon';
return null;
}
async function fetchExternalMedia(connectionId, url) {
const allowed = externalMedia.get(connectionId);
if (typeof url !== 'string' || !allowed?.has(url)) {
return { ok: false, error: { code: 'forbidden', message: 'The server did not announce this address' } };
}
if (!mediaSession) mediaSession = session.fromPartition('teamspeach-media', { cache: true });
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const res = await mediaSession.fetch(url, { signal: controller.signal, headers: { Accept: 'image/*' } });
const finalProtocol = new URL(res.url || url).protocol;
if (finalProtocol !== 'https:' && finalProtocol !== 'http:') throw new Error('redirect to a non-http scheme');
if (!res.ok) return { ok: false, error: { code: 'http_error', message: `HTTP ${res.status}` } };
const reader = res.body.getReader();
const chunks = [];
let size = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > EXTERNAL_MEDIA_LIMIT) {
controller.abort();
return { ok: false, error: { code: 'media_too_large', message: 'Image larger than 4 MiB' } };
}
chunks.push(Buffer.from(value));
}
const bytes = Buffer.concat(chunks);
// Servers mislabel images (e.g. text/plain); trust only the bytes.
const mime = sniffImage(bytes);
if (externalMedia.get(connectionId) !== allowed) return { ok: false, error: { code: 'connection_closed', message: 'The server session ended' } };
if (!mime) return { ok: false, error: { code: 'media_unsupported', message: 'Not an image' } };
return { ok: true, result: { mime, bytes: bytes.length, data: bytes.toString('base64') } };
} catch (err) {
return { ok: false, error: { code: 'io', message: err.name === 'AbortError' ? 'Download timed out' : err.message } };
} finally {
clearTimeout(timer);
}
}
// ---------- identity backup (main-only, native dialogs) ----------
/** Native dialog text in the user's interface language. */
function tr(key, params) {
return i18n.t(key, params, prefs.get().language);
}
async function chooseAvatar() {
const pick = await dialog.showOpenDialog(mainWindow, {
title: tr('native.avatar.title'),
filters: [{ name: tr('native.avatar.filter'), extensions: ['png', 'jpg', 'jpeg'] }],
properties: ['openFile'],
});
if (pick.canceled || pick.filePaths.length !== 1) return { ok: true, canceled: true };
let file;
try {
file = await fs.promises.open(pick.filePaths[0], 'r');
const stat = await file.stat();
const limit = 128 * 1024;
if (!stat.isFile() || stat.size === 0 || stat.size > limit) throw new Error(tr('native.avatar.invalid'));
// Read at most the validated size plus one byte, even if the selected file changes while open.
const data = Buffer.alloc(stat.size + 1);
let size = 0;
while (size < data.length) {
const { bytesRead } = await file.read(data, size, data.length - size, null);
if (!bytesRead) break;
size += bytesRead;
}
const image = data.subarray(0, size);
const png = image.length >= 8 && image.toString('latin1', 0, 8) === '\x89PNG\r\n\x1a\n';
const jpeg = image.length >= 3 && image[0] === 0xff && image[1] === 0xd8 && image[2] === 0xff;
if (size !== stat.size || (!png && !jpeg)) throw new Error(tr('native.avatar.invalid'));
return { ok: true, data: image.toString('base64') };
} catch {
return { ok: false, error: { code: 'invalid_avatar', message: tr('native.avatar.invalid') } };
} finally {
if (file) await file.close();
}
}
// ---------- window ----------
function createWindow() {
mainWindow = new BrowserWindow({
width: 1220,
height: 780,
minWidth: 880,
minHeight: 560,
show: false,
...(testOffscreen ? { focusable: false } : {}),
title: 'TeamsPeach',
...titlebarOptions(process.platform, nativeTheme.shouldUseDarkColors),
backgroundColor: nativeTheme.shouldUseDarkColors ? '#141b27' : '#e9edf2',
icon: path.join(__dirname, '..', 'renderer', 'assets', 'icon.png'),
webPreferences: {
...(testOffscreen ? { offscreen: true, backgroundThrottling: false, paintWhenInitiallyHidden: true } : {}),
preload: path.join(__dirname, '..', 'preload', 'preload.js'),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
nodeIntegrationInWorker: false,
webSecurity: true,
spellcheck: false,
autoplayPolicy: 'no-user-gesture-required',
devTools: !app.isPackaged || process.env.TEAMSPEACH_DEVTOOLS === '1',
},
});
if (testOffscreen) mainWindow.webContents.setAudioMuted(true);
streamPopout.attach(mainWindow);
bindTitlebar(mainWindow, nativeTheme);
osSettings.attachWindow(mainWindow);
// Hide-to-tray on close (official os settings) is decided first; only a real close continues below.
mainWindow.on('close', (event) => {
if (osSettings.interceptClose(event)) return;
});
if (!testOffscreen) mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.on('closed', () => {
appAudio?.stopAll();
capture?.cancel();
mainWindow = null;
});
mainWindow.loadURL(`${APP_ORIGIN}/index.html`);
}
function registerProtocol() {
protocol.handle(APP_SCHEME, async (request) => {
const url = new URL(request.url);
if (url.host !== APP_HOST) return new Response('Not found', { status: 404 });
let rel;
try {
rel = decodeURIComponent(url.pathname);
} catch {
return new Response('Bad request', { status: 400 });
}
if (rel === '/' || rel === '') rel = '/index.html';
const filePath = path.normalize(path.join(RENDERER_DIR, rel));
if (!filePath.startsWith(RENDERER_DIR + path.sep)) return new Response('Forbidden', { status: 403 });
const type = MIME[path.extname(filePath).toLowerCase()];
if (!type) return new Response('Forbidden', { status: 403 });
try {
const body = await fs.promises.readFile(filePath);
return new Response(body, {
status: 200,
headers: {
'Content-Type': type,
'Content-Security-Policy': rel === MERMAID_FRAME_PATH ? MERMAID_FRAME_CSP : CSP,
...(rel === MERMAID_FRAME_PATH ? { 'Permissions-Policy': MERMAID_FRAME_PERMISSIONS } : {}),
'X-Content-Type-Options': 'nosniff',
'Cross-Origin-Opener-Policy': 'same-origin',
'Referrer-Policy': 'no-referrer',
},
});
} catch {
return new Response('Not found', { status: 404 });
}
});
}
function hardenSession() {
const ses = session.defaultSession;
// Electron passes origins as "app://teamspeach/"; the policy normalises them (see permissions.js).
ses.setPermissionRequestHandler((_wc, permission, callback, details) => {
callback(!testOffscreen && details?.isMainFrame !== false && (permissionRequestAllowed(permission, details, APP_ORIGIN) || capture.permissionRequestAllowed(_wc, permission, details)));
});
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin, details) => {
return !testOffscreen && permissionCheckAllowed(permission, requestingOrigin, details, APP_ORIGIN);
});
if (testOffscreen) ses.setDisplayMediaRequestHandler((_request, callback) => callback(null));
else capture.install(ses);
}
app.on('web-contents-created', (_event, contents) => {
contents.on('will-navigate', (event, url) => {
if (!isAppUrl(url)) event.preventDefault();
});
contents.on('will-redirect', (event, url) => {
if (!isAppUrl(url)) event.preventDefault();
});
contents.setWindowOpenHandler(() => ({ action: 'deny' }));
contents.on('will-attach-webview', (event) => event.preventDefault());
});
// ---------- IPC ----------
function registerIpc() {
registerInformationIpc({ ipcMain, trustedSender, service: createInformationService({ isPackaged: app.isPackaged,
appRoot: APP_ROOT, appPath: app.getAppPath(), resourcesPath: process.resourcesPath, execPath: process.execPath,
rendererDir: RENDERER_DIR, platform: process.platform, arch: process.arch, electronVersion: process.versions.electron }) });
registerTitlebarIpc(ipcMain, () => mainWindow, APP_ORIGIN);
capture.registerIpc(ipcMain, (event) => !testOffscreen && trustedSender(event));
appAudio.registerIpc(ipcMain, (event) => !testOffscreen && trustedSender(event));
themeService.registerIpc(ipcMain, trustedSender);
registerChatIpc(ipcMain, { trustedSender, getWindow: () => mainWindow, baseDir: path.join(app.getPath('userData'), 'chat-history'), testOffscreen, shell, nativeImage, app });
registerRecordingIpc({ ipcMain, trustedSender, dialog, getWindow: () => mainWindow, testOffscreen, testProfileDir: testOffscreen ? profileOverride : null, prefs });
filesController = registerFilesIpc({ ipcMain, trustedSender, dialog, shell, clipboard, getWindow: () => mainWindow, request: (id, cmd, args) => connections.request(id, cmd, args), validConnectionId: (id) => ConnectionManager.validId(id), getConnectionEpoch: (id) => { const entry = connections.get(id); return entry?.state === 'connected' ? entry.session : null; }, settingsPath: path.join(app.getPath('userData'), 'files-settings.json'), testOffscreen, testProfileDir: testOffscreen ? profileOverride : null, tr });
osSettings = registerOsSettings({ ipcMain, trustedSender, getWindow: () => mainWindow, testOffscreen, prefs, translate: (k) => i18n.t(k, {}, prefs.get().language), iconPath: defaultIconPath() });
registerClientVolumesIpc({ ipcMain, trustedSender, connections, file: path.join(path.dirname(prefsFile()), 'client-volumes.json'), log: (level, message) => appendLog('main.log', `${level}: ${message}`) });
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}`) });
registerPhishingIpc({ ipcMain, trustedSender, list: phishingList });
phishingList.start();
badgeCatalog = new BadgeCatalog({ cacheDir: path.join(app.getPath('userData'), 'badges'),
fetchImpl: (url, init) => net.fetch(url, init), enabled: !testOffscreen,
officialCacheDirs: testOffscreen ? [] : officialBadgeCacheDirs(),
log: (level, message) => appendLog('main.log', `${level}: ${message}`) });
registerBadgesIpc({ ipcMain, trustedSender, catalog: badgeCatalog });
registerServerIconsIpc({ ipcMain, trustedSender, dialog, nativeImage, getWindow: () => mainWindow,
request: (id, cmd, args) => ['file_upload', 'file_download'].includes(cmd) ? filesController.requestTransfer(id, cmd, args) : connections.request(id, cmd, args),
validConnectionId: (id) => ConnectionManager.validId(id), getConnection: (id) => connections.get(id),
subscribeCore: (listener) => { connections.on('event', listener); return () => connections.off('event', listener); }, testOffscreen, tr });
registerServerSnapshotsIpc({ ipcMain, trustedSender, dialog, getWindow: () => mainWindow, request: (id, cmd, args) => ['file_upload', 'file_download'].includes(cmd) ? filesController.requestTransfer(id, cmd, args) : connections.request(id, cmd, args), validConnectionId: (id) => ConnectionManager.validId(id), getConnection: (id) => connections.get(id), subscribeCore: (listener) => { connections.on('event', listener); return () => connections.off('event', listener); }, testOffscreen, tr });
streamPopout = registerStreamPopout({ ipcMain, BrowserWindow, getWindow: () => mainWindow, trustedSender, appOrigin: APP_ORIGIN, getConnection: (id) => connections.get(id), testOffscreen });
ipcMain.handle('core:request', async (event, connectionId, cmd, args) => {
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
if (!ConnectionManager.validId(connectionId)) return { ok: false, error: { code: 'bad_request', message: 'Invalid server connection' } };
if (PROFILE_ONLY_COMMANDS.has(cmd)) return { ok: false, error: { code: 'bad_request', message: 'Profile commands go through profile:request' } };
if (testOffscreen && cmd === 'connect') return { ok: false, error: { code: 'test_safety', message: 'Real server connections are disabled in offscreen tests' } };
let clean;
try {
clean = validateRequest(cmd, args, { approvedRecordingDirectory: () => approvedRecordingDirectory(prefs) });
} catch (err) {
return { ok: false, error: { code: err.code || 'bad_request', message: err.message } };
}
const hasArgs = Object.keys(clean).length > 0;
const entry = connections.get(connectionId);
const epoch = entry?.session;
const core = entry?.core;
const response = await connections.request(connectionId, cmd, hasArgs ? clean : undefined);
if (!response.ok && response.error.code === 'external_media' && response.error.detail && connections.get(connectionId) === entry && entry?.session === epoch && entry?.core === core) {
const detail = response.error.detail;
allowExternalMedia(connectionId, detail.url);
if (Array.isArray(detail.urls)) for (const v of detail.urls) allowExternalMedia(connectionId, v && v.url);
}
return response;
});
// The profile (identity + nickname) is shared by every connection core; see profileRequest().
ipcMain.handle('profile:request', async (event, cmd, args) => {
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
if (!PROFILE_COMMANDS.has(cmd)) return { ok: false, error: { code: 'unknown_command', message: 'Command not allowed' } };
let clean;
try {
clean = validateRequest(cmd, args);
} catch (err) {
return { ok: false, error: { code: err.code || 'bad_request', message: err.message } };
}
return profileRequest(cmd, Object.keys(clean).length > 0 ? clean : undefined);
});
// Captured voice: routed by main to the selected input connection only (connections.setInput).
ipcMain.on('core:audio-frame', (event, frame, whisper) => {
if (!trustedSender(event)) return;
if (!(frame instanceof Uint8Array) || frame.byteLength !== 1920) return;
if (whisper !== undefined && !(Number.isInteger(whisper) && whisper >= 1 && whisper <= 0xffffffff)) return;
connections.sendAudioFrame(Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength).toString('base64'), whisper);
});
ipcMain.on('core:audio-end', (event) => {
if (!trustedSender(event)) return;
connections.endAudio();
});
ipcMain.handle('connections:list', (event) => (trustedSender(event) ? { connections: connections.list(), input: connections.inputId } : null));
ipcMain.handle('connections:create', (event) => (trustedSender(event) ? connections.create() : { ok: false, error: { code: 'forbidden', message: 'forbidden' } }));
ipcMain.handle('connections:close', (event, connectionId) => {
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
if (!ConnectionManager.validId(connectionId)) return { ok: false, error: { code: 'bad_request', message: 'Invalid server connection' } };
// The official client always keeps one connection tab; the last one is reused, never closed.
if (connections.entries.size <= 1) return { ok: false, error: { code: 'last_connection', message: 'The last server tab cannot be closed' } };
onConnectionInactive(connectionId);
return connections.close(connectionId);
});
ipcMain.handle('connections:set-input', (event, connectionId) => {
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
if (connectionId !== null && !ConnectionManager.validId(connectionId)) return { ok: false, error: { code: 'bad_request', message: 'Invalid server connection' } };
return connections.setInput(connectionId);
});
ipcMain.handle('core:restart', async (event, connectionId) => {
if (!trustedSender(event) || !ConnectionManager.validId(connectionId)) return false;
return (await connections.restart(connectionId)).ok;
});
ipcMain.handle('app:info', (event) => {
if (!trustedSender(event)) return null;
return {
appVersion: app.getVersion(),
electron: process.versions.electron,
chrome: process.versions.chrome,
platform: process.platform,
arch: process.arch,
packaged: app.isPackaged,
coreVersion: Array.from(connections.entries.values()).find((e) => e.core?.coreVersion)?.core.coreVersion ?? null,
coreBinary: resolveCoreBinary().path || null,
dataDir: dataDir(),
logsDir: logsDir(),
};
});
ipcMain.handle('prefs:get', (event) => (trustedSender(event) ? prefs.get() : null));
ipcMain.handle('prefs:set', (event, partial) => {
if (!trustedSender(event)) return { ok: false };
// Main-only: set by the recording folder dialog (recording-main.js), never by the renderer.
if (partial && typeof partial === 'object' && Object.hasOwn(partial, 'recordingFolder')) return { ok: false, message: 'prefs: recordingFolder is chosen in the folder dialog' };
const trustError = trustedHostsUpdateError(prefs.get(), partial, (host) => phishingList.has(host));
if (trustError) return { ok: false, message: trustError };
try {
const next = prefs.set(partial);
if (partial && Object.prototype.hasOwnProperty.call(partial, 'theme')) nativeTheme.themeSource = next.theme;
if (Object.hasOwn(partial, 'pttCode')) whisperIpc?.refreshBindings();
return { ok: true, prefs: next };
} catch (err) {
return { ok: false, message: err.message };
}
});
ipcMain.handle('avatar:choose', (event) => (trustedSender(event) ? chooseAvatar() : { ok: false, error: { code: 'forbidden', message: 'forbidden' } }));
ipcMain.handle('media:external', (event, connectionId, url) => (trustedSender(event) ? fetchExternalMedia(connectionId, url) : { ok: false }));
ipcMain.handle('clipboard:write', (event, text) => {
if (!trustedSender(event) || testOffscreen || typeof text !== 'string' || text.length > 4096) return false;
clipboard.writeText(text);
return true;
});
ipcMain.handle('app:video-status', (event) => {
if (!trustedSender(event)) return null;
return { hardwareDecodeAtLaunch: hardwareVideoDecodeAtLaunch, gpu: app.getGPUFeatureStatus() };
});
ipcMain.handle('app:relaunch', (event) => {
if (!trustedSender(event) || testOffscreen) return false;
app.relaunch();
app.quit();
return true;
});
ipcMain.handle('app:open-logs', async (event) => {
if (!trustedSender(event) || testOffscreen) return false;
fs.mkdirSync(logsDir(), { recursive: true });
return (await shell.openPath(logsDir())) === '';
});
ipcMain.on('app:log', (event, level, message) => {
if (!trustedSender(event) || typeof message !== 'string') return;
const now = Date.now();
if (now - rendererLogBudget.windowStart > 1000) rendererLogBudget = { windowStart: now, count: 0 };
if (++rendererLogBudget.count > 40) return;
const lvl = ['debug', 'info', 'warn', 'error'].includes(level) ? level : 'info';
// Per-burst voice diagnostics are debug level: written only when started with TEAMSPEACH_LOG=debug|trace.
if (lvl === 'debug' && !RENDERER_DEBUG_LOG) return;
if (!rendererLog) {
fs.mkdirSync(logsDir(), { recursive: true });
rendererLog = fs.createWriteStream(path.join(logsDir(), 'renderer.log'), { flags: 'a' });
}
rendererLog.write(`${new Date().toISOString()} ${lvl} ${message.slice(0, 4000).replace(/[\r\n]+/g, ' ')}\n`);
});
}
// ---------- app lifecycle ----------
app.whenReady().then(() => {
if (!gotInstanceLock) return;
Menu.setApplicationMenu(null);
prefs = new Prefs(prefsFile());
// Explicit theme choice drives Chromium's prefers-color-scheme; 'system' follows the OS.
nativeTheme.themeSource = prefs.get().theme;
registerProtocol();
themeService = themes.createThemeService({
root: themes.extensionsDir(app.getPath('userData')),
appOrigin: APP_ORIGIN,
prefs,
openPath: (dir) => shell.openPath(dir),
openExternal: (url) => shell.openExternal(url),
allowShell: !testOffscreen,
});
themeService.registerProtocol(protocol);
appAudio = new AppAudioController({
resolveBinary: () => resolveCoreBinary().path,
getWindow: () => mainWindow,
trustedFrame: (frame) => Boolean(capture?.trustedFrame(frame)),
});
capture = new CaptureController({
desktopCapturer, getWindow: () => mainWindow, appOrigin: APP_ORIGIN,
onSelected: (selection) => appAudio.authorizeSelection(selection.frame, selection.sourceId),
onCaptureGranted: (selection) => appAudio.confirmSelection(selection.frame),
});
hardenSession();
// Before IPC and the window exist, so no renderer request can find the manager missing.
startConnections();
registerIpc();
if (process.env.TEAMSPEACH_TEST_HOLD_WINDOW === '1') {
// Test harness only (scripts/lib/electron-app.mjs with --exe): Playwright cannot inject its startup loader
// into a packaged app, and attaching while the first page commits loses its utility world, so the harness
// attaches first and then creates the window through this hook.
globalThis.__teamspeachCreateWindow = () => {
delete globalThis.__teamspeachCreateWindow;
createWindow();
};
} else {
createWindow();
}
// Updates come only from published releases of the public repo; nothing installs without a click.
updates = createUpdateService({
prefs,
isSessionActive: () => connections.anyActive(),
send: (state) => sendToRenderer('update:state', state),
...(testOffscreen ? { openExternal: async () => { throw new Error('External applications are disabled in offscreen tests'); } } : {}),
});
updates.registerIpc(ipcMain, trustedSender);
updates.start();
});
app.on('window-all-closed', () => app.quit());
app.on('before-quit', (event) => {
osSettings?.markQuitting();
identities?.shutdown();
whisperIpc?.dispose();
remoteApps?.dispose();
phishingList?.stop();
badgeCatalog?.stop();
streamPopout?.dispose();
appAudio?.stopAll();
capture?.cancel();
if (quitting || !connections || !connections.running) return;
event.preventDefault();
quitting = true;
connections.stopAll().finally(() => app.quit());
});