diff --git a/package.json b/package.json index 6a5ea3e0..ee6482c3 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "buildLibVesktop": "pnpm -C packages/libvesktop install && pnpm -C packages/libvesktop run build", "package": "pnpm build && electron-builder", "package:dir": "pnpm build && electron-builder --dir", - "lint": "oxlint src scripts", + "lint": "oxlint src scripts packages/discord-rpc", "lint:fix": "pnpm lint --fix", "fmt": "oxfmt", "fmt:check": "oxfmt --check", @@ -27,7 +27,6 @@ "generateMeta": "tsx scripts/utils/generateMeta.mts" }, "dependencies": { - "arrpc": "github:Vencord/arrpc#1dc801e8ea14d96ce8dccff416417614f058afb8", "electron-updater": "6.6.2" }, "optionalDependencies": { @@ -38,6 +37,7 @@ "@types/node": "^26.6.5", "@types/react": "19.2.9", "@vencord/types": "^1.15.14", + "discord-rpc": "workspace:*", "electron": "45.1.0", "electron-builder": "^26.18.0", "esbuild": "^0.28.2", diff --git a/packages/discord-rpc/package.json b/packages/discord-rpc/package.json new file mode 100644 index 00000000..97205e17 --- /dev/null +++ b/packages/discord-rpc/package.json @@ -0,0 +1,14 @@ +{ + "name": "discord-rpc", + "private": true, + "license": "GPL-3.0-or-later", + "main": "src/index.ts", + "types": "src/index.ts", + "dependencies": { + "@vencord/game-detection": "0.1.0-alpha.1", + "ws": "^8.21.3" + }, + "devDependencies": { + "@types/ws": "^8.18.1" + } +} diff --git a/packages/discord-rpc/src/games.ts b/packages/discord-rpc/src/games.ts new file mode 100644 index 00000000..69e0e95b --- /dev/null +++ b/packages/discord-rpc/src/games.ts @@ -0,0 +1,102 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { readFile, stat, writeFile } from "fs/promises"; + +import type { DetectableGame, RunningGame } from "@vencord/game-detection"; + +const DATABASE_URL = "https://discord.com/api/v9/applications/detectable"; +const DATABASE_MAX_AGE = 24 * 60 * 60 * 1000; +const SCAN_INTERVAL = 5000; + +// Used to toggle streamer mode, not a real application +export const STREAMER_MODE_ID = "STREAMERMODE"; +const OBS: DetectableGame = { + id: STREAMER_MODE_ID, + name: "OBS", + executables: [ + { is_launcher: false, name: "obs", os: "linux" }, + { is_launcher: false, name: "obs.exe", os: "win32" } + ] +}; + +export type { RunningGame as DetectedGame } from "@vencord/game-detection"; + +export interface GameDetectionOptions { + // Path of the native addon. It can't be bundled, so the host decides where it lives + nativePath: string; + cachePath: string; + onChange(game: RunningGame, running: boolean): void; +} + +async function loadDatabase(cachePath: string): Promise { + const stats = await stat(cachePath).catch(() => null); + + if (!stats || Date.now() - stats.mtimeMs > DATABASE_MAX_AGE) { + try { + const res = await fetch(DATABASE_URL, { + headers: stats ? { "If-Modified-Since": stats.mtime.toUTCString() } : {} + }); + + if (res.ok) await writeFile(cachePath, await res.text()); + else if (res.status !== 304) throw new Error(`HTTP ${res.status}`); + } catch (e) { + console.warn("[RPC:Games] Failed to update database, continuing with cached one:", e); + } + } + + return JSON.parse(await readFile(cachePath, "utf8")); +} + +export function startGameDetection({ nativePath, cachePath, onChange }: GameDetectionOptions) { + const games = new Map(); + let stopped = false; + let interval: NodeJS.Timeout | undefined; + + async function init() { + const native: typeof import("@vencord/game-detection") = require(nativePath); + + const database = await loadDatabase(cachePath); + if (stopped) return; + + native.setDetectableDatabase([...database, OBS]); + + const scan = async () => { + try { + const running = await native.getRunningGames(); + + for (const game of running) { + if (games.has(game.id)) continue; + + games.set(game.id, game); + onChange(game, true); + } + + for (const game of games.values()) { + if (running.some(g => g.id === game.id)) continue; + + games.delete(game.id); + onChange(game, false); + } + } catch (e) { + console.error("[RPC:Games] Failed to scan for games:", e); + } + }; + + scan(); + interval = setInterval(scan, SCAN_INTERVAL); + } + + init().catch(e => console.error("[RPC:Games] Game detection unavailable:", e)); + + return { + getGames: () => [...games.values()], + stop() { + stopped = true; + clearInterval(interval); + } + }; +} diff --git a/packages/discord-rpc/src/index.ts b/packages/discord-rpc/src/index.ts new file mode 100644 index 00000000..d8020398 --- /dev/null +++ b/packages/discord-rpc/src/index.ts @@ -0,0 +1,50 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { startIpcTransport } from "./ipc"; +import { CloseCode, RpcConnection, RpcHandlers, TransportHost } from "./types"; +import { startWebSocketTransport } from "./websocket"; + +export * from "./games"; +export * from "./types"; + +export function createRpcServer(handlers: RpcHandlers) { + const connections = new Map(); + let nextId = 0; + + const host: TransportHost = { + connect(client, connection) { + const id = String(nextId++); + connections.set(id, connection); + handlers.onConnect({ ...client, id }); + return id; + }, + request: handlers.onRequest, + disconnect(id) { + connections.delete(id); + handlers.onDisconnect(id); + } + }; + + const transports = [ + startIpcTransport(host).catch(e => console.error("[RPC:IPC] Failed to start:", e)), + startWebSocketTransport(host) + ]; + + const closeAll = (code: number, message: string) => { + for (const connection of connections.values()) connection.close(code, message); + }; + + return { + send: (id: string, json: string) => connections.get(id)?.send(json), + close: (id: string, code: number, message?: string) => connections.get(id)?.close(code, message), + closeAll, + stop() { + closeAll(CloseCode.Normal, "Server stopped"); + for (const transport of transports) transport.then(stop => stop?.()); + } + }; +} diff --git a/packages/discord-rpc/src/ipc.ts b/packages/discord-rpc/src/ipc.ts new file mode 100644 index 00000000..8f06c316 --- /dev/null +++ b/packages/discord-rpc/src/ipc.ts @@ -0,0 +1,191 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { unlinkSync } from "fs"; +import { createConnection, createServer, Socket } from "net"; +import { join } from "path"; + +import { CloseCode, RPC_VERSION, TransportHost } from "./types"; + +const enum Opcode { + Handshake, + Frame, + Close, + Ping, + Pong +} + +const HEADER_SIZE = 8; +const MAX_MESSAGE_SIZE = 3 * 1024 * 1024; +const MAX_BUFFER_SIZE = 5 * 1024 * 1024; +const MAX_CONNECTIONS = 100; +const HANDSHAKE_TIMEOUT = 10_000; +const PROBE_TIMEOUT = 1000; +const MAX_SOCKETS = 10; + +const { XDG_RUNTIME_DIR, TMPDIR, TMP, TEMP } = process.env; +const SOCKET_PATH = + process.platform === "win32" + ? "\\\\?\\pipe\\discord-ipc" + : join(XDG_RUNTIME_DIR || TMPDIR || TMP || TEMP || "/tmp", "discord-ipc"); + +function encodeFrame(opcode: Opcode, json: string) { + const size = Buffer.byteLength(json); + const frame = Buffer.alloc(HEADER_SIZE + size); + frame.writeInt32LE(opcode, 0); + frame.writeInt32LE(size, 4); + frame.write(json, HEADER_SIZE); + return frame; +} + +function createFrameReader(onFrame: (opcode: Opcode, data: any) => void) { + let buffer = Buffer.alloc(0); + + return (chunk: Buffer) => { + if (buffer.length + chunk.length > MAX_BUFFER_SIZE) throw new Error("total buffer size exceeded"); + buffer = Buffer.concat([buffer, chunk]); + + while (buffer.length >= HEADER_SIZE) { + const opcode = buffer.readInt32LE(0); + const size = buffer.readInt32LE(4); + + if (opcode < Opcode.Handshake || opcode > Opcode.Pong || size < 0) throw new Error("protocol error"); + if (size > MAX_MESSAGE_SIZE) throw new Error("message too large"); + if (buffer.length < HEADER_SIZE + size) break; + + const data = JSON.parse(buffer.toString("utf8", HEADER_SIZE, HEADER_SIZE + size)); + buffer = buffer.subarray(HEADER_SIZE + size); + onFrame(opcode, data); + } + }; +} + +function closeSocket(socket: Socket, code: number, message = "") { + socket.end(encodeFrame(Opcode.Close, JSON.stringify({ code, message }))); + socket.destroy(); +} + +function isSocketInUse(path: string) { + return new Promise(resolve => { + const socket = createConnection(path); + + const finish = (inUse: boolean) => { + clearTimeout(timeout); + socket.destroy(); + resolve(inUse); + }; + + const timeout = setTimeout(() => finish(true), PROBE_TIMEOUT); + const read = createFrameReader(opcode => opcode === Opcode.Pong && finish(true)); + + socket.on("connect", () => socket.write(encodeFrame(Opcode.Ping, "1"))); + socket.on("data", chunk => { + try { + read(chunk as Buffer); + } catch { + finish(true); + } + }); + // Only a failed connect proves nobody is listening. Unlinking a live socket would break its owner + socket.on("error", (e: NodeJS.ErrnoException) => finish(e.code !== "ENOENT" && e.code !== "ECONNREFUSED")); + }); +} + +async function findAvailableSocket() { + for (let i = 0; i < MAX_SOCKETS; i++) { + const path = `${SOCKET_PATH}-${i}`; + if (await isSocketInUse(path)) continue; + + if (process.platform !== "win32") { + try { + unlinkSync(path); + } catch {} + } + + return path; + } + + throw new Error("No available ipc socket"); +} + +function handleConnection(socket: Socket, host: TransportHost) { + let id: string | undefined; + + const handshakeTimeout = setTimeout( + () => closeSocket(socket, CloseCode.Abnormal, "Handshake timeout"), + HANDSHAKE_TIMEOUT + ); + + const onHandshake = (data: { v?: unknown; client_id?: string }) => { + if (id != null) throw new Error("already did handshake"); + + const version = Number(data.v); + if (version !== RPC_VERSION) { + return closeSocket(socket, CloseCode.InvalidVersion, `Invalid Version: ${data.v}`); + } + + clearTimeout(handshakeTimeout); + + id = host.connect( + { transport: "ipc", clientId: data.client_id ?? null, origin: null, version }, + { + send: json => socket.write(encodeFrame(Opcode.Frame, json)), + close: (code, message) => closeSocket(socket, code, message) + } + ); + }; + + const read = createFrameReader((opcode, data) => { + switch (opcode) { + case Opcode.Handshake: + onHandshake(data); + break; + case Opcode.Frame: + if (id == null) throw new Error("did not handshake"); + host.request(id, data); + break; + case Opcode.Close: + closeSocket(socket, CloseCode.Normal, "client disconnect"); + break; + case Opcode.Ping: + socket.write(encodeFrame(Opcode.Pong, JSON.stringify(data))); + break; + } + }); + + socket.on("data", chunk => { + try { + read(chunk as Buffer); + } catch (e) { + closeSocket(socket, CloseCode.Unsupported, String(e)); + } + }); + + socket.on("error", e => console.error("[RPC:IPC] Socket error:", e)); + socket.on("close", () => { + clearTimeout(handshakeTimeout); + if (id != null) host.disconnect(id); + }); +} + +export async function startIpcTransport(host: TransportHost) { + let connections = 0; + + const server = createServer(socket => { + if (connections >= MAX_CONNECTIONS) return closeSocket(socket, CloseCode.Abnormal, "Server at capacity"); + + connections++; + socket.on("close", () => connections--); + handleConnection(socket, host); + }); + + server.on("error", e => console.error("[RPC:IPC] Server error:", e)); + + const path = await findAvailableSocket(); + server.listen(path, () => console.log("[RPC:IPC] Listening on", path)); + + return () => server.close(); +} diff --git a/packages/discord-rpc/src/types.ts b/packages/discord-rpc/src/types.ts new file mode 100644 index 00000000..f30399af --- /dev/null +++ b/packages/discord-rpc/src/types.ts @@ -0,0 +1,41 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +export const RPC_VERSION = 1; + +export const enum CloseCode { + Normal = 1000, + Unsupported = 1003, + Abnormal = 1006, + InvalidVersion = 4004, + InvalidEncoding = 4005 +} + +export interface RpcClient { + id: string; + transport: "ipc" | "ws"; + clientId: string | null; + // null for ipc. Browsers always send one, other websocket clients get "" + origin: string | null; + version: number; +} + +export interface RpcHandlers { + onConnect(client: RpcClient): void; + onRequest(id: string, payload: unknown): void; + onDisconnect(id: string): void; +} + +export interface RpcConnection { + send(json: string): void; + close(code: number, message?: string): void; +} + +export interface TransportHost { + connect(client: Omit, connection: RpcConnection): string; + request(id: string, payload: unknown): void; + disconnect(id: string): void; +} diff --git a/packages/discord-rpc/src/websocket.ts b/packages/discord-rpc/src/websocket.ts new file mode 100644 index 00000000..aa3c05d0 --- /dev/null +++ b/packages/discord-rpc/src/websocket.ts @@ -0,0 +1,78 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { createServer, IncomingMessage, Server } from "http"; + +import { WebSocket, WebSocketServer } from "ws"; + +import { CloseCode, RPC_VERSION, TransportHost } from "./types"; + +const FIRST_PORT = 6463; +const LAST_PORT = 6472; +const MAX_MESSAGE_SIZE = 3 * 1024 * 1024; + +function handleConnection(socket: WebSocket, request: IncomingMessage, host: TransportHost) { + const params = new URL(request.url!, "http://localhost").searchParams; + + const encoding = params.get("encoding") ?? "json"; + if (encoding !== "json") return socket.close(CloseCode.InvalidEncoding, `Invalid Encoding: ${encoding}`); + + const version = Number(params.get("v")); + if (version !== RPC_VERSION) return socket.close(CloseCode.InvalidVersion, `Invalid Version: ${params.get("v")}`); + + const id = host.connect( + { transport: "ws", clientId: params.get("client_id"), origin: request.headers.origin ?? "", version }, + { + send: json => socket.send(json), + close(code, message) { + try { + socket.close(code, message); + } catch { + // ws refuses codes that can't go on the wire, like 1006 + socket.terminate(); + } + } + } + ); + + socket.on("error", e => console.error("[RPC:WS] Socket error:", e)); + socket.on("close", () => host.disconnect(id)); + socket.on("message", data => { + try { + host.request(id, JSON.parse(data.toString())); + } catch { + socket.close(CloseCode.Unsupported, "Payload not json"); + } + }); +} + +function tryListen(server: Server, port: number) { + return new Promise(resolve => { + server.once("error", () => resolve(false)); + server.listen(port, "127.0.0.1", () => resolve(true)); + }); +} + +export async function startWebSocketTransport(host: TransportHost) { + for (let port = FIRST_PORT; port <= LAST_PORT; port++) { + const server = createServer((_, res) => res.writeHead(404).end()); + if (!(await tryListen(server, port))) continue; + + server.on("error", e => console.error("[RPC:WS] Server error:", e)); + + const webSocketServer = new WebSocketServer({ server, maxPayload: MAX_MESSAGE_SIZE }); + webSocketServer.on("connection", (socket, request) => handleConnection(socket, request, host)); + + console.log("[RPC:WS] Listening on", port); + + return () => { + webSocketServer.close(); + server.close(); + }; + } + + console.error("[RPC:WS] No available port"); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3f37785e..9b3ac913 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -169,9 +169,6 @@ importers: .: dependencies: - arrpc: - specifier: github:Vencord/arrpc#1dc801e8ea14d96ce8dccff416417614f058afb8 - version: https://codeload.github.com/Vencord/arrpc/tar.gz/1dc801e8ea14d96ce8dccff416417614f058afb8 electron-updater: specifier: 6.6.2 version: 6.6.2(patch_hash=080505564abb2ebbda932bbf8fe91540c74dd905de994888d52ffce6f882f887)(supports-color@7.2.0) @@ -188,6 +185,9 @@ importers: '@vencord/types': specifier: ^1.15.14 version: 1.15.14(@types/react-dom@19.2.3(@types/react@19.2.9))(@types/react@19.2.9) + discord-rpc: + specifier: workspace:* + version: link:packages/discord-rpc electron: specifier: 45.1.0 version: 45.1.0(supports-color@7.2.0) @@ -229,6 +229,19 @@ importers: specifier: ^7.2.5 version: 7.2.5(supports-color@7.2.0) + packages/discord-rpc: + dependencies: + '@vencord/game-detection': + specifier: 0.1.0-alpha.1 + version: 0.1.0-alpha.1 + ws: + specifier: ^8.21.3 + version: 8.21.3 + devDependencies: + '@types/ws': + specifier: ^8.18.1 + version: 8.18.2 + packages/libvesktop: devDependencies: node-addon-api: @@ -854,11 +867,17 @@ packages: '@types/responselike@1.0.3': resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==} + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + '@vencord/discord-types@1.15.14': resolution: {integrity: sha512-ZMzj0qLVPrHzXEkaAaDW4pLZdEBNjrNPakQrDMy7JWnCGZZbhviNFSVCSp6ihBWrPMmap5lsOPjkkOc58ho2cw==} peerDependencies: '@types/react': 19.2.3 + '@vencord/game-detection@0.1.0-alpha.1': + resolution: {integrity: sha512-5SqfcX2KEY4deEcKUncaW7t8KgmRF2QrePJM9H5tBiXZYB6k+VWjh/8ypfALBjMfXGRBX34ZXhmcJI/cv3SIcQ==} + '@vencord/types@1.15.14': resolution: {integrity: sha512-mJIx1ikRa3QyWh+mZlP/HC5EU4Sb6Jlv1xSjyHO4WaJXybr5tEKsPinwMh3zosjpEubj1Ious28X5TFOW36IFg==} peerDependencies: @@ -941,11 +960,6 @@ packages: argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} - arrpc@https://codeload.github.com/Vencord/arrpc/tar.gz/1dc801e8ea14d96ce8dccff416417614f058afb8: - resolution: {gitHosted: true, integrity: sha512-/hVH9ZN2J1S2uExkz/8DjsuskA3YYcWb9oXRyaRbPExybJkvx33bpZsWOIVqgZO85ihn4wb9J97JdeWO+HIhrQ==, tarball: https://codeload.github.com/Vencord/arrpc/tar.gz/1dc801e8ea14d96ce8dccff416417614f058afb8} - version: 3.7.0 - hasBin: true - asn1js@3.0.10: resolution: {integrity: sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==} engines: {node: '>=12.0.0'} @@ -2835,12 +2849,18 @@ snapshots: dependencies: '@types/node': 26.6.5 + '@types/ws@8.18.2': + dependencies: + '@types/node': 26.6.5 + '@vencord/discord-types@1.15.14(@types/react@19.2.9)': dependencies: '@types/react': 19.2.9 moment: 2.30.1 type-fest: 5.10.0 + '@vencord/game-detection@0.1.0-alpha.1': {} + '@vencord/types@1.15.14(@types/react-dom@19.2.3(@types/react@19.2.9))(@types/react@19.2.9)': dependencies: '@types/node': 26.6.5 @@ -2965,13 +2985,6 @@ snapshots: argparse@2.0.1: {} - arrpc@https://codeload.github.com/Vencord/arrpc/tar.gz/1dc801e8ea14d96ce8dccff416417614f058afb8: - dependencies: - ws: 8.21.3 - transitivePeerDependencies: - - bufferutil - - utf-8-validate - asn1js@3.0.10: dependencies: pvtsutils: 1.3.6 diff --git a/scripts/build/build.mts b/scripts/build/build.mts index 033fa6c6..852c5d1a 100644 --- a/scripts/build/build.mts +++ b/scripts/build/build.mts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ -import { copyFile } from "fs/promises"; +import { copyFile, rm } from "fs/promises"; import { BuildContext, BuildOptions, context } from "esbuild"; @@ -54,6 +54,19 @@ async function copyVenmic() { ]).catch(() => console.warn("Failed to copy venmic. Building without venmic support")); } +async function copyGameDetection() { + const prebuilds = "./node_modules/@vencord/game-detection/prebuilds"; + + return Promise.all( + ["x64", "arm64"].map(async arch => { + const dest = `./static/dist/game-detection-${arch}.node`; + // Overwriting in place crashes a running instance, as the addon is mapped into memory + await rm(dest, { force: true }); + await copyFile(`${prebuilds}/${process.platform}-${arch}/rpc_native.node`, dest); + }) + ).catch(() => console.warn("Failed to copy game detection. Building without game detection support")); +} + async function copyLibVesktop() { if (process.platform !== "linux") return; @@ -77,18 +90,13 @@ async function copyLibVesktop() { await Promise.all([ copyVenmic(), copyLibVesktop(), + copyGameDetection(), createContext({ ...NodeCommonOpts, entryPoints: ["src/main/index.ts"], outfile: "dist/js/main.js", footer: { js: "//# sourceURL=VesktopMain" } }), - createContext({ - ...NodeCommonOpts, - entryPoints: ["src/main/arrpc/worker.ts"], - outfile: "dist/js/arRpcWorker.js", - footer: { js: "//# sourceURL=VesktopArRpcWorker" } - }), createContext({ ...NodeCommonOpts, entryPoints: ["src/preload/index.ts"], diff --git a/src/main/arrpc/index.ts b/src/main/arrpc/index.ts deleted file mode 100644 index 3411e235..00000000 --- a/src/main/arrpc/index.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Vesktop, a desktop app aiming to give you a snappier Discord Experience - * Copyright (c) 2023 Vendicated and Vencord contributors - * SPDX-License-Identifier: GPL-3.0-or-later - */ - -import { join, resolve } from "path"; -import { MessageChannel, Worker } from "worker_threads"; - -import { SESSION_DATA_DIR } from "main/constants"; -import { IpcCommands } from "shared/IpcEvents"; - -import { sendRendererCommand } from "../ipcCommands"; -import { Settings } from "../settings"; -import { ArRpcEvent, ArRpcHostEvent } from "./types"; - -let worker: Worker; - -const inviteCodeRegex = /^(\w|-)+$/; - -export async function initArRPC() { - if (worker || !Settings.store.arRPC) return; - - process.env.ARRPC_DETECTABLE_CACHE_PATH = join(SESSION_DATA_DIR, "arrpc-detectable-db.json"); - - try { - const { port1: hostPort, port2: workerPort } = new MessageChannel(); - - worker = new Worker(resolve(__dirname, "./arRpcWorker.js"), { - workerData: { - workerPort - }, - transferList: [workerPort] - }); - - hostPort.on("message", async ({ type, nonce, data }: ArRpcEvent) => { - switch (type) { - case "activity": { - sendRendererCommand(IpcCommands.RPC_ACTIVITY, data); - break; - } - - case "invite": { - const invite = String(data); - - const response: ArRpcHostEvent = { - type: "ack-invite", - nonce, - data: false - }; - - if (!inviteCodeRegex.test(invite)) { - return hostPort.postMessage(response); - } - - response.data = await sendRendererCommand(IpcCommands.RPC_INVITE, invite).catch(() => false); - - hostPort.postMessage(response); - break; - } - - case "link": { - const response: ArRpcHostEvent = { - type: "ack-link", - nonce: nonce, - data: false - }; - - response.data = await sendRendererCommand(IpcCommands.RPC_DEEP_LINK, data).catch(() => false); - - hostPort.postMessage(response); - break; - } - } - }); - } catch (e) { - console.error("Failed to start arRPC server", e); - } -} - -Settings.addChangeListener("arRPC", initArRPC); diff --git a/src/main/arrpc/types.ts b/src/main/arrpc/types.ts deleted file mode 100644 index 6e2c7ee6..00000000 --- a/src/main/arrpc/types.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Vesktop, a desktop app aiming to give you a snappier Discord Experience - * Copyright (c) 2025 Vendicated and Vesktop contributors - * SPDX-License-Identifier: GPL-3.0-or-later - */ - -export type ArRpcEvent = ArRpcActivityEvent | ArRpcInviteEvent | ArRpcLinkEvent; -export type ArRpcHostEvent = ArRpcHostAckInviteEvent | ArRpcHostAckLinkEvent; - -export interface ArRpcActivityEvent { - type: "activity"; - nonce: string; - data: string; -} - -export interface ArRpcInviteEvent { - type: "invite"; - nonce: string; - data: string; -} - -export interface ArRpcLinkEvent { - type: "link"; - nonce: string; - data: any; -} - -export interface ArRpcHostAckInviteEvent { - type: "ack-invite"; - nonce: string; - data: boolean; -} - -export interface ArRpcHostAckLinkEvent { - type: "ack-link"; - nonce: string; - data: boolean; -} diff --git a/src/main/arrpc/worker.ts b/src/main/arrpc/worker.ts deleted file mode 100644 index e0545f6d..00000000 --- a/src/main/arrpc/worker.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Vesktop, a desktop app aiming to give you a snappier Discord Experience - * Copyright (c) 2025 Vendicated and Vesktop contributors - * SPDX-License-Identifier: GPL-3.0-or-later - */ - -import { randomUUID } from "crypto"; -import { MessagePort, workerData } from "worker_threads"; - -import Server from "arrpc"; - -import { ArRpcEvent, ArRpcHostEvent } from "./types"; - -let server: any; - -type InviteCallback = (valid: boolean) => void; -type LinkCallback = InviteCallback; - -const inviteCallbacks = new Map(); -const linkCallbacks = new Map(); - -(async function () { - const { workerPort } = workerData as { workerPort: MessagePort }; - - server = await new Server(); - - server.on("activity", (data: any) => { - const event: ArRpcEvent = { - type: "activity", - data: JSON.stringify(data), - nonce: randomUUID() - }; - workerPort.postMessage(event); - }); - - server.on("invite", (invite: string, callback: InviteCallback) => { - const nonce = randomUUID(); - inviteCallbacks.set(nonce, callback); - - const event: ArRpcEvent = { - type: "invite", - data: invite, - nonce - }; - workerPort.postMessage(event); - }); - - server.on("link", async (data: any, callback: LinkCallback) => { - const nonce = randomUUID(); - linkCallbacks.set(nonce, callback); - - const event: ArRpcEvent = { - type: "link", - data, - nonce - }; - workerPort.postMessage(event); - }); - - workerPort.on("message", (e: ArRpcHostEvent) => { - switch (e.type) { - case "ack-invite": { - inviteCallbacks.get(e.nonce)?.(e.data); - inviteCallbacks.delete(e.nonce); - break; - } - case "ack-link": { - linkCallbacks.get(e.nonce)?.(e.data); - linkCallbacks.delete(e.nonce); - break; - } - } - }); -})(); diff --git a/src/main/main.ts b/src/main/main.ts index 9f2e241d..00edb879 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -7,6 +7,7 @@ import "./cli"; import "./updater"; import "./ipc"; +import "./rpc"; import "./userAssets"; import "./vesktopProtocol"; import { app, BrowserWindow, nativeTheme } from "electron"; diff --git a/src/main/mainWindow.ts b/src/main/mainWindow.ts index 83df0373..1ed870b6 100644 --- a/src/main/mainWindow.ts +++ b/src/main/mainWindow.ts @@ -23,7 +23,6 @@ import { once } from "shared/utils/once"; import type { SettingsStore } from "shared/utils/SettingsStore"; import { createAboutWindow } from "./about"; -import { initArRPC } from "./arrpc"; import { CommandLine } from "./cli"; import { BrowserUserAgent, DEFAULT_HEIGHT, DEFAULT_WIDTH, MIN_HEIGHT, MIN_WIDTH } from "./constants"; import { AppEvents } from "./events"; @@ -516,5 +515,4 @@ export async function createWindows() { }); mainWin.webContents.on("render-process-gone", (event, details) => console.log(details)); - initArRPC(); } diff --git a/src/main/rpc/index.ts b/src/main/rpc/index.ts new file mode 100644 index 00000000..04c89732 --- /dev/null +++ b/src/main/rpc/index.ts @@ -0,0 +1,73 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { join } from "path"; + +import { CloseCode, createRpcServer, startGameDetection } from "discord-rpc"; +import { SESSION_DATA_DIR } from "main/constants"; +import { IpcCommands, IpcEvents } from "shared/IpcEvents"; +import { STATIC_DIR } from "shared/paths"; + +import { sendRendererCommand } from "../ipcCommands"; +import { Settings } from "../settings"; +import { handle } from "../utils/ipcWrappers"; + +let server: ReturnType | null = null; +let gameDetection: ReturnType | null = null; +let rendererReady = false; + +function sendToRenderer(id: string, command: IpcCommands, data: unknown) { + sendRendererCommand(command, data).catch(() => server?.close(id, CloseCode.Abnormal, "Renderer unavailable")); +} + +function sendGame(game: unknown, running: boolean) { + sendRendererCommand(IpcCommands.RPC_GAME, { game, running }).catch(() => {}); +} + +function start() { + server = createRpcServer({ + onConnect: client => sendToRenderer(client.id, IpcCommands.RPC_CONNECT, client), + // Sent as json since objects from the bridge can't be relied on to be mutable, which Discord's handlers expect + onRequest: (id, payload) => + sendToRenderer(id, IpcCommands.RPC_REQUEST, { id, payload: JSON.stringify(payload) }), + onDisconnect: id => sendRendererCommand(IpcCommands.RPC_DISCONNECT, id).catch(() => {}) + }); + + gameDetection = startGameDetection({ + nativePath: join(STATIC_DIR, `dist/game-detection-${process.arch}.node`), + cachePath: join(SESSION_DATA_DIR, "arrpc-detectable-db.json"), + onChange: sendGame + }); +} + +function stop() { + if (!server) return; + + server.stop(); + gameDetection!.stop(); + server = gameDetection = null; + + sendRendererCommand(IpcCommands.RPC_RESET).catch(() => {}); +} + +handle(IpcEvents.RPC_READY, () => { + rendererReady = true; + + if (server) { + server.closeAll(CloseCode.Normal, "Renderer reloaded"); + gameDetection!.getGames().forEach(game => sendGame(game, true)); + } else if (Settings.store.arRPC) { + start(); + } +}); + +handle(IpcEvents.RPC_SEND, (_, id: string, json: string) => server?.send(id, json)); +handle(IpcEvents.RPC_CLOSE, (_, id: string, code: number, message?: string) => server?.close(id, code, message)); + +Settings.addChangeListener("arRPC", enabled => { + if (!enabled) stop(); + else if (rendererReady && !server) start(); +}); diff --git a/src/preload/VesktopNative.ts b/src/preload/VesktopNative.ts index 1dd6710f..2c8ece10 100644 --- a/src/preload/VesktopNative.ts +++ b/src/preload/VesktopNative.ts @@ -103,6 +103,11 @@ export const VesktopNative = { launchGpu: () => invoke(IpcEvents.DEBUG_LAUNCH_GPU), launchWebrtcInternals: () => invoke(IpcEvents.DEBUG_LAUNCH_WEBRTC_INTERNALS) }, + rpc: { + ready: () => invoke(IpcEvents.RPC_READY), + send: (id: string, json: string) => invoke(IpcEvents.RPC_SEND, id, json), + close: (id: string, code: number, message?: string) => invoke(IpcEvents.RPC_CLOSE, id, code, message) + }, commands: { onCommand(cb: (message: IpcMessage) => void) { ipcRenderer.on(IpcEvents.IPC_COMMAND, (_, message) => cb(message)); diff --git a/src/renderer/arrpc.ts b/src/renderer/arrpc.ts deleted file mode 100644 index 3c14d17c..00000000 --- a/src/renderer/arrpc.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Vesktop, a desktop app aiming to give you a snappier Discord Experience - * Copyright (c) 2025 Vendicated and Vencord contributors - * SPDX-License-Identifier: GPL-3.0-or-later - */ - -import type arRpcPlugin from "@vencord/types/plugins/arRPC.web"; -import { Logger } from "@vencord/types/utils"; -import { findLazy, onceReady } from "@vencord/types/webpack"; -import { FluxDispatcher, InviteActions, StreamerModeStore } from "@vencord/types/webpack/common"; -import { IpcCommands } from "shared/IpcEvents"; - -import { onIpcCommand } from "./ipcCommands"; -import { Settings } from "./settings"; - -const logger = new Logger("VesktopRPC", "#5865f2"); - -const arRPC = Vencord.Plugins.plugins["WebRichPresence (arRPC)"] as typeof arRpcPlugin; - -let userDisabledStreamerMode = false; - -onIpcCommand(IpcCommands.RPC_ACTIVITY, async jsonData => { - if (!Settings.store.arRPC) return; - - await onceReady; - - const data = JSON.parse(jsonData); - - if (data.socketId === "STREAMERMODE" && StreamerModeStore.autoToggle) { - const value = data.activity?.application_id === "STREAMERMODE"; - - if (!value) { - userDisabledStreamerMode = false; - } else if (userDisabledStreamerMode) { - return; - } - - FluxDispatcher.dispatch({ - type: "STREAMER_MODE_UPDATE", - key: "enabled", - value, - isAuto: true - }); - - return; - } - - arRPC.handleEvent(new MessageEvent("message", { data: jsonData })); -}); - -onceReady.then(() => { - FluxDispatcher.subscribe("STREAMER_MODE_UPDATE", e => { - if (!e.isAuto && !e.value) { - userDisabledStreamerMode = true; - } - }); -}); - -onIpcCommand(IpcCommands.RPC_INVITE, async code => { - const { invite } = await InviteActions.resolveInvite(code, "Desktop Modal"); - if (!invite) return false; - - VesktopNative.win.focus(); - - FluxDispatcher.dispatch({ - type: "INVITE_MODAL_OPEN", - invite, - code, - context: "APP" - }); - - return true; -}); - -const { DEEP_LINK } = findLazy(m => m.DEEP_LINK?.handler); - -onIpcCommand(IpcCommands.RPC_DEEP_LINK, async data => { - logger.debug("Opening deep link:", data); - try { - DEEP_LINK.handler({ args: data }); - return true; - } catch (err) { - logger.error("Failed to open deep link:", err); - return false; - } -}); diff --git a/src/renderer/components/settings/Settings.tsx b/src/renderer/components/settings/Settings.tsx index 6fc35904..86f4151c 100644 --- a/src/renderer/components/settings/Settings.tsx +++ b/src/renderer/components/settings/Settings.tsx @@ -135,7 +135,7 @@ const SettingsOptions: Record> { key: "arRPC", title: "Rich Presence", - description: "Enables Rich Presence via arRPC" + description: "Lets games and apps connect to Vesktop for Rich Presence and game detection" }, { diff --git a/src/renderer/index.ts b/src/renderer/index.ts index 1e6f6b5c..5f31e9ee 100644 --- a/src/renderer/index.ts +++ b/src/renderer/index.ts @@ -8,7 +8,7 @@ import "./themedSplash"; import "./ipcCommands"; import "./appBadge"; import "./fixes"; -import "./arrpc"; +import "./rpc"; import "__patches__"; // auto generated by the build script export * as Components from "./components"; diff --git a/src/renderer/patches/rpc.ts b/src/renderer/patches/rpc.ts new file mode 100644 index 00000000..d167f47b --- /dev/null +++ b/src/renderer/patches/rpc.ts @@ -0,0 +1,80 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { setObservedGamesCallback } from "../rpc"; +import { addPatch } from "./shared"; + +addPatch({ + patches: [ + // RunningGameStore has everything needed for RPC even on Web, it just has no native server for it. Re-enable support + { + find: 'displayName="RunningGameStore"', + // The lock check throws on web and crashes the UI, so only enable detection if it can be patched too + group: true, + replacement: [ + { + match: /if\((\i)\)(?=.+?canCollectExecutableFingerprintsForRunningGames\(\)\{return \1\})/, + replace: "if(true)" + }, + // Function used by the Overlay and called for running games. The overlay causes a crash due to missing native utils + // Return false to make the lock fail, which skips Overlay + { + match: /acquireLock=\i=>\{/, + replace: "$&return false;" + } + ] + }, + + { + find: ",setSystemTrayApplications", + replacement: [ + { + match: /setObservedGamesCallback\(\i,\i,(\i),\i\)\{/, + replace: "$&return VesktopPatchGlobals.setObservedGamesCallback($1);" + }, + { + match: /setGameDetection(Error)?Callback\(\i\)\{/g, + replace: "$&return;" + }, + // Called by overlay for running games. Will print an ugly error to the console due to missing native utils + { + match: /((?:GetWindowFullscreenTypeByPid|GetWindowFullscreenTypeExtraByPid|GameDisplayModeIsGameSupported)\((?:\i,)*\i\)\{let\{\i:\i\}=)this\.getDiscordUtils\(\)/g, + replace: "$1{}" + } + ] + }, + + // The card above the user panel. Commented out because: + // - Patch doesn't seem very stable + // - This has high crash potential. It's a UI element that always renders and Discord may introduce DiscordNative usage, as it is + // supposed to be Desktop-only + + // { + // find: 'location:"ActivityPanelGameCard",applicationId', + // replacement: { + // match: /(=null!=\i&&)\(\i\|\|\i\|\|\i\)(?=&&\(!\i\|\|\i\?\.pid!=null\))/, + // replace: "$1true" + // } + // }, + + // Registered Games settings page + { + find: ".REGISTERED_GAMES_SIDEBAR_ITEM,{", + replacement: [ + { + match: /(\.REGISTERED_GAMES_SIDEBAR_ITEM,\{.{0,100}?usePredicate:)\i\.\i/, + replace: "$1()=>true" + }, + { + match: /(\.getGamesSeen\(!1\)\.some\(.{0,30}?\)\)&&)\(0,\i\.\i\)\(\)/g, + replace: "$1true" + } + ] + } + ], + + setObservedGamesCallback +}); diff --git a/src/renderer/rpc.ts b/src/renderer/rpc.ts new file mode 100644 index 00000000..d875e0b7 --- /dev/null +++ b/src/renderer/rpc.ts @@ -0,0 +1,188 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { findByCodeLazy, findByPropsLazy, onceReady } from "@vencord/types/webpack"; +import { FluxDispatcher, StreamerModeStore } from "@vencord/types/webpack/common"; +import type { DetectedGame, RpcClient } from "discord-rpc"; +import { IpcCommands } from "shared/IpcEvents"; + +import { onIpcCommand } from "./ipcCommands"; + +type TransportEvent = "connect" | "request" | "disconnect"; + +interface Connection { + socket: ReturnType; + // Resolves to whether Discord accepted the client. Requests have to wait for this + ready: Promise; +} + +// Discord's own RPC server. All commands and events are registered on it even on web, +// it just doesn't have any transport for desktop clients +const RPCServer = findByPropsLazy("registerTransport", "dispatchToSubscriptions"); +// Validates origin & client ID +const validateClient: (socket: unknown, origin: string | null, clientId: string | null) => Promise = + findByCodeLazy('"No Client ID Specified"'); + +const STREAMER_MODE_ID = "STREAMERMODE"; + +const listeners = {} as Record void>; +const connections = new Map(); +const games = new Map(); + +let userDisabledStreamerMode = false; +let observedGamesCallback: ((games: unknown[]) => void) | undefined; + +// Replaces the native process observer that feeds RunningGameStore, see patches/gameDetection.ts +export function setObservedGamesCallback(callback: typeof observedGamesCallback) { + observedGamesCallback = callback; + reportGames(); +} + +function createSocket({ id, transport, version }: RpcClient) { + // Empty values are filled in by Discord's validateClient. Discord uses their own class with defaults for this, + // mimic same defaults here + return { + id, + version, + encoding: "json", + transport, + source: { type: transport }, + application: { id: null, name: null, icon: null }, + authorization: { authing: false, scopes: new Set(), accessToken: null, expires: new Date(0) }, + abortController: new AbortController(), + send: (payload: unknown) => VesktopNative.rpc.send(id, JSON.stringify(payload)), + close: (code: number, message?: string) => VesktopNative.rpc.close(id, code, message) + }; +} + +// Discord only focuses the window for these on the desktop app +function opensUi({ cmd, args }: { cmd?: string; args?: Record }) { + switch (cmd) { + case "AUTHORIZE": + case "INVITE_BROWSER": + case "GUILD_TEMPLATE_BROWSER": + case "GIFT_CODE_BROWSER": + case "DEEP_LINK": + return true; + case "AUTHENTICATE": + return args?.access_token == null; + default: + return false; + } +} + +function disconnect(id: string) { + const connection = connections.get(id); + if (!connection) return; + + const { socket, ready } = connection; + connections.delete(id); + + socket.abortController.abort("DISCONNECTED"); + ready.then(accepted => accepted && listeners.disconnect(socket)); +} + +function reportGames() { + observedGamesCallback?.( + Array.from(games.values(), ({ id, name, pid, path }) => { + const exeName = path.split("/").pop(); + + return { + id, + name, + pid, + exeName, + exePath: path, + processName: exeName, + cmdLine: "", + pidPath: [pid], + isLauncher: false, + lastFocused: Math.floor(Date.now() / 1000), + // Otherwise Discord asks its native module for it + windowHandle: "0" + }; + }) + ); +} + +function updateStreamerMode(running: boolean) { + if (!StreamerModeStore.autoToggle) return; + + if (!running) { + userDisabledStreamerMode = false; + } else if (userDisabledStreamerMode) { + return; + } + + FluxDispatcher.dispatch({ + type: "STREAMER_MODE_UPDATE", + key: "enabled", + value: running, + isAuto: true + }); +} + +onIpcCommand(IpcCommands.RPC_CONNECT, (client: RpcClient) => { + const socket = createSocket(client); + + const ready = validateClient(socket, client.origin, client.clientId).then( + () => { + if (socket.abortController.signal.aborted) return false; + + listeners.connect(socket); + return true; + }, + ({ code, message }) => { + if (!socket.abortController.signal.aborted) socket.close(code, message); + return false; + } + ); + + connections.set(client.id, { socket, ready }); +}); + +onIpcCommand(IpcCommands.RPC_REQUEST, async ({ id, payload }: { id: string; payload: string }) => { + const connection = connections.get(id); + if (!connection || !(await connection.ready)) return; + + const request = JSON.parse(payload); + if (opensUi(request)) VesktopNative.win.focus(); + + listeners.request(connection.socket, request); +}); + +onIpcCommand(IpcCommands.RPC_DISCONNECT, disconnect); + +onIpcCommand(IpcCommands.RPC_GAME, ({ game, running }: { game: DetectedGame; running: boolean }) => { + if (game.id === STREAMER_MODE_ID) return updateStreamerMode(running); + + if (running) games.set(game.id, game); + else games.delete(game.id); + + reportGames(); +}); + +onIpcCommand(IpcCommands.RPC_RESET, () => { + for (const id of connections.keys()) disconnect(id); + games.clear(); + reportGames(); +}); + +onceReady.then(() => { + FluxDispatcher.subscribe("STREAMER_MODE_UPDATE", e => { + if (!e.isAuto && !e.value) { + userDisabledStreamerMode = true; + } + }); + + RPCServer.registerTransport({ + on(event: TransportEvent, listener: (...args: any[]) => void) { + listeners[event] = listener; + } + }); + + VesktopNative.rpc.ready(); +}); diff --git a/src/shared/IpcEvents.ts b/src/shared/IpcEvents.ts index 55efe80f..03c9c345 100644 --- a/src/shared/IpcEvents.ts +++ b/src/shared/IpcEvents.ts @@ -52,6 +52,10 @@ export const enum IpcEvents { VIRT_MIC_UNMUTE = "VCD_VIRT_MIC_UNMUTE", VIRT_MIC_STOP = "VCD_VIRT_MIC_STOP", + RPC_READY = "VCD_RPC_READY", + RPC_SEND = "VCD_RPC_SEND", + RPC_CLOSE = "VCD_RPC_CLOSE", + CLIPBOARD_COPY_IMAGE = "VCD_CLIPBOARD_COPY_IMAGE", DEBUG_LAUNCH_GPU = "VCD_DEBUG_LAUNCH_GPU", @@ -75,9 +79,11 @@ export const enum UpdaterIpcEvents { } export const enum IpcCommands { - RPC_ACTIVITY = "rpc:activity", - RPC_INVITE = "rpc:invite", - RPC_DEEP_LINK = "rpc:link", + RPC_CONNECT = "rpc:connect", + RPC_REQUEST = "rpc:request", + RPC_DISCONNECT = "rpc:disconnect", + RPC_GAME = "rpc:game", + RPC_RESET = "rpc:reset", NAVIGATE_SETTINGS = "navigate:settings", diff --git a/static/views/about.html b/static/views/about.html index 8cfa9ccf..561067ea 100644 --- a/static/views/about.html +++ b/static/views/about.html @@ -70,8 +70,8 @@ support out of the box
  • - arrpc - - An open implementation of Discord's Rich Presence server + GameDetection + - Native game detection for Discord Rich Presence
  • rohrkabel diff --git a/static/views/first-launch.html b/static/views/first-launch.html index 7c3dfaee..3fc035f3 100644 --- a/static/views/first-launch.html +++ b/static/views/first-launch.html @@ -133,10 +133,7 @@ diff --git a/tsconfig.json b/tsconfig.json index 463c93f2..6a0e2019 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -19,5 +19,5 @@ "types": ["node", "@vencord/types"] }, - "include": ["src/**/*"] + "include": ["src/**/*", "packages/discord-rpc/src/**/*"] }