add bitrix support

This commit is contained in:
kulikov0 committed 2026-09-07 21:14:11 +02:00
1 parent 747f8f2312
commit 5690cf58a9
62 files changed
+4098 -1053

No files matched your search

@@ -721,7 +721,7 @@ class MainActivity :
mainFragment()?.onConnectedChanged(false)
val headlessMode =
Prefs.headless || platform == CallPlatform.WBSTREAM || platform == CallPlatform.DION
Prefs.headless || platform == CallPlatform.WBSTREAM || platform == CallPlatform.DION || platform == CallPlatform.BITRIX
if (headlessMode && platform != CallPlatform.VK) {
setJoinOverlayVisible(false)
@@ -21,13 +21,7 @@ data class CallConfig(
CallPlatform.TELEMOST -> "TM"
CallPlatform.WBSTREAM -> "WB"
CallPlatform.DION -> "DN"
}
val platformLabel: String get() = when (platform) {
CallPlatform.VK -> "VK"
CallPlatform.TELEMOST -> "Telemost"
CallPlatform.WBSTREAM -> "WB Stream"
CallPlatform.DION -> "DION"
CallPlatform.BITRIX -> "BX"
}
fun toJson(): JSONObject = JSONObject().apply {
@@ -81,6 +75,7 @@ data class CallConfig(
CallPlatform.TELEMOST -> "Telemost"
CallPlatform.WBSTREAM -> "WB Stream"
CallPlatform.DION -> "DION"
CallPlatform.BITRIX -> "Bitrix"
}
return label
}
@@ -4,12 +4,14 @@ enum class CallPlatform(val id: String, val urlMarker: String) {
VK("vk", ""),
TELEMOST("telemost", "telemost"),
WBSTREAM("wbstream", "wbstream://"),
DION("dion", "dion://");
DION("dion", "dion://"),
BITRIX("bitrix", "/video/");
companion object {
fun fromUrl(url: String): CallPlatform = when {
url.contains(DION.urlMarker) || url.contains("dion.vc/event/") -> DION
url.contains(WBSTREAM.urlMarker) -> WBSTREAM
url.contains("bitrix24") && url.contains(BITRIX.urlMarker) -> BITRIX
url.contains(TELEMOST.urlMarker) -> TELEMOST
else -> VK
}
@@ -18,6 +20,17 @@ enum class CallPlatform(val id: String, val urlMarker: String) {
val trimmed = url.trim()
if (trimmed.startsWith(WBSTREAM.urlMarker)) return trimmed.removePrefix(WBSTREAM.urlMarker).trim()
if (trimmed.startsWith(DION.urlMarker)) return trimmed.removePrefix(DION.urlMarker).trim()
if (trimmed.contains("bitrix24")) {
val vidx = trimmed.indexOf(BITRIX.urlMarker)
if (vidx >= 0) {
var code = trimmed.substring(vidx + BITRIX.urlMarker.length)
val q = code.indexOf('?')
if (q >= 0) code = code.substring(0, q)
val s = code.indexOf('/')
if (s >= 0) code = code.substring(0, s)
return code.trim()
}
}
val dionPrefix = "dion.vc/event/"
val idx = trimmed.indexOf(dionPrefix)
if (idx >= 0) {
@@ -56,6 +56,10 @@ class HeadlessJoinController(
put("reliable", Prefs.activeReliable)
when (platform) {
CallPlatform.TELEMOST -> put("joinLink", url)
CallPlatform.BITRIX -> {
put("joinLink", url)
put("tunnelMode", Prefs.activeTunnelMode.relayArg)
}
CallPlatform.WBSTREAM -> {
put("roomId", CallPlatform.extractRoomId(url))
put("tunnelMode", Prefs.activeTunnelMode.relayArg)
@@ -81,7 +81,8 @@ class HeadlessSessionService : Service() {
Prefs.headless ||
platform == CallPlatform.WBSTREAM ||
platform == CallPlatform.DION ||
platform == CallPlatform.TELEMOST
platform == CallPlatform.TELEMOST ||
platform == CallPlatform.BITRIX
if (!headlessMode) {
showToast(R.string.tile_requires_headless_destination)
safeStopSelf()
+27 -1
View File
@@ -9,6 +9,7 @@ HEADLESS_VK_DIR="$HEADLESS_DIR/vk"
HEADLESS_TM_DIR="$HEADLESS_DIR/telemost"
HEADLESS_WB_DIR="$HEADLESS_DIR/wbstream"
HEADLESS_DION_DIR="$HEADLESS_DIR/dion"
HEADLESS_BITRIX_DIR="$HEADLESS_DIR/bitrix"
echo "=== Building relay binaries ==="
cd "$RELAY_DIR"
@@ -111,7 +112,27 @@ GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/he
echo "Linux x86..."
GOOS=linux GOARCH=386 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/headless-dion-linux-ia32" .
ls -lh "$HEADLESS_DIR"/headless-vk-darwin "$HEADLESS_DIR"/headless-telemost-darwin "$HEADLESS_DIR"/headless-wbstream-darwin "$HEADLESS_DIR"/headless-dion-darwin
echo ""
echo "=== Building headless-bitrix-creator ==="
cd "$HEADLESS_BITRIX_DIR"
echo "macOS (universal)..."
GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/headless-bitrix-darwin-amd64" .
GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/headless-bitrix-darwin-arm64" .
lipo -create -output "$HEADLESS_DIR/headless-bitrix-darwin" "$HEADLESS_DIR/headless-bitrix-darwin-amd64" "$HEADLESS_DIR/headless-bitrix-darwin-arm64"
rm "$HEADLESS_DIR/headless-bitrix-darwin-amd64" "$HEADLESS_DIR/headless-bitrix-darwin-arm64"
echo "Windows x64..."
GOOS=windows GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/headless-bitrix-windows-x64.exe" .
echo "Windows x86..."
GOOS=windows GOARCH=386 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/headless-bitrix-windows-ia32.exe" .
echo "Linux x64..."
GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/headless-bitrix-linux-x64" .
echo "Linux x86..."
GOOS=linux GOARCH=386 go build -trimpath -ldflags="-s -w" -o "$HEADLESS_DIR/headless-bitrix-linux-ia32" .
ls -lh "$HEADLESS_DIR"/headless-vk-darwin "$HEADLESS_DIR"/headless-telemost-darwin "$HEADLESS_DIR"/headless-wbstream-darwin "$HEADLESS_DIR"/headless-dion-darwin "$HEADLESS_DIR"/headless-bitrix-darwin
echo ""
echo "=== Building Electron apps ==="
@@ -132,6 +153,7 @@ cp "$HEADLESS_DIR/headless-vk-windows-x64.exe" "$HEADLESS_DIR/headless-vk-bundle
cp "$HEADLESS_DIR/headless-telemost-windows-x64.exe" "$HEADLESS_DIR/headless-telemost-bundle.exe"
cp "$HEADLESS_DIR/headless-wbstream-windows-x64.exe" "$HEADLESS_DIR/headless-wbstream-bundle.exe"
cp "$HEADLESS_DIR/headless-dion-windows-x64.exe" "$HEADLESS_DIR/headless-dion-bundle.exe"
cp "$HEADLESS_DIR/headless-bitrix-windows-x64.exe" "$HEADLESS_DIR/headless-bitrix-bundle.exe"
npx electron-builder --win --x64
# Windows x86
@@ -142,6 +164,7 @@ cp "$HEADLESS_DIR/headless-vk-windows-ia32.exe" "$HEADLESS_DIR/headless-vk-bundl
cp "$HEADLESS_DIR/headless-telemost-windows-ia32.exe" "$HEADLESS_DIR/headless-telemost-bundle.exe"
cp "$HEADLESS_DIR/headless-wbstream-windows-ia32.exe" "$HEADLESS_DIR/headless-wbstream-bundle.exe"
cp "$HEADLESS_DIR/headless-dion-windows-ia32.exe" "$HEADLESS_DIR/headless-dion-bundle.exe"
cp "$HEADLESS_DIR/headless-bitrix-windows-ia32.exe" "$HEADLESS_DIR/headless-bitrix-bundle.exe"
npx electron-builder --win --ia32
# Linux x64
@@ -152,6 +175,7 @@ cp "$HEADLESS_DIR/headless-vk-linux-x64" "$HEADLESS_DIR/headless-vk-bundle"
cp "$HEADLESS_DIR/headless-telemost-linux-x64" "$HEADLESS_DIR/headless-telemost-bundle"
cp "$HEADLESS_DIR/headless-wbstream-linux-x64" "$HEADLESS_DIR/headless-wbstream-bundle"
cp "$HEADLESS_DIR/headless-dion-linux-x64" "$HEADLESS_DIR/headless-dion-bundle"
cp "$HEADLESS_DIR/headless-bitrix-linux-x64" "$HEADLESS_DIR/headless-bitrix-bundle"
npx electron-builder --linux --x64
# Cleanup build artifacts
@@ -165,6 +189,8 @@ rm -f "$HEADLESS_DIR"/headless-wbstream-darwin "$HEADLESS_DIR"/headless-wbstream
rm -f "$HEADLESS_DIR"/headless-wbstream-bundle "$HEADLESS_DIR"/headless-wbstream-bundle.exe
rm -f "$HEADLESS_DIR"/headless-dion-darwin "$HEADLESS_DIR"/headless-dion-windows-*.exe "$HEADLESS_DIR"/headless-dion-linux-*
rm -f "$HEADLESS_DIR"/headless-dion-bundle "$HEADLESS_DIR"/headless-dion-bundle.exe
rm -f "$HEADLESS_DIR"/headless-bitrix-darwin "$HEADLESS_DIR"/headless-bitrix-windows-*.exe "$HEADLESS_DIR"/headless-bitrix-linux-*
rm -f "$HEADLESS_DIR"/headless-bitrix-bundle "$HEADLESS_DIR"/headless-bitrix-bundle.exe
"$ROOT/clean-prebuilts.sh"
+4 -1
View File
@@ -14,6 +14,9 @@ go -C "$ROOT/headless/wbstream" build -trimpath -ldflags="-s -w" -o headless-wbs
echo "Building headless-dion-creator..."
go -C "$ROOT/headless/dion" build -trimpath -ldflags="-s -w" -o headless-dion-creator .
echo "Building headless-bitrix-creator..."
go -C "$ROOT/headless/bitrix" build -trimpath -ldflags="-s -w" -o headless-bitrix-creator .
echo "Building headless-dion-joiner..."
go -C "$ROOT/headless/dion-joiner" build -trimpath -ldflags="-s -w" -o headless-dion-joiner .
@@ -27,4 +30,4 @@ echo "Building headless-vk-bot..."
go -C "$ROOT/headless/vk-bot" build -trimpath -ldflags="-s -w" -o headless-vk-bot .
echo "Done."
ls -lh "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator" "$ROOT/headless/wbstream/headless-wbstream-creator" "$ROOT/headless/dion/headless-dion-creator" "$ROOT/headless/dion-joiner/headless-dion-joiner" "$ROOT/headless/wbstream-joiner/headless-wbstream-joiner" "$ROOT/headless/telemost-joiner/headless-telemost-joiner" "$ROOT/headless/vk-bot/headless-vk-bot"
ls -lh "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator" "$ROOT/headless/wbstream/headless-wbstream-creator" "$ROOT/headless/dion/headless-dion-creator" "$ROOT/headless/bitrix/headless-bitrix-creator" "$ROOT/headless/dion-joiner/headless-dion-joiner" "$ROOT/headless/wbstream-joiner/headless-wbstream-joiner" "$ROOT/headless/telemost-joiner/headless-telemost-joiner" "$ROOT/headless/vk-bot/headless-vk-bot"
+26
View File
@@ -19,6 +19,7 @@
<button class="btn-headless-tm" id="btnHeadlessTM">Telemost</button>
<button class="btn-headless-wb" id="btnHeadlessWB">WBStream</button>
<button class="btn-headless-dion" id="btnHeadlessDion">DION</button>
<button class="btn-headless-bitrix" id="btnHeadlessBitrix">Bitrix</button>
<button class="btn-vk" id="btnVk">VK (legacy)</button>
<button class="btn-telemost" id="btnTelemost">Telemost (legacy)</button>
<span class="toolbar-spacer"></span>
@@ -54,6 +55,11 @@
<div class="headless-start-card-desc">Store an email and password so the session renews itself and never asks for a browser login.</div>
<button class="headless-start-btn" id="btnDionAccount">Edit credentials</button>
</div>
<div class="headless-start-card" id="headlessBitrixAccountCard" style="display:none">
<div class="headless-start-card-title">Bitrix account (optional)</div>
<div class="headless-start-card-desc">Create or Join opens the Bitrix login, you pick your portal there and the app captures the cookies. Optionally store portal, email and password here so the session renews itself without a browser login.</div>
<button class="headless-start-btn" id="btnBitrixAccount">Edit credentials</button>
</div>
</div>
<div class="headless-status" id="headlessStatus">Starting...</div>
<div class="headless-call-info" id="headlessCallInfo">
@@ -71,6 +77,9 @@
<div class="headless-call-info" id="headlessCallInfoDion">
<div class="headless-row"><span class="headless-label">Join link:</span> <a id="headlessDionJoinLink" href="#" class="headless-link"></a><img class="headless-copy" src="resources/icons8-copy-50.png" data-copy="headlessDionJoinLink" title="Copy"></div>
</div>
<div class="headless-call-info" id="headlessCallInfoBitrix">
<div class="headless-row"><span class="headless-label">Join link:</span> <a id="headlessBitrixJoinLink" href="#" class="headless-link"></a><img class="headless-copy" src="resources/icons8-copy-50.png" data-copy="headlessBitrixJoinLink" title="Copy"></div>
</div>
<div class="headless-qr" id="headlessQrWrap" style="display:none">
<img id="headlessQr" alt="Join link QR code">
<div class="headless-qr-hint">Scan in the Android app</div>
@@ -111,6 +120,7 @@
<button type="button" class="btn-clear-cookies" data-platform="telemost">Telemost</button>
<button type="button" class="btn-clear-cookies" data-platform="wbstream">WBStream</button>
<button type="button" class="btn-clear-cookies" data-platform="dion">DION</button>
<button type="button" class="btn-clear-cookies" data-platform="bitrix">Bitrix</button>
</div>
<div class="clear-cookies-status" id="clearCookiesStatus"></div>
<div class="popup-buttons">
@@ -133,6 +143,22 @@
</div>
</div>
</div>
<div class="popup-overlay" id="bitrixAccountPopup">
<div class="popup">
<h2>Bitrix account</h2>
<label for="bitrixPortal">Portal</label>
<input type="text" id="bitrixPortal" placeholder="https://your-portal.bitrix24.ru">
<label for="bitrixEmail">Email</label>
<input type="text" id="bitrixEmail" placeholder="you@example.com">
<label for="bitrixPassword">Password</label>
<input type="text" id="bitrixPassword" placeholder="">
<div class="clear-cookies-status" id="bitrixAccountStatus"></div>
<div class="popup-buttons">
<button class="btn-cancel" id="btnBitrixAccountCancel">Cancel</button>
<button class="btn-save" id="btnBitrixAccountSave">Save</button>
</div>
</div>
</div>
<div class="popup-overlay" id="errorPopup">
<div class="popup" style="padding:16px">
<h2 class="error-title">Bot error</h2>
+12
View File
@@ -70,6 +70,10 @@
{
"from": "../headless/headless-dion-darwin",
"to": "headless-dion-creator"
},
{
"from": "../headless/headless-bitrix-darwin",
"to": "headless-bitrix-creator"
}
]
},
@@ -97,6 +101,10 @@
{
"from": "../headless/headless-dion-bundle.exe",
"to": "headless-dion-creator.exe"
},
{
"from": "../headless/headless-bitrix-bundle.exe",
"to": "headless-bitrix-creator.exe"
}
]
},
@@ -124,6 +132,10 @@
{
"from": "../headless/headless-dion-bundle",
"to": "headless-dion-creator"
},
{
"from": "../headless/headless-bitrix-bundle",
"to": "headless-bitrix-creator"
}
]
}
+6
View File
@@ -18,10 +18,13 @@ export const VK_LOGIN_URL = 'https://vk.ru/';
export const YANDEX_LOGIN_URL = 'https://passport.yandex.ru/auth?retpath=https%3A%2F%2Ftelemost.yandex.ru%2F';
export const DION_LOGIN_URL = 'https://dion.vc/login';
export const WBSTREAM_LOGIN_URL = 'https://stream.wb.ru/login';
export const BITRIX_LOGIN_URL = 'https://www.bitrix24.ru/';
export const VK_AUTH_COOKIE = 'remixsid';
export const YANDEX_AUTH_COOKIE = 'Session_id';
export const DION_AUTH_COOKIE = 'vc-refresh-token';
export const WBSTREAM_AUTH_COOKIE = 'x_wbaas_token';
export const BITRIX_SESSION_COOKIE = 'BITRIX_SM_UIDH';
export const BITRIX_AUTH_NET_HOST = 'https://auth2.bitrix24.net';
export const SESSION_PARTITION = 'persist:creator';
export const WINDOW_WIDTH = 1200;
@@ -35,6 +38,7 @@ export const VK_COOKIE_DOMAINS = ['vk.ru'];
export const YANDEX_COOKIE_DOMAINS = ['yandex.ru', 'yandex.net', 'ya.ru'];
export const DION_COOKIE_DOMAINS = ['dion.vc'];
export const WBSTREAM_COOKIE_DOMAINS = ['stream.wb.ru', 'wb.ru', 'wildberries.ru'];
export const BITRIX_COOKIE_DOMAINS = ['bitrix24.ru', 'bitrix24.net', 'bitrix24.com'];
export enum Selector {
VK_ADMIT = '[data-testid="calls_waiting_hall_promote"]',
@@ -63,6 +67,8 @@ export enum IPC {
CLEAR_COOKIES = 'clear-cookies',
GET_DION_CREDENTIALS = 'get-dion-credentials',
SET_DION_CREDENTIALS = 'set-dion-credentials',
GET_BITRIX_CREDENTIALS = 'get-bitrix-credentials',
SET_BITRIX_CREDENTIALS = 'set-bitrix-credentials',
EXPORT_COOKIES_ZIP = 'export-cookies-zip',
RENDER_QR = 'render-qr',
RELAY_LOG = 'relay-log',
@@ -0,0 +1,60 @@
import * as fs from 'fs/promises';
import { BitrixCredentials } from '../types';
export interface BitrixCookie {
name: string;
value: string;
host: string;
}
export class BitrixCookieFile {
private filePath: string;
constructor(filePath: string) {
this.filePath = filePath;
}
async readCredentials(): Promise<BitrixCredentials> {
const content = await this.read();
return {
portal: content?.portal || '',
email: content?.email || '',
password: content?.password || '',
};
}
async writeCredentials(portal: string, email: string, password: string): Promise<void> {
const content = {
portal: portal || undefined,
email: email || undefined,
password: password || undefined,
cookies: [] as unknown[],
};
await fs.writeFile(this.filePath, JSON.stringify(content));
}
async writeSession(portal: string, cookies: BitrixCookie[]): Promise<void> {
const existing = await this.read();
const content = {
portal: portal || existing?.portal || undefined,
email: existing?.email || undefined,
password: existing?.password || undefined,
cookies,
};
await fs.writeFile(this.filePath, JSON.stringify(content));
}
private async read(): Promise<BitrixCredentials | null> {
try {
const raw = await fs.readFile(this.filePath, 'utf8');
const parsed = JSON.parse(raw);
return {
portal: typeof parsed.portal === 'string' ? parsed.portal : '',
email: typeof parsed.email === 'string' ? parsed.email : '',
password: typeof parsed.password === 'string' ? parsed.password : '',
};
} catch {
return null;
}
}
}
+264
View File
@@ -0,0 +1,264 @@
import { app, session } from 'electron';
import * as path from 'path';
import * as fs from 'fs/promises';
import { Platform, DionCredentials, BitrixCredentials } from '../types';
import {
SESSION_PARTITION,
VK_COOKIE_DOMAINS,
YANDEX_COOKIE_DOMAINS,
DION_COOKIE_DOMAINS,
WBSTREAM_COOKIE_DOMAINS,
BITRIX_COOKIE_DOMAINS,
BITRIX_SESSION_COOKIE,
BITRIX_AUTH_NET_HOST,
} from '../constants';
import { PLATFORM_CONFIG } from './platform-config';
import { DionCookieFile } from './dion-cookie-file';
import { BitrixCookieFile, BitrixCookie } from './bitrix-cookie-file';
import { buildStoredZip } from './util/zip';
export interface BitrixSession {
portal: string;
cookies: BitrixCookie[];
}
export class CookieStore {
cookieFilePath(platform: Platform): string {
return path.join(app.getPath('userData'), `cookies-${platform}.json`);
}
async getCookiesForDomains(domains: string[]): Promise<{ name: string; value: string }[]> {
const ses = session.fromPartition(SESSION_PARTITION);
const all = await ses.cookies.get({});
return all
.filter((c) => c.domain != null && domains.some((d) => c.domain!.includes(d)))
.map((c) => ({ name: c.name, value: c.value }));
}
waitForLogin(cookieDomains: string[], authCookieName: string): Promise<void> {
return new Promise((resolve) => {
const ses = session.fromPartition(SESSION_PARTITION);
const finish = () => {
ses.cookies.removeListener('changed', onChanged);
resolve();
};
const onChanged = (
_e: Electron.Event,
cookie: Electron.Cookie,
_cause: string,
removed: boolean,
) => {
if (removed) return;
if (cookie.name !== authCookieName) return;
if (!cookie.domain || !cookieDomains.some((d) => cookie.domain!.includes(d))) return;
finish();
};
ses.cookies.on('changed', onChanged);
ses.cookies.get({ name: authCookieName }).then((found) => {
if (found.some((c) => c.domain && cookieDomains.some((d) => c.domain!.includes(d)))) {
finish();
}
});
});
}
waitForCookies(names: string[]): Promise<void> {
return new Promise((resolve) => {
const ses = session.fromPartition(SESSION_PARTITION);
const remaining = new Set(names);
const finish = () => {
ses.cookies.removeListener('changed', onChanged);
resolve();
};
const onChanged = (
_e: Electron.Event,
cookie: Electron.Cookie,
_cause: string,
removed: boolean,
) => {
if (removed) return;
if (!remaining.has(cookie.name)) return;
remaining.delete(cookie.name);
if (remaining.size === 0) finish();
};
ses.cookies.on('changed', onChanged);
Promise.all(names.map((name) => ses.cookies.get({ name }))).then((results) => {
results.forEach((found, i) => {
if (found.length > 0) remaining.delete(names[i]);
});
if (remaining.size === 0) finish();
});
});
}
waitForBitrixSession(): Promise<BitrixSession | null> {
return new Promise((resolve) => {
const ses = session.fromPartition(SESSION_PARTITION);
let settled = false;
const finish = (value: BitrixSession | null): void => {
if (settled) return;
settled = true;
ses.cookies.removeListener('changed', onChanged);
resolve(value);
};
const check = (): void => {
this.captureBitrixSession().then((data) => {
if (data) finish(data);
});
};
const onChanged = (
_e: Electron.Event,
cookie: Electron.Cookie,
_cause: string,
removed: boolean,
): void => {
if (removed) return;
if (cookie.name !== BITRIX_SESSION_COOKIE) return;
check();
};
ses.cookies.on('changed', onChanged);
check();
});
}
async captureBitrixSession(preferredPortal?: string): Promise<BitrixSession | null> {
const ses = session.fromPartition(SESSION_PARTITION);
const all = await ses.cookies.get({});
const relevant = all.filter((c) => c.domain != null && BITRIX_COOKIE_DOMAINS.some((d) => c.domain!.includes(d)));
if (relevant.length === 0) return null;
const bareHost = (domain: string): string => (domain.startsWith('.') ? domain.slice(1) : domain);
const isPortalHost = (host: string): boolean =>
/\.bitrix24\.(ru|com)$/.test(host) && host !== 'www.bitrix24.ru' && host !== 'www.bitrix24.com';
let preferredHost = '';
if (preferredPortal) {
try {
preferredHost = new URL(preferredPortal).hostname;
} catch {
preferredHost = '';
}
}
const sessionHosts = relevant
.filter((c) => c.name === BITRIX_SESSION_COOKIE)
.map((c) => bareHost(c.domain!))
.filter(isPortalHost);
let portalHost = '';
if (preferredHost && sessionHosts.includes(preferredHost)) portalHost = preferredHost;
else if (sessionHosts.length > 0) portalHost = sessionHosts[0];
if (!portalHost) return null;
const portal = 'https://' + portalHost;
const cookies: BitrixCookie[] = relevant.map((c) => {
const host = bareHost(c.domain!);
const hostUrl = host.includes('bitrix24.net') ? BITRIX_AUTH_NET_HOST : portal;
return { name: c.name, value: c.value, host: hostUrl };
});
return { portal, cookies };
}
async clearAuthCookies(cookieDomains: string[], authCookieName: string): Promise<void> {
const ses = session.fromPartition(SESSION_PARTITION);
const matches = await ses.cookies.get({ name: authCookieName });
for (const cookie of matches) {
if (!cookie.domain || !cookieDomains.some((d) => cookie.domain!.includes(d))) continue;
const host = cookie.domain.startsWith('.') ? cookie.domain.slice(1) : cookie.domain;
const url = `https://${host}${cookie.path || '/'}`;
try {
await ses.cookies.remove(url, cookie.name);
} catch (err) {
console.log(`[COOKIES] failed to remove ${cookie.name} on ${url}:`, err);
}
}
}
async clearPlatformCookies(platform: Platform): Promise<number> {
if (platform === Platform.Bitrix) {
const removed = await this.removeCookiesForDomains(BITRIX_COOKIE_DOMAINS);
const account = new BitrixCookieFile(this.cookieFilePath(Platform.Bitrix));
const creds = await account.readCredentials();
if (creds.email && creds.password) {
await account.writeCredentials(creds.portal, creds.email, creds.password);
} else {
await fs.unlink(this.cookieFilePath(Platform.Bitrix)).catch(() => {});
}
console.log(`[COOKIES] cleared ${removed} bitrix cookies`);
return removed;
}
const config = PLATFORM_CONFIG[platform];
if (!config) return 0;
const removed = await this.removeCookiesForDomains(config.cookieDomains);
await fs.unlink(this.cookieFilePath(platform)).catch(() => {});
console.log(`[COOKIES] cleared ${removed} cookies for ${platform}`);
return removed;
}
private async removeCookiesForDomains(domains: string[]): Promise<number> {
const ses = session.fromPartition(SESSION_PARTITION);
const all = await ses.cookies.get({});
let removed = 0;
for (const cookie of all) {
if (!cookie.domain || !domains.some((d) => cookie.domain!.includes(d))) continue;
const host = cookie.domain.startsWith('.') ? cookie.domain.slice(1) : cookie.domain;
const url = `https://${host}${cookie.path || '/'}`;
try {
await ses.cookies.remove(url, cookie.name);
removed++;
} catch (err) {
console.log(`[COOKIES] failed to remove ${cookie.name} on ${url}:`, err);
}
}
return removed;
}
async getDionCredentials(): Promise<DionCredentials> {
return new DionCookieFile(this.cookieFilePath(Platform.Dion)).readCredentials();
}
async setDionCredentials(email: string, password: string): Promise<void> {
await new DionCookieFile(this.cookieFilePath(Platform.Dion)).writeCredentials(email, password);
}
async getBitrixCredentials(): Promise<BitrixCredentials> {
return new BitrixCookieFile(this.cookieFilePath(Platform.Bitrix)).readCredentials();
}
async setBitrixCredentials(portal: string, email: string, password: string): Promise<void> {
await new BitrixCookieFile(this.cookieFilePath(Platform.Bitrix)).writeCredentials(portal, email, password);
}
async buildCookiesZip(): Promise<Buffer> {
const platforms: { filename: string; domains: string[]; platform: Platform }[] = [
{ filename: 'cookies-vk.json', domains: VK_COOKIE_DOMAINS, platform: Platform.VK },
{ filename: 'cookies-yandex.json', domains: YANDEX_COOKIE_DOMAINS, platform: Platform.Telemost },
{ filename: 'cookies-dion.json', domains: DION_COOKIE_DOMAINS, platform: Platform.Dion },
{ filename: 'cookies-wbstream.json', domains: WBSTREAM_COOKIE_DOMAINS, platform: Platform.WBStream },
];
const cookies = await Promise.all(platforms.map((p) => this.getCookiesForDomains(p.domains)));
const dionContent = await new DionCookieFile(this.cookieFilePath(Platform.Dion)).readContent();
const entries = platforms.map((p, i) => {
const content = p.platform === Platform.Dion && dionContent ? dionContent : cookies[i];
return { name: p.filename, data: Buffer.from(JSON.stringify(content, null, 2), 'utf8') };
});
return buildStoredZip(entries);
}
async setWBStreamDeviceId(id: string): Promise<void> {
if (!id) return;
const ses = session.fromPartition(SESSION_PARTITION);
const existing = await ses.cookies.get({ url: 'https://stream.wb.ru/', name: '__wb_device_id' });
if (existing.length > 0 && existing[0].value === id) return;
try {
await ses.cookies.set({
url: 'https://stream.wb.ru/',
name: '__wb_device_id',
value: id,
domain: 'stream.wb.ru',
path: '/',
secure: true,
httpOnly: false,
expirationDate: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 365 * 5,
});
console.log(`[wb-device-id] persisted ${id}`);
} catch (err) {
console.log(`[wb-device-id] failed to persist:`, err);
}
}
}
+306
View File
@@ -0,0 +1,306 @@
import { BrowserWindow } from 'electron';
import { spawn, ChildProcess } from 'child_process';
import * as path from 'path';
import * as fs from 'fs/promises';
import {
TabState,
Platform,
TunnelMode,
RelayMode,
HeadlessStartArgs,
HeadlessMode,
UpstreamProxy,
} from '../types';
import { IPC, BITRIX_LOGIN_URL } from '../constants';
import { BotManager } from '../bot/bot-manager';
import { DionCookieFile } from './dion-cookie-file';
import { BitrixCookieFile } from './bitrix-cookie-file';
import { resolveResourcePath, binaryName } from './util/paths';
import { PLATFORM_CONFIG } from './platform-config';
import { CookieStore } from './cookie-store';
export interface LauncherHost {
getOrCreateTab(tabId: string): Promise<TabState>;
getTab(tabId: string): TabState | undefined;
readonly mainWindow: BrowserWindow | null;
readonly botManager: BotManager | null;
}
type AuthErrorKind = 'invalid' | 'expired';
function parseAuthError(msg: string): AuthErrorKind | null {
if (msg.includes('STATUS:AUTH_ERROR:INVALID_CREDENTIALS')) return 'invalid';
if (msg.includes('STATUS:AUTH_ERROR:SESSION_EXPIRED')) return 'expired';
return null;
}
export class HeadlessLauncher {
private relayPath: string;
private bitrixPath: string;
private binaryPaths = new Map<Platform, string>();
private upstreamProxy: UpstreamProxy = { socks: '', user: '', pass: '' };
private debugLogging = false;
constructor(
private host: LauncherHost,
private cookies: CookieStore,
) {
this.relayPath = resolveResourcePath(
path.join('relay', binaryName('relay')),
binaryName('relay'),
);
this.bitrixPath = resolveResourcePath(
path.join('headless', 'bitrix', binaryName('headless-bitrix-creator')),
binaryName('headless-bitrix-creator'),
);
for (const [platform, config] of Object.entries(PLATFORM_CONFIG)) {
this.binaryPaths.set(
platform as Platform,
resolveResourcePath(
path.join('headless', config!.binarySubdir, binaryName(config!.binaryBase)),
binaryName(config!.binaryBase),
),
);
}
}
setUpstreamProxy(proxy: UpstreamProxy): void {
this.upstreamProxy = {
socks: (proxy?.socks || '').trim(),
user: (proxy?.user || '').trim(),
pass: (proxy?.pass || '').trim(),
};
}
setDebugLogging(enabled: boolean): void {
this.debugLogging = enabled;
}
sendLog(tabId: string, msg: string): void {
const win = this.host.mainWindow;
if (win && !win.isDestroyed()) {
win.webContents.send(IPC.RELAY_LOG, { tabId, msg });
}
}
killRelay(tabId: string, tab: TabState): void {
if (tab.relay) {
console.log(`[${tabId}] killing process pid=${tab.relay.pid}`);
tab.relay.kill();
tab.relay = null;
}
}
startRelay(tabId: string, tab: TabState): void {
this.killRelay(tabId, tab);
const port = tab.tunnelMode === TunnelMode.PionVideo ? tab.pionPort : tab.dcPort;
let relayMode: RelayMode = RelayMode.DCCreator;
if (tab.tunnelMode === TunnelMode.PionVideo) {
relayMode = tab.platform === Platform.Telemost
? RelayMode.TelemostVideoCreator
: RelayMode.VKVideoCreator;
}
const relayArgs = ['--mode', relayMode, '--ws-port', String(port)];
this.appendUpstreamArgs(relayArgs);
if (this.debugLogging) relayArgs.push('--debug');
const proc = spawn(this.relayPath, relayArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
});
tab.relay = proc;
this.attachProcessOutput(proc, tabId);
proc.on('close', (code) => {
this.sendLog(tabId, `Relay exited with code ${code}`);
});
}
async startHeadless(tabId: string, platform: Platform, args: HeadlessStartArgs): Promise<void> {
if (platform === Platform.Bitrix) {
await this.startBitrixHeadless(tabId, args);
return;
}
const tab = await this.host.getOrCreateTab(tabId);
tab.platform = platform;
const joinTarget = args.mode === HeadlessMode.Join ? (args.target || '').trim() : '';
if (args.mode === HeadlessMode.Join && !joinTarget) {
this.sendLog(tabId, 'Join requested but no target link/room provided.');
return;
}
const config = PLATFORM_CONFIG[platform];
if (!config) {
this.sendLog(tabId, `Unsupported headless platform: ${platform}`);
return;
}
tab.tunnelMode = config.tunnelMode;
const cookiesPath = this.cookies.cookieFilePath(platform);
const dionCookieFile = platform === Platform.Dion ? new DionCookieFile(cookiesPath) : null;
const fileHasSession = dionCookieFile != null && await dionCookieFile.hasSession();
let cookies = await this.cookies.getCookiesForDomains(config.cookieDomains);
const needsLogin = !fileHasSession && !cookies.some((c) => c.name === config.refreshCookie);
if (needsLogin) {
if (tab.isBot) {
const reply = `Please log into ${config.platformName} in the creator app first, then try again.`;
this.sendLog(tabId, reply);
if (this.host.botManager && tab.peerId != null) {
await this.host.botManager.sendMessage(tab.peerId, reply);
}
return;
}
this.sendLog(tabId, `No ${config.platformName} session found, opening login.`);
const win = this.host.mainWindow;
if (win && !win.isDestroyed()) {
win.webContents.send(IPC.LOGIN_REQUIRED, { tabId, url: config.loginUrl });
}
if (config.loginWaitCookies) {
this.sendLog(tabId, `Waiting for ${config.loginWaitCookies.join(', ')}...`);
await this.cookies.waitForCookies(config.loginWaitCookies);
} else {
await this.cookies.waitForLogin(config.cookieDomains, config.authCookie);
}
if (win && !win.isDestroyed()) {
win.webContents.send(IPC.LOGIN_DONE, { tabId });
}
this.sendLog(tabId, `${config.platformName} login captured.`);
cookies = await this.cookies.getCookiesForDomains(config.cookieDomains);
}
if (fileHasSession) {
this.sendLog(tabId, `${config.platformName} session file is still active, keeping it as is.`);
} else {
this.sendLog(tabId, `${config.platformName} cookies (${cookies.length}): ${cookies.map((c) => c.name).join(', ')}`);
await fs.writeFile(cookiesPath, JSON.stringify(cookies));
}
const spawnArgs = ['--resources', 'default', '--cookies', cookiesPath];
this.killRelay(tabId, tab);
if (joinTarget && config.joinFlag) {
spawnArgs.push(config.joinFlag, joinTarget);
}
this.appendUpstreamArgs(spawnArgs);
if (this.debugLogging) spawnArgs.push('--debug');
const proc = spawn(this.binaryPaths.get(platform)!, spawnArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
});
tab.relay = proc;
let authError: AuthErrorKind | null = null;
this.attachProcessOutput(proc, tabId, (msg) => {
const kind = parseAuthError(msg);
if (kind) authError = kind;
});
proc.on('close', async (code) => {
this.sendLog(tabId, `Headless exited with code ${code}`);
if (authError === 'invalid') {
this.sendLog(tabId, `${config.platformName} rejected the email and password stored in ${cookiesPath}, fix them or clear cookies to log in through the browser.`);
return;
}
if (authError === 'expired') {
if (dionCookieFile) await dionCookieFile.clearTokens();
await this.cookies.clearAuthCookies(config.cookieDomains, config.authCookie);
if (this.host.getTab(tabId) === tab) this.startHeadless(tabId, platform, args);
}
});
}
private async startBitrixHeadless(tabId: string, args: HeadlessStartArgs): Promise<void> {
const tab = await this.host.getOrCreateTab(tabId);
tab.platform = Platform.Bitrix;
tab.tunnelMode = TunnelMode.HeadlessBitrix;
const joinTarget = args.mode === HeadlessMode.Join ? (args.target || '').trim() : '';
if (args.mode === HeadlessMode.Join && !joinTarget) {
this.sendLog(tabId, 'Join requested but no target link/room provided.');
return;
}
const cookiesPath = this.cookies.cookieFilePath(Platform.Bitrix);
const account = new BitrixCookieFile(cookiesPath);
const creds = await account.readCredentials();
const hasPassword = !!(creds.portal && creds.email && creds.password);
let sessionData = await this.cookies.captureBitrixSession();
if (!hasPassword && !sessionData) {
if (tab.isBot) {
const reply = 'Please log into Bitrix in the creator app first, then try again.';
this.sendLog(tabId, reply);
if (this.host.botManager && tab.peerId != null) {
await this.host.botManager.sendMessage(tab.peerId, reply);
}
return;
}
this.sendLog(tabId, 'No Bitrix session found, opening login. Pick your portal in the Bitrix login screen.');
const win = this.host.mainWindow;
if (win && !win.isDestroyed()) {
win.webContents.send(IPC.LOGIN_REQUIRED, { tabId, url: BITRIX_LOGIN_URL });
}
this.sendLog(tabId, 'Waiting for the portal session...');
sessionData = await this.cookies.waitForBitrixSession();
if (win && !win.isDestroyed()) {
win.webContents.send(IPC.LOGIN_DONE, { tabId });
}
this.sendLog(tabId, `Bitrix login captured on ${sessionData?.portal}.`);
}
if (!hasPassword) {
if (!sessionData) {
this.sendLog(tabId, 'Could not capture Bitrix cookies, log in and try again.');
return;
}
await account.writeSession(sessionData.portal, sessionData.cookies);
this.sendLog(tabId, `Bitrix session captured, portal ${sessionData.portal}`);
} else {
this.sendLog(tabId, 'Bitrix account credentials present, logging in with portal and password.');
}
const spawnArgs = ['--resources', 'default', '--cookies', cookiesPath];
this.killRelay(tabId, tab);
if (joinTarget) {
spawnArgs.push('--room', joinTarget);
}
this.appendUpstreamArgs(spawnArgs);
if (this.debugLogging) spawnArgs.push('--debug');
const proc = spawn(this.bitrixPath, spawnArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
});
tab.relay = proc;
let authError: AuthErrorKind | null = null;
this.attachProcessOutput(proc, tabId, (msg) => {
const kind = parseAuthError(msg);
if (kind) authError = kind;
});
proc.on('close', async (code) => {
this.sendLog(tabId, `Headless exited with code ${code}`);
if (authError === 'invalid') {
this.sendLog(tabId, `Bitrix rejected the portal, email or password stored in ${cookiesPath}, fix them in the Bitrix account card or log in again.`);
return;
}
if (authError === 'expired' && !hasPassword) {
await this.cookies.clearPlatformCookies(Platform.Bitrix);
if (this.host.getTab(tabId) === tab) this.startBitrixHeadless(tabId, args);
}
});
}
private appendUpstreamArgs(args: string[]): void {
if (!this.upstreamProxy.socks) return;
args.push('--upstream-socks', this.upstreamProxy.socks);
if (this.upstreamProxy.user) args.push('--upstream-user', this.upstreamProxy.user);
if (this.upstreamProxy.pass) args.push('--upstream-pass', this.upstreamProxy.pass);
}
private attachProcessOutput(
proc: ChildProcess,
tabId: string,
inspect?: (msg: string) => void,
): void {
const onData = (data: Buffer) => {
data
.toString()
.trim()
.split('\n')
.forEach((msg) => {
if (!msg) return;
console.log(`[relay:${tabId}]`, msg);
this.sendLog(tabId, msg);
if (inspect) inspect(msg);
});
};
proc.stdout?.on('data', onData);
proc.stderr?.on('data', onData);
}
}
+8
View File
@@ -120,6 +120,14 @@ export function registerIpcHandlers(tabManager: TabManager): void {
return tabManager.setDionCredentials(email, password);
});
ipcMain.handle(IPC.GET_BITRIX_CREDENTIALS, () => {
return tabManager.getBitrixCredentials();
});
ipcMain.handle(IPC.SET_BITRIX_CREDENTIALS, (_e, portal: string, email: string, password: string) => {
return tabManager.setBitrixCredentials(portal, email, password);
});
ipcMain.handle(IPC.SEND_BOT_CALL_LINK, (_e, tabId: string, link: string) => {
tabManager.sendBotCallLink(tabId, link);
});
+79
View File
@@ -0,0 +1,79 @@
import { Platform, TunnelMode } from '../types';
import {
VK_COOKIE_DOMAINS,
YANDEX_COOKIE_DOMAINS,
DION_COOKIE_DOMAINS,
WBSTREAM_COOKIE_DOMAINS,
VK_LOGIN_URL,
YANDEX_LOGIN_URL,
DION_LOGIN_URL,
WBSTREAM_LOGIN_URL,
VK_AUTH_COOKIE,
YANDEX_AUTH_COOKIE,
DION_AUTH_COOKIE,
WBSTREAM_AUTH_COOKIE,
} from '../constants';
export interface PlatformConfig {
tunnelMode: TunnelMode;
authCookie: string;
refreshCookie: string;
loginUrl: string;
cookieDomains: string[];
platformName: string;
binarySubdir: string;
binaryBase: string;
joinFlag: string | null;
loginWaitCookies: string[] | null;
}
export const PLATFORM_CONFIG: Partial<Record<Platform, PlatformConfig>> = {
[Platform.VK]: {
tunnelMode: TunnelMode.HeadlessVK,
authCookie: VK_AUTH_COOKIE,
refreshCookie: VK_AUTH_COOKIE,
loginUrl: VK_LOGIN_URL,
cookieDomains: VK_COOKIE_DOMAINS,
platformName: 'VK',
binarySubdir: 'vk',
binaryBase: 'headless-vk-creator',
joinFlag: '--vk-link',
loginWaitCookies: null,
},
[Platform.Telemost]: {
tunnelMode: TunnelMode.HeadlessTelemost,
authCookie: YANDEX_AUTH_COOKIE,
refreshCookie: YANDEX_AUTH_COOKIE,
loginUrl: YANDEX_LOGIN_URL,
cookieDomains: YANDEX_COOKIE_DOMAINS,
platformName: 'Yandex',
binarySubdir: 'telemost',
binaryBase: 'headless-telemost-creator',
joinFlag: '--tm-link',
loginWaitCookies: null,
},
[Platform.Dion]: {
tunnelMode: TunnelMode.HeadlessDion,
authCookie: DION_AUTH_COOKIE,
refreshCookie: DION_AUTH_COOKIE,
loginUrl: DION_LOGIN_URL,
cookieDomains: DION_COOKIE_DOMAINS,
platformName: 'DION',
binarySubdir: 'dion',
binaryBase: 'headless-dion-creator',
joinFlag: '--room',
loginWaitCookies: ['vc-refresh-token', 'vc-access-token'],
},
[Platform.WBStream]: {
tunnelMode: TunnelMode.HeadlessWBStream,
authCookie: WBSTREAM_AUTH_COOKIE,
refreshCookie: 'wbx-refresh',
loginUrl: WBSTREAM_LOGIN_URL,
cookieDomains: WBSTREAM_COOKIE_DOMAINS,
platformName: 'WB Stream',
binarySubdir: 'wbstream',
binaryBase: 'headless-wbstream-creator',
joinFlag: '--room',
loginWaitCookies: ['x_wbaas_token', 'wbx-refresh', 'wbx-validation-key'],
},
};
+47 -428
View File
@@ -1,6 +1,4 @@
import { app } from 'electron';
import { spawn, ChildProcess } from 'child_process';
import { BrowserWindow, session } from 'electron';
import { app, BrowserWindow } from 'electron';
import * as net from 'net';
import * as path from 'path';
import * as fs from 'fs/promises';
@@ -10,36 +8,20 @@ import {
TabListEntry,
Platform,
TunnelMode,
RelayMode,
CallStatus,
HeadlessStartArgs,
HeadlessMode,
UpstreamProxy,
DionCredentials,
BitrixCredentials,
} from '../types';
import {
INITIAL_PORT_BASE,
IPC,
RELAY_RESTART_DELAY_MS,
SESSION_PARTITION,
VK_COOKIE_DOMAINS,
YANDEX_COOKIE_DOMAINS,
DION_COOKIE_DOMAINS,
WBSTREAM_COOKIE_DOMAINS,
VK_LOGIN_URL,
YANDEX_LOGIN_URL,
DION_LOGIN_URL,
WBSTREAM_LOGIN_URL,
VK_AUTH_COOKIE,
YANDEX_AUTH_COOKIE,
DION_AUTH_COOKIE,
WBSTREAM_AUTH_COOKIE,
LOG_CAPTURE_SNIPPET,
} from '../constants';
import { BotManager } from '../bot/bot-manager';
import { DionCookieFile } from './dion-cookie-file';
import { buildStoredZip } from './util/zip';
import { resolveResourcePath, binaryName } from './util/paths';
import { CookieStore } from './cookie-store';
import { HeadlessLauncher } from './headless-launcher';
export class TabManager {
private tabs = new Map<string, TabState>();
@@ -48,39 +30,15 @@ export class TabManager {
private nextPortBase = INITIAL_PORT_BASE;
private _mainWindow: BrowserWindow | null = null;
private _botManager: BotManager | null = null;
private relayPath: string;
private headlessVKPath: string;
private headlessTelemostPath: string;
private headlessWBStreamPath: string;
private headlessDionPath: string;
private hooksDir: string;
private upstreamProxy: UpstreamProxy = { socks: '', user: '', pass: '' };
private debugLogging = false;
private cookies = new CookieStore();
private launcher: HeadlessLauncher;
constructor() {
this.relayPath = resolveResourcePath(
path.join('relay', binaryName('relay')),
binaryName('relay'),
);
this.headlessVKPath = resolveResourcePath(
path.join('headless', 'vk', binaryName('headless-vk-creator')),
binaryName('headless-vk-creator'),
);
this.headlessTelemostPath = resolveResourcePath(
path.join('headless', 'telemost', binaryName('headless-telemost-creator')),
binaryName('headless-telemost-creator'),
);
this.headlessWBStreamPath = resolveResourcePath(
path.join('headless', 'wbstream', binaryName('headless-wbstream-creator')),
binaryName('headless-wbstream-creator'),
);
this.headlessDionPath = resolveResourcePath(
path.join('headless', 'dion', binaryName('headless-dion-creator')),
binaryName('headless-dion-creator'),
);
this.hooksDir = app.isPackaged
? path.join(process.resourcesPath!, 'hooks')
: path.join(__dirname, '..', '..', '..', 'hooks');
this.launcher = new HeadlessLauncher(this, this.cookies);
}
get mainWindow(): BrowserWindow | null {
@@ -142,7 +100,7 @@ export class TabManager {
deleteTab(tabId: string): void {
const tab = this.tabs.get(tabId);
if (tab) {
this.killRelay(tabId, tab);
this.launcher.killRelay(tabId, tab);
this.tabs.delete(tabId);
}
this.botTabIds.delete(tabId);
@@ -183,33 +141,6 @@ export class TabManager {
return result;
}
private sendLog(tabId: string, msg: string): void {
if (this._mainWindow && !this._mainWindow.isDestroyed()) {
this._mainWindow.webContents.send(IPC.RELAY_LOG, { tabId, msg });
}
}
private attachProcessOutput(
proc: ChildProcess,
tabId: string,
inspect?: (msg: string) => void,
): void {
const onData = (data: Buffer) => {
data
.toString()
.trim()
.split('\n')
.forEach((msg) => {
if (!msg) return;
console.log(`[relay:${tabId}]`, msg);
this.sendLog(tabId, msg);
if (inspect) inspect(msg);
});
};
proc.stdout?.on('data', onData);
proc.stderr?.on('data', onData);
}
sendBotCallLink(tabId: string, link: string): void {
if (!this.botTabIds.has(tabId) || !this._botManager) return;
const tab = this.tabs.get(tabId);
@@ -219,292 +150,42 @@ export class TabManager {
}
setUpstreamProxy(proxy: UpstreamProxy): void {
this.upstreamProxy = {
socks: (proxy?.socks || '').trim(),
user: (proxy?.user || '').trim(),
pass: (proxy?.pass || '').trim(),
};
this.launcher.setUpstreamProxy(proxy);
}
setDebugLogging(enabled: boolean): void {
this.debugLogging = enabled;
}
private appendUpstreamArgs(args: string[]): void {
if (!this.upstreamProxy.socks) return;
args.push('--upstream-socks', this.upstreamProxy.socks);
if (this.upstreamProxy.user) args.push('--upstream-user', this.upstreamProxy.user);
if (this.upstreamProxy.pass) args.push('--upstream-pass', this.upstreamProxy.pass);
this.launcher.setDebugLogging(enabled);
}
startRelay(tabId: string, tab: TabState): void {
this.killRelay(tabId, tab);
const port = tab.tunnelMode === TunnelMode.PionVideo ? tab.pionPort : tab.dcPort;
let relayMode: RelayMode = RelayMode.DCCreator;
if (tab.tunnelMode === TunnelMode.PionVideo) {
relayMode = tab.platform === Platform.Telemost
? RelayMode.TelemostVideoCreator
: RelayMode.VKVideoCreator;
}
const relayArgs = ['--mode', relayMode, '--ws-port', String(port)];
this.appendUpstreamArgs(relayArgs);
if (this.debugLogging) relayArgs.push('--debug');
const proc = spawn(this.relayPath, relayArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
});
tab.relay = proc;
this.attachProcessOutput(proc, tabId);
proc.on('close', (code) => {
this.sendLog(tabId, `Relay exited with code ${code}`);
});
this.launcher.startRelay(tabId, tab);
}
private headlessConfig(platform: Platform): {
tunnelMode: TunnelMode;
authCookie: string;
loginUrl: string;
cookieDomains: string[];
platformName: string;
binaryPath: string;
} | null {
switch (platform) {
case Platform.Telemost:
return {
tunnelMode: TunnelMode.HeadlessTelemost,
authCookie: YANDEX_AUTH_COOKIE,
loginUrl: YANDEX_LOGIN_URL,
cookieDomains: YANDEX_COOKIE_DOMAINS,
platformName: 'Yandex',
binaryPath: this.headlessTelemostPath,
};
case Platform.Dion:
return {
tunnelMode: TunnelMode.HeadlessDion,
authCookie: DION_AUTH_COOKIE,
loginUrl: DION_LOGIN_URL,
cookieDomains: DION_COOKIE_DOMAINS,
platformName: 'DION',
binaryPath: this.headlessDionPath,
};
case Platform.VK:
return {
tunnelMode: TunnelMode.HeadlessVK,
authCookie: VK_AUTH_COOKIE,
loginUrl: VK_LOGIN_URL,
cookieDomains: VK_COOKIE_DOMAINS,
platformName: 'VK',
binaryPath: this.headlessVKPath,
};
case Platform.WBStream:
return {
tunnelMode: TunnelMode.HeadlessWBStream,
authCookie: WBSTREAM_AUTH_COOKIE,
loginUrl: WBSTREAM_LOGIN_URL,
cookieDomains: WBSTREAM_COOKIE_DOMAINS,
platformName: 'WB Stream',
binaryPath: this.headlessWBStreamPath,
};
default:
return null;
}
}
private joinFlagFor(platform: Platform): string | null {
switch (platform) {
case Platform.VK:
return '--vk-link';
case Platform.Telemost:
return '--tm-link';
case Platform.WBStream:
case Platform.Dion:
return '--room';
default:
return null;
}
}
async startHeadless(tabId: string, platform: Platform, args: HeadlessStartArgs): Promise<void> {
const tab = await this.getOrCreateTab(tabId);
tab.platform = platform;
const joinTarget = args.mode === HeadlessMode.Join ? (args.target || '').trim() : '';
if (args.mode === HeadlessMode.Join && !joinTarget) {
this.sendLog(tabId, 'Join requested but no target link/room provided.');
return;
}
const config = this.headlessConfig(platform);
if (!config) {
this.sendLog(tabId, `Unsupported headless platform: ${platform}`);
return;
}
tab.tunnelMode = config.tunnelMode;
const cookiesPath = this.cookieFilePath(platform);
const refreshCookie = platform === Platform.WBStream ? 'wbx-refresh' : config.authCookie;
const dionCookieFile = platform === Platform.Dion ? new DionCookieFile(cookiesPath) : null;
const fileHasSession = dionCookieFile != null && await dionCookieFile.hasSession();
let cookies = await this.getCookiesForDomains(config.cookieDomains);
const needsLogin = !fileHasSession && !cookies.some((c) => c.name === refreshCookie);
if (needsLogin) {
if (tab.isBot) {
const reply = `Please log into ${config.platformName} in the creator app first, then try again.`;
this.sendLog(tabId, reply);
if (this._botManager && tab.peerId != null) {
await this._botManager.sendMessage(tab.peerId, reply);
}
return;
}
this.sendLog(tabId, `No ${config.platformName} session found, opening login.`);
if (this._mainWindow && !this._mainWindow.isDestroyed()) {
this._mainWindow.webContents.send(IPC.LOGIN_REQUIRED, { tabId, url: config.loginUrl });
}
if (platform === Platform.WBStream) {
this.sendLog(tabId, 'Waiting for x_wbaas_token, wbx-refresh, wbx-validation-key...');
await this.waitForCookies(['x_wbaas_token', 'wbx-refresh', 'wbx-validation-key']);
} else if (platform === Platform.Dion) {
this.sendLog(tabId, 'Waiting for vc-refresh-token, vc-access-token...');
await this.waitForCookies(['vc-refresh-token', 'vc-access-token']);
} else {
await this.waitForLogin(config.cookieDomains, config.authCookie);
}
if (this._mainWindow && !this._mainWindow.isDestroyed()) {
this._mainWindow.webContents.send(IPC.LOGIN_DONE, { tabId });
}
this.sendLog(tabId, `${config.platformName} login captured.`);
cookies = await this.getCookiesForDomains(config.cookieDomains);
}
if (fileHasSession) {
this.sendLog(tabId, `${config.platformName} session file is still active, keeping it as is.`);
} else {
this.sendLog(tabId, `${config.platformName} cookies (${cookies.length}): ${cookies.map((c) => c.name).join(', ')}`);
await fs.writeFile(cookiesPath, JSON.stringify(cookies));
}
const spawnArgs = ['--resources', 'default', '--cookies', cookiesPath];
this.killRelay(tabId, tab);
if (joinTarget) {
const flag = this.joinFlagFor(platform);
if (flag) spawnArgs.push(flag, joinTarget);
}
this.appendUpstreamArgs(spawnArgs);
if (this.debugLogging) spawnArgs.push('--debug');
const proc = spawn(config.binaryPath, spawnArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
});
tab.relay = proc;
let sawAuthFailure = false;
let sawInvalidCredentials = false;
this.attachProcessOutput(proc, tabId, (msg) => {
if (dionCookieFile && (msg.includes('"code":1086') || msg.includes('Invalid credentials'))) {
sawInvalidCredentials = true;
}
if (
msg.includes('status 401') ||
msg.includes('"UnauthorizedError"') ||
msg.includes('"error":"unauthorized') ||
msg.includes('empty access_token')
) {
sawAuthFailure = true;
}
});
proc.on('close', async (code) => {
this.sendLog(tabId, `Headless exited with code ${code}`);
if (sawInvalidCredentials) {
this.sendLog(tabId, `${config.platformName} rejected the email and password stored in ${cookiesPath}, fix them or clear cookies to log in through the browser.`);
return;
}
if (sawAuthFailure) {
if (dionCookieFile) await dionCookieFile.clearTokens();
await this.clearAuthCookies(config.cookieDomains, config.authCookie);
if (this.tabs.get(tabId) === tab) this.startHeadless(tabId, platform, args);
}
});
}
private async clearAuthCookies(cookieDomains: string[], authCookieName: string): Promise<void> {
const ses = session.fromPartition(SESSION_PARTITION);
const matches = await ses.cookies.get({ name: authCookieName });
for (const cookie of matches) {
if (!cookie.domain || !cookieDomains.some((d) => cookie.domain!.includes(d))) continue;
const host = cookie.domain.startsWith('.') ? cookie.domain.slice(1) : cookie.domain;
const url = `https://${host}${cookie.path || '/'}`;
try {
await ses.cookies.remove(url, cookie.name);
} catch (err) {
console.log(`[COOKIES] failed to remove ${cookie.name} on ${url}:`, err);
}
}
}
private cookieFilePath(platform: Platform): string {
return path.join(app.getPath('userData'), `cookies-${platform}.json`);
}
async getDionCredentials(): Promise<DionCredentials> {
return new DionCookieFile(this.cookieFilePath(Platform.Dion)).readCredentials();
}
async setDionCredentials(email: string, password: string): Promise<void> {
await new DionCookieFile(this.cookieFilePath(Platform.Dion)).writeCredentials(email, password);
}
async clearPlatformCookies(platform: Platform): Promise<number> {
const config = this.headlessConfig(platform);
if (!config) return 0;
const ses = session.fromPartition(SESSION_PARTITION);
const all = await ses.cookies.get({});
let removed = 0;
for (const cookie of all) {
if (!cookie.domain || !config.cookieDomains.some((d) => cookie.domain!.includes(d))) continue;
const host = cookie.domain.startsWith('.') ? cookie.domain.slice(1) : cookie.domain;
const url = `https://${host}${cookie.path || '/'}`;
try {
await ses.cookies.remove(url, cookie.name);
removed++;
} catch (err) {
console.log(`[COOKIES] failed to remove ${cookie.name} on ${url}:`, err);
}
}
await fs.unlink(this.cookieFilePath(platform)).catch(() => {});
console.log(`[COOKIES] cleared ${removed} cookies for ${platform}`);
return removed;
}
private waitForLogin(cookieDomains: string[], authCookieName: string): Promise<void> {
return new Promise((resolve) => {
const ses = session.fromPartition(SESSION_PARTITION);
const finish = () => {
ses.cookies.removeListener('changed', onChanged);
resolve();
};
const onChanged = (
_e: Electron.Event,
cookie: Electron.Cookie,
_cause: string,
removed: boolean,
) => {
if (removed) return;
if (cookie.name !== authCookieName) return;
if (!cookie.domain || !cookieDomains.some((d) => cookie.domain!.includes(d))) return;
finish();
};
ses.cookies.on('changed', onChanged);
ses.cookies.get({ name: authCookieName }).then((found) => {
if (found.some((c) => c.domain && cookieDomains.some((d) => c.domain!.includes(d)))) {
finish();
}
});
});
startHeadless(tabId: string, platform: Platform, args: HeadlessStartArgs): Promise<void> {
return this.launcher.startHeadless(tabId, platform, args);
}
killRelay(tabId: string, tab: TabState): void {
if (tab.relay) {
console.log(`[${tabId}] killing process pid=${tab.relay.pid}`);
tab.relay.kill();
tab.relay = null;
}
this.launcher.killRelay(tabId, tab);
}
killAllRelays(): void {
this.tabs.forEach((tab, tabId) => this.killRelay(tabId, tab));
this.tabs.forEach((tab, tabId) => this.launcher.killRelay(tabId, tab));
}
async setTunnelMode(tabId: string, mode: TunnelMode, platform?: Platform): Promise<void> {
const tab = await this.getOrCreateTab(tabId);
tab.tunnelMode = mode;
if (platform) tab.platform = platform;
if (
mode === TunnelMode.HeadlessVK ||
mode === TunnelMode.HeadlessTelemost ||
mode === TunnelMode.HeadlessWBStream ||
mode === TunnelMode.HeadlessDion ||
mode === TunnelMode.HeadlessBitrix
) return;
this.launcher.killRelay(tabId, tab);
setTimeout(() => this.launcher.startRelay(tabId, tab), RELAY_RESTART_DELAY_MS);
}
async loadHook(tabId: string, url: string, tab: TabState): Promise<string> {
@@ -526,93 +207,31 @@ export class TabManager {
return LOG_CAPTURE_SNIPPET + `window.WS_PORT=${tab.dcPort};` + hook;
}
async setTunnelMode(tabId: string, mode: TunnelMode, platform?: Platform): Promise<void> {
const tab = await this.getOrCreateTab(tabId);
tab.tunnelMode = mode;
if (platform) tab.platform = platform;
if (
mode === TunnelMode.HeadlessVK ||
mode === TunnelMode.HeadlessTelemost ||
mode === TunnelMode.HeadlessWBStream ||
mode === TunnelMode.HeadlessDion
) return;
this.killRelay(tabId, tab);
setTimeout(() => this.startRelay(tabId, tab), RELAY_RESTART_DELAY_MS);
getDionCredentials(): Promise<DionCredentials> {
return this.cookies.getDionCredentials();
}
private async getCookiesForDomains(domains: string[]): Promise<{ name: string; value: string }[]> {
const ses = session.fromPartition(SESSION_PARTITION);
const all = await ses.cookies.get({});
return all
.filter((c) => c.domain != null && domains.some((d) => c.domain!.includes(d)))
.map((c) => ({ name: c.name, value: c.value }));
setDionCredentials(email: string, password: string): Promise<void> {
return this.cookies.setDionCredentials(email, password);
}
private waitForCookies(names: string[]): Promise<void> {
return new Promise((resolve) => {
const ses = session.fromPartition(SESSION_PARTITION);
const remaining = new Set(names);
const finish = () => {
ses.cookies.removeListener('changed', onChanged);
resolve();
};
const onChanged = (
_e: Electron.Event,
cookie: Electron.Cookie,
_cause: string,
removed: boolean,
) => {
if (removed) return;
if (!remaining.has(cookie.name)) return;
remaining.delete(cookie.name);
if (remaining.size === 0) finish();
};
ses.cookies.on('changed', onChanged);
Promise.all(names.map((name) => ses.cookies.get({ name }))).then((results) => {
results.forEach((found, i) => {
if (found.length > 0) remaining.delete(names[i]);
});
if (remaining.size === 0) finish();
});
});
getBitrixCredentials(): Promise<BitrixCredentials> {
return this.cookies.getBitrixCredentials();
}
async buildCookiesZip(): Promise<Buffer> {
const platforms: { filename: string; domains: string[]; platform: Platform }[] = [
{ filename: 'cookies-vk.json', domains: VK_COOKIE_DOMAINS, platform: Platform.VK },
{ filename: 'cookies-yandex.json', domains: YANDEX_COOKIE_DOMAINS, platform: Platform.Telemost },
{ filename: 'cookies-dion.json', domains: DION_COOKIE_DOMAINS, platform: Platform.Dion },
{ filename: 'cookies-wbstream.json', domains: WBSTREAM_COOKIE_DOMAINS, platform: Platform.WBStream },
];
const cookies = await Promise.all(platforms.map((p) => this.getCookiesForDomains(p.domains)));
const dionContent = await new DionCookieFile(this.cookieFilePath(Platform.Dion)).readContent();
const entries = platforms.map((p, i) => {
const content = p.platform === Platform.Dion && dionContent ? dionContent : cookies[i];
return { name: p.filename, data: Buffer.from(JSON.stringify(content, null, 2), 'utf8') };
});
return buildStoredZip(entries);
setBitrixCredentials(portal: string, email: string, password: string): Promise<void> {
return this.cookies.setBitrixCredentials(portal, email, password);
}
async setWBStreamDeviceId(id: string): Promise<void> {
if (!id) return;
const ses = session.fromPartition(SESSION_PARTITION);
const existing = await ses.cookies.get({ url: 'https://stream.wb.ru/', name: '__wb_device_id' });
if (existing.length > 0 && existing[0].value === id) return;
try {
await ses.cookies.set({
url: 'https://stream.wb.ru/',
name: '__wb_device_id',
value: id,
domain: 'stream.wb.ru',
path: '/',
secure: true,
httpOnly: false,
expirationDate: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 365 * 5,
});
console.log(`[wb-device-id] persisted ${id}`);
} catch (err) {
console.log(`[wb-device-id] failed to persist:`, err);
}
clearPlatformCookies(platform: Platform): Promise<number> {
return this.cookies.clearPlatformCookies(platform);
}
buildCookiesZip(): Promise<Buffer> {
return this.cookies.buildCookiesZip();
}
setWBStreamDeviceId(id: string): Promise<void> {
return this.cookies.setWBStreamDeviceId(id);
}
}
+6
View File
@@ -38,6 +38,12 @@ import { IPC } from '../constants';
setDionCredentials(email: string, password: string) {
return ipcRenderer.invoke(IPC.SET_DION_CREDENTIALS, email, password);
},
getBitrixCredentials() {
return ipcRenderer.invoke(IPC.GET_BITRIX_CREDENTIALS);
},
setBitrixCredentials(portal: string, email: string, password: string) {
return ipcRenderer.invoke(IPC.SET_BITRIX_CREDENTIALS, portal, email, password);
},
onCreateBotTab(cb: (data: any) => void) {
ipcRenderer.on(IPC.CREATE_BOT_TAB, (_e, data) => cb(data));
},
+11
View File
@@ -56,6 +56,7 @@ export function renderContent(tm: RendererTabManager): void {
if (activeTab.platform === Platform.Telemost) title = 'Telemost';
else if (activeTab.platform === Platform.WBStream) title = 'WBStream';
else if (activeTab.platform === Platform.Dion) title = 'DION';
else if (activeTab.platform === Platform.Bitrix) title = 'Bitrix';
document.getElementById('headlessTitle')!.textContent = title;
const startEl = document.getElementById('headlessStart')!;
const statusEl = document.getElementById('headlessStatus')!;
@@ -70,12 +71,17 @@ export function renderContent(tm: RendererTabManager): void {
errorEl.textContent = '';
const dionAccountCard = document.getElementById('headlessDionAccountCard')!;
dionAccountCard.style.display = activeTab.platform === Platform.Dion ? '' : 'none';
const bitrixAccountCard = document.getElementById('headlessBitrixAccountCard')!;
bitrixAccountCard.style.display = activeTab.platform === Platform.Bitrix ? '' : 'none';
if (activeTab.platform === Platform.WBStream) {
targetLabel.textContent = 'Paste a room id or stream.wb.ru/room/<id> link.';
targetInput.placeholder = 'https://stream.wb.ru/room/<id>';
} else if (activeTab.platform === Platform.Dion) {
targetLabel.textContent = 'Paste a room id or dion.vc event link.';
targetInput.placeholder = 'abc-def-ghi';
} else if (activeTab.platform === Platform.Bitrix) {
targetLabel.textContent = 'Paste a portal /video/ link, or leave empty to create a new room.';
targetInput.placeholder = 'https://your-portal.bitrix24.ru/video/CODE';
} else if (activeTab.platform === Platform.Telemost) {
targetLabel.textContent = 'Paste a Telemost conference link.';
targetInput.placeholder = 'https://telemost.yandex.ru/j/...';
@@ -93,10 +99,12 @@ export function renderContent(tm: RendererTabManager): void {
const callInfoTM = document.getElementById('headlessCallInfoTM')!;
const callInfoWB = document.getElementById('headlessCallInfoWB')!;
const callInfoDion = document.getElementById('headlessCallInfoDion')!;
const callInfoBitrix = document.getElementById('headlessCallInfoBitrix')!;
callInfoVK.style.display = 'none';
callInfoTM.style.display = 'none';
callInfoWB.style.display = 'none';
callInfoDion.style.display = 'none';
callInfoBitrix.style.display = 'none';
if (callInfo) {
if (activeTab.platform === Platform.WBStream) {
callInfoWB.style.display = 'block';
@@ -108,6 +116,9 @@ export function renderContent(tm: RendererTabManager): void {
} else if (activeTab.platform === Platform.Dion) {
callInfoDion.style.display = 'block';
document.getElementById('headlessDionJoinLink')!.textContent = callInfo.joinLink || '';
} else if (activeTab.platform === Platform.Bitrix) {
callInfoBitrix.style.display = 'block';
document.getElementById('headlessBitrixJoinLink')!.textContent = callInfo.joinLink || '';
} else {
callInfoVK.style.display = 'block';
document.getElementById('headlessJoinLink')!.textContent = callInfo.joinLink || '';
+56 -29
View File
@@ -60,6 +60,7 @@ function bindToolbarEvents(): void {
document.getElementById('btnHeadlessTM')!.addEventListener('click', () => tm.switchToHeadless(Platform.Telemost));
document.getElementById('btnHeadlessWB')!.addEventListener('click', () => tm.switchToHeadless(Platform.WBStream));
document.getElementById('btnHeadlessDion')!.addEventListener('click', () => tm.switchToHeadless(Platform.Dion));
document.getElementById('btnHeadlessBitrix')!.addEventListener('click', () => tm.switchToHeadless(Platform.Bitrix));
document.getElementById('modeSelect')!.addEventListener('change', (event) => {
tm.setTunnelMode((event.target as HTMLSelectElement).value);
});
@@ -108,41 +109,52 @@ function bindSettingsEvents(): void {
});
}
function bindDionAccountEvents(): void {
document.getElementById('btnDionAccount')!.addEventListener('click', openDionAccount);
document.getElementById('dionAccountPopup')!.addEventListener('click', closeDionAccount);
document.querySelector('#dionAccountPopup .popup')!.addEventListener('click', (event) => event.stopPropagation());
document.getElementById('btnDionAccountCancel')!.addEventListener('click', closeDionAccount);
document.getElementById('btnDionAccountSave')!.addEventListener('click', async () => {
const email = (document.getElementById('dionEmail') as HTMLInputElement).value.trim();
const password = (document.getElementById('dionPassword') as HTMLInputElement).value;
const status = document.getElementById('dionAccountStatus')!;
interface AccountPopupConfig {
name: string;
fields: string[];
load: () => Promise<Record<string, string>>;
save: (values: Record<string, string>) => Promise<void>;
readError: string;
}
function bindAccountPopup(cfg: AccountPopupConfig): void {
const lc = cfg.name.toLowerCase();
const popup = document.getElementById(`${lc}AccountPopup`)!;
const status = document.getElementById(`${lc}AccountStatus`)!;
const field = (key: string) =>
document.getElementById(`${lc}${key[0].toUpperCase()}${key.slice(1)}`) as HTMLInputElement;
const close = (): void => popup.classList.remove('visible');
const open = async (): Promise<void> => {
status.textContent = '';
popup.classList.add('visible');
try {
await window.bridge.setDionCredentials(email, password);
closeDionAccount();
const values = await cfg.load();
for (const key of cfg.fields) field(key).value = values[key] ?? '';
} catch {
status.textContent = cfg.readError;
}
};
document.getElementById(`btn${cfg.name}Account`)!.addEventListener('click', open);
popup.addEventListener('click', close);
popup.querySelector('.popup')!.addEventListener('click', (event) => event.stopPropagation());
document.getElementById(`btn${cfg.name}AccountCancel`)!.addEventListener('click', close);
document.getElementById(`btn${cfg.name}AccountSave`)!.addEventListener('click', async () => {
const values: Record<string, string> = {};
for (const key of cfg.fields) {
const raw = field(key).value;
values[key] = key === 'password' ? raw : raw.trim();
}
try {
await cfg.save(values);
close();
} catch {
status.textContent = 'Failed to save the credentials.';
}
});
}
async function openDionAccount(): Promise<void> {
const status = document.getElementById('dionAccountStatus')!;
status.textContent = '';
document.getElementById('dionAccountPopup')!.classList.add('visible');
try {
const credentials = await window.bridge.getDionCredentials();
(document.getElementById('dionEmail') as HTMLInputElement).value = credentials.email;
(document.getElementById('dionPassword') as HTMLInputElement).value = credentials.password;
} catch {
status.textContent = 'Failed to read the session file.';
}
}
function closeDionAccount(): void {
document.getElementById('dionAccountPopup')!.classList.remove('visible');
}
function bindErrorPopup(): void {
document.getElementById('errorPopup')!.addEventListener('click', closeError);
document.querySelector('#errorPopup .popup')!.addEventListener('click', (event) => event.stopPropagation());
@@ -224,7 +236,20 @@ function init(): void {
bindToolbarEvents();
bindActionBarEvents();
bindSettingsEvents();
bindDionAccountEvents();
bindAccountPopup({
name: 'Dion',
fields: ['email', 'password'],
load: async () => ({ ...(await window.bridge.getDionCredentials()) }),
save: (v) => window.bridge.setDionCredentials(v.email, v.password),
readError: 'Failed to read the session file.',
});
bindAccountPopup({
name: 'Bitrix',
fields: ['portal', 'email', 'password'],
load: async () => ({ ...(await window.bridge.getBitrixCredentials()) }),
save: (v) => window.bridge.setBitrixCredentials(v.portal, v.email, v.password),
readError: 'Failed to read the account file.',
});
bindErrorPopup();
bindLogEvents();
bindHeadlessEvents();
@@ -253,6 +278,8 @@ function init(): void {
tm.switchToHeadless(Platform.WBStream, data.joinTarget);
} else if (data.mode === TunnelMode.HeadlessDion) {
tm.switchToHeadless(Platform.Dion, data.joinTarget);
} else if (data.mode === TunnelMode.HeadlessBitrix) {
tm.switchToHeadless(Platform.Bitrix, data.joinTarget);
} else {
const url = data.platform === Platform.Telemost ? TELEMOST_URL : VK_IM_URL;
loadURL(tm, url);
+7 -1
View File
@@ -70,6 +70,10 @@ export class RendererTabManager {
tab.mode = TunnelMode.HeadlessDion;
if (!tab.isBot) tab.name = 'DION';
break;
case Platform.Bitrix:
tab.mode = TunnelMode.HeadlessBitrix;
if (!tab.isBot) tab.name = 'Bitrix';
break;
default:
tab.mode = TunnelMode.HeadlessVK;
if (!tab.isBot) tab.name = 'VK';
@@ -109,11 +113,13 @@ export class RendererTabManager {
data.mode === TunnelMode.HeadlessVK ||
data.mode === TunnelMode.HeadlessTelemost ||
data.mode === TunnelMode.HeadlessWBStream ||
data.mode === TunnelMode.HeadlessDion;
data.mode === TunnelMode.HeadlessDion ||
data.mode === TunnelMode.HeadlessBitrix;
let platformName = 'VK';
if (data.platform === Platform.Telemost) platformName = 'Telemost';
else if (data.platform === Platform.WBStream) platformName = 'WBStream';
else if (data.platform === Platform.Dion) platformName = 'DION';
else if (data.platform === Platform.Bitrix) platformName = 'Bitrix';
const botName = isHeadless ? `Bot-${platformName}` : `Bot-${platformName} (legacy)`;
this.tabs[data.tabId] = {
wv: null,
+10
View File
@@ -7,6 +7,7 @@ export enum TunnelMode {
HeadlessTelemost = 'headless-telemost',
HeadlessWBStream = 'headless-wbstream',
HeadlessDion = 'headless-dion',
HeadlessBitrix = 'headless-bitrix',
}
export enum Platform {
@@ -14,6 +15,7 @@ export enum Platform {
Telemost = 'telemost',
WBStream = 'wbstream',
Dion = 'dion',
Bitrix = 'bitrix',
}
export enum RelayMode {
@@ -87,6 +89,12 @@ export interface DionCredentials {
password: string;
}
export interface BitrixCredentials {
portal: string;
email: string;
password: string;
}
export interface TabConfig {
mode: TunnelMode;
peerId: number;
@@ -171,6 +179,8 @@ export interface Bridge {
clearCookies(platform: string): Promise<number>;
getDionCredentials(): Promise<DionCredentials>;
setDionCredentials(email: string, password: string): Promise<void>;
getBitrixCredentials(): Promise<BitrixCredentials>;
setBitrixCredentials(portal: string, email: string, password: string): Promise<void>;
onCreateBotTab(cb: (data: BotTabData) => void): void;
getCallCreatorCode(scriptFile: string): Promise<string>;
onBotError(cb: (msg: string) => void): void;
+6
View File
@@ -188,6 +188,12 @@ body {
opacity: 0.85;
}
.btn-headless-bitrix {
background: #2fc7f7;
color: white;
opacity: 0.85;
}
.toolbar-spacer {
margin-left: auto;
}
+38
View File
@@ -0,0 +1,38 @@
module headless-bitrix-creator
go 1.26.1
require whitelist-bypass/relay v0.0.0
require (
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
github.com/klauspost/reedsolomon v1.12.0 // indirect
github.com/pion/datachannel v1.6.0 // indirect
github.com/pion/dtls/v3 v3.1.2 // indirect
github.com/pion/ice/v4 v4.2.2 // indirect
github.com/pion/interceptor v0.1.44 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/mdns/v2 v2.1.0 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.16 // indirect
github.com/pion/rtp v1.10.1 // indirect
github.com/pion/sctp v1.9.4 // indirect
github.com/pion/sdp/v3 v3.0.18 // indirect
github.com/pion/srtp/v3 v3.0.10 // indirect
github.com/pion/stun/v3 v3.1.1 // indirect
github.com/pion/transport/v4 v4.0.1 // indirect
github.com/pion/turn/v4 v4.1.4 // indirect
github.com/pion/webrtc/v4 v4.2.11 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/tjfoc/gmsm v1.4.1 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
github.com/xtaci/kcp-go/v5 v5.6.72 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/time v0.14.0 // indirect
)
replace whitelist-bypass/relay => ../../relay
+138
View File
@@ -0,0 +1,138 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc=
github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/klauspost/reedsolomon v1.12.0 h1:I5FEp3xSwVCcEh3F5A7dofEfhXdF/bWhQWPH+XwBFno=
github.com/klauspost/reedsolomon v1.12.0/go.mod h1:EPLZJeh4l27pUGC3aXOjheaoh1I9yut7xTURiW3LQ9Y=
github.com/pion/datachannel v1.6.0 h1:XecBlj+cvsxhAMZWFfFcPyUaDZtd7IJvrXqlXD/53i0=
github.com/pion/datachannel v1.6.0/go.mod h1:ur+wzYF8mWdC+Mkis5Thosk+u/VOL287apDNEbFpsIk=
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
github.com/pion/ice/v4 v4.2.2 h1:dQJzzcgTFHDYyV3BoCfjPeX+JEtr58BWPi4PGyo6Vjg=
github.com/pion/ice/v4 v4.2.2/go.mod h1:2quLV1S5v1tAx3VvAJaH//KGitRXvo4RKlX6D3tnN+c=
github.com/pion/interceptor v0.1.44 h1:sNlZwM8dWXU9JQAkJh8xrarC0Etn8Oolcniukmuy0/I=
github.com/pion/interceptor v0.1.44/go.mod h1:4atVlBkcgXuUP+ykQF0qOCGU2j7pQzX2ofvPRFsY5RY=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY=
github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
github.com/pion/rtp v1.10.1 h1:xP1prZcCTUuhO2c83XtxyOHJteISg6o8iPsE2acaMtA=
github.com/pion/rtp v1.10.1/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM=
github.com/pion/sctp v1.9.4 h1:cMxEu0F5tbP4qH07bKf1Zjf4rUih9LIo0qQt424e258=
github.com/pion/sctp v1.9.4/go.mod h1:N20Dq6LY+JvJDAh9VVh1JELngb2rQ8dPgds5yBWiPgw=
github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI=
github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8=
github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ=
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=
github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=
github.com/pion/webrtc/v4 v4.2.11 h1:QUX1QZKlNIn4O7U5JxLPGP0sV5RTncZkzu9SPR3jVNU=
github.com/pion/webrtc/v4 v4.2.11/go.mod h1:s/rAiyy77GyRFrZMx+Ls6aua26dIBPudH8/ZHYbIRWY=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/xtaci/kcp-go/v5 v5.6.72 h1:FLaQPalgpufJYQRk0OK+gErEhXGLUPjv6FSRPrFR8Lk=
github.com/xtaci/kcp-go/v5 v5.6.72/go.mod h1:9O3D8WR+cyyUjGiTILYfg17vn72otWuXK2AFfqIe6CM=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+198
View File
@@ -0,0 +1,198 @@
package main
import (
"flag"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"runtime/debug"
"strings"
"sync"
"syscall"
"whitelist-bypass/relay/bitrix"
"whitelist-bypass/relay/common"
"whitelist-bypass/relay/tunnel"
)
func main() {
common.MaybePrintVersion()
cookiesPath := flag.String("cookies", "", "path to cookies-bitrix.json (exported from creator-app: email/password/portal/cookies)")
roomFlag := flag.String("room", "", "conference link https://portal/video/CODE or alias to rejoin as host (empty = create new room)")
resources := flag.String("resources", "default", "resource mode: moderate, default, unlimited")
writeFile := flag.String("write-file", "", "path to file where the active guest link is appended")
upstreamSocks := flag.String("upstream-socks", "", "route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username")
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password")
debugFlag := flag.Bool("debug", false, "verbose debug logging")
allowPrivate := flag.Bool("allow-private-dst", false, "let the joiner reach private/internal addresses through this creator")
flag.Parse()
common.Debug = *debugFlag
common.AllowPrivateDst = *allowPrivate
var memLimit int64
switch *resources {
case "moderate":
memLimit = 64 << 20
case "default":
memLimit = 128 << 20
case "unlimited":
memLimit = 256 << 20
default:
log.Fatalf("[config] unknown resources mode: %s", *resources)
}
if memLimit > 0 {
debug.SetMemoryLimit(memLimit)
}
log.Printf("[config] resources=%s", *resources)
if *cookiesPath == "" {
log.Fatalf("[FATAL] --cookies is required")
}
creds, err := bitrix.LoadCredentials(*cookiesPath)
if err != nil {
log.Fatalf("[FATAL] LoadCredentials: %v", err)
}
portal := creds.Portal
alias := ""
if *roomFlag != "" {
if strings.Contains(*roomFlag, "://") {
u, perr := url.Parse(*roomFlag)
if perr != nil {
log.Fatalf("[FATAL] bad room link: %v", perr)
}
portal = u.Scheme + "://" + u.Host
alias = strings.TrimPrefix(u.Path, "/video/")
} else {
alias = *roomFlag
}
}
if portal == "" {
log.Fatalf("[FATAL] no portal: set \"portal\" in %s or pass a full --room link", *cookiesPath)
}
userAgent := common.RandomDeviceProfile().UserAgent
c, err := bitrix.NewClient(portal, userAgent)
if err != nil {
log.Fatalf("[FATAL] NewClient: %v", err)
}
if err := c.LoadSession(*cookiesPath); err != nil {
common.EmitAuthError(common.AuthErrorSessionExpired)
log.Fatalf("[FATAL] LoadSession: %v", err)
}
if err := c.EnsureLogin(); err != nil {
if strings.Contains(err.Error(), "login rejected") {
common.EmitAuthError(common.AuthErrorInvalidCredentials)
} else {
common.EmitAuthError(common.AuthErrorSessionExpired)
}
log.Fatalf("[FATAL] EnsureLogin: %v", err)
}
log.Printf("[auth] ready")
var res bitrix.JoinResult
joinLink := ""
if alias != "" {
log.Printf("[room] rejoining as HOST alias=%s", alias)
res, err = c.JoinAsHost(alias)
if err != nil {
log.Fatalf("[FATAL] JoinAsHost(%s): %v", alias, err)
}
joinLink = portal + "/video/" + alias
} else {
res, joinLink, err = c.CreateAndJoin()
if err != nil {
log.Fatalf("[FATAL] CreateAndJoin: %v", err)
}
if u, perr := url.Parse(joinLink); perr == nil {
alias = strings.TrimPrefix(u.Path, "/video/")
}
log.Printf("[room] created alias=%s", alias)
}
if alias == "" {
log.Fatalf("[FATAL] could not resolve conference alias")
}
log.Printf("[room] roomId=%s mediaServer=%s", res.RoomID, res.MediaServerURL)
if *writeFile != "" {
fileHandle, ferr := os.OpenFile(*writeFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if ferr != nil {
log.Fatalf("[FATAL] open write-file: %v", ferr)
}
fmt.Fprintln(fileHandle, joinLink)
fileHandle.Close()
log.Printf("[config] wrote join link to %s", *writeFile)
}
fmt.Println("")
fmt.Println(" CALL CREATED")
fmt.Println(" join_link: " + joinLink)
fmt.Println("")
var once sync.Once
connected := make(chan struct{})
sig, err := bitrix.ConnectSignal(bitrix.SignalConfig{
SignalURL: bitrix.SignalURL(res),
Origin: portal,
UserAgent: userAgent,
LogFn: log.Printf,
OnConnected: func() {
once.Do(func() { close(connected) })
},
})
if err != nil {
log.Fatalf("[FATAL] signal connect: %v", err)
}
defer sig.Close()
ms, err := bitrix.NewMediaSession(bitrix.MediaParams{
Signal: sig,
Alias: alias,
Mode: bitrix.TunnelModeAuto,
FPS: 24,
Batch: 30,
LogFn: log.Printf,
})
if err != nil {
log.Fatalf("[FATAL] media session: %v", err)
}
ms.OnConnected = func(tun tunnel.DataTunnel) {
readBuf := common.VP8BufSize
switch tun.(type) {
case *tunnel.DCTunnel, *tunnel.MultiTrackKCPTunnel:
readBuf = common.DCBufSize
}
rb := tunnel.NewRelayBridge(tun, "creator", readBuf, log.Printf)
rb.SetUpstreamSocks(*upstreamSocks, *upstreamUser, *upstreamPass)
rb.MarkReady()
log.Printf("[bx] creator egress ready transport=%T upstream=%q", tun, *upstreamSocks)
fmt.Println("")
fmt.Println(" TUNNEL CONNECTED")
fmt.Println("")
}
go func() {
<-connected
if err := ms.Start(); err != nil {
log.Printf("[bx] media start failed: %v", err)
}
}()
go func() {
if err := sig.Run(); err != nil {
log.Printf("[signal] run ended: %v", err)
}
}()
log.Printf("[bx] role=creator alias=%s waiting for media...", alias)
shutdownChan := make(chan os.Signal, 1)
signal.Notify(shutdownChan, os.Interrupt, syscall.SIGTERM)
<-shutdownChan
log.Printf("[shutdown] signal received, exiting")
ms.Stop()
}
+1
View File
@@ -65,6 +65,7 @@ func main() {
log.Printf("[auth] credentials present, session will re-login automatically when the refresh token dies")
}
if err := auth.EnsureValidToken(); err != nil {
common.EmitAuthErrorFor(err)
log.Fatalf("[FATAL] EnsureValidToken: %v", err)
}
+2
View File
@@ -996,11 +996,13 @@ func main() {
if *tmLink != "" {
connInfo, err = joinExistingConference(cookieStr, *tmLink, cfg)
if err != nil {
common.EmitAuthErrorFor(err)
log.Fatalf("Failed to join existing conference: %v", err)
}
} else {
connInfo, err = createAndJoinCall(cookieStr, cfg)
if err != nil {
common.EmitAuthErrorFor(err)
log.Fatalf("Failed to create call: %v", err)
}
}
+2
View File
@@ -698,11 +698,13 @@ func main() {
if *vkLink != "" {
callInfo, err = joinExistingCall(cookieStr, *vkLink, cfg)
if err != nil {
common.EmitAuthErrorFor(err)
log.Fatalf("Failed to join existing call: %v", err)
}
} else {
callInfo, err = createAndJoinCall(cookieStr, *peerId, cfg)
if err != nil {
common.EmitAuthErrorFor(err)
log.Fatalf("Failed to create call: %v", err)
}
}
+2
View File
@@ -71,12 +71,14 @@ func main() {
cookieHeader := common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
bearer, err := wbstream.RefreshAccessToken(nil, cookieHeader, deviceID)
if err != nil {
common.EmitAuthErrorFor(err)
log.Fatalf("[auth] slide-v3 refresh: %v", err)
}
log.Printf("[auth] bearer refreshed (len=%d)", len(bearer))
requestedRoom := wbstream.ParseRoomID(*roomFlag)
roomID, roomToken, accessToken, serverURL, err := wbstream.AuthAsLoggedIn(nil, cookieHeader, bearer, requestedRoom, *displayName)
if err != nil {
common.EmitAuthErrorFor(err)
log.Fatalf("[auth] %v", err)
}
log.Printf("[auth] room=%s server=%s", roomID, serverURL)
+5 -5
View File
@@ -24,13 +24,13 @@ import (
"syscall"
"time"
joinerCommon "whitelist-bypass/relay/pion/headless-joiner-common"
"whitelist-bypass/relay/common"
"whitelist-bypass/relay/desktoptun"
"whitelist-bypass/relay/dion"
"whitelist-bypass/relay/pion"
joinerCommon "whitelist-bypass/relay/pion/headless-joiner-common"
"whitelist-bypass/relay/tunnel"
"whitelist-bypass/relay/wbstream"
"whitelist-bypass/relay/desktoptun"
)
type statusEmitter struct{}
@@ -175,9 +175,9 @@ func main() {
tunReady := make(chan struct{})
var tunOnce sync.Once
var (
pendingMu sync.Mutex
pending []string
tunStarted bool
pendingMu sync.Mutex
pending []string
tunStarted bool
)
bringUpTun := func() {
tunOnce.Do(func() {
+476
View File
@@ -0,0 +1,476 @@
package bitrix
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/google/uuid"
"whitelist-bypass/relay/common"
)
const (
slbBase = "https://slb.bitrix24.tech/v2/join"
signalSDK = "js"
signalVersion = "1.6.7"
signalProtocol = "8"
clientVersion = "1.0.0"
clientPlatform = "web"
callTypeInstant = 2
roomTypeSmall = 1
)
var (
reConferenceID = regexp.MustCompile(`conferenceId:\s*'([^']+)'`)
reChatID = regexp.MustCompile(`chatId:\s*'([^']+)'`)
reAlias = regexp.MustCompile(`alias:\s*'([^']+)'`)
reSessid = regexp.MustCompile(`bitrix_sessid["']?\s*[:=]\s*["']([a-f0-9]{8,})`)
reUserID = regexp.MustCompile(`"USER_ID"\s*:\s*"?(\d+)`)
)
type Client struct {
HTTP *http.Client
LogFn func(string, ...any)
portal string
sessid string
userAgent string
instanceID string
email string
password string
credsPath string
}
type JoinResult struct {
RoomData string `json:"roomData"`
RoomID string `json:"roomId"`
MediaServerURL string `json:"mediaServerUrl"`
}
type conferenceParams struct {
ConferenceID string
ChatID string
Alias string
}
type callInfo struct {
UUID string
ChatID string
CallToken string
UserToken string
Alias string
GuestLink string
}
type slbRequest struct {
UserToken string `json:"userToken"`
IsOneToOne bool `json:"isOneToOne"`
ClientVersion string `json:"clientVersion"`
ClientPlatform string `json:"clientPlatform"`
CallType int `json:"callType"`
RoomType int `json:"roomType"`
InstanceID string `json:"instanceId"`
CallToken string `json:"callToken"`
Provider string `json:"provider"`
IsVideo bool `json:"isVideo"`
CallUUID string `json:"callUuid"`
}
func NewClient(portal, userAgent string) (*Client, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &Client{
HTTP: &http.Client{Jar: jar},
LogFn: log.Printf,
portal: strings.TrimRight(portal, "/"),
userAgent: userAgent,
instanceID: uuid.New().String(),
}, nil
}
func SignalURL(res JoinResult) string {
q := url.Values{}
q.Set("auto_subscribe", "1")
q.Set("sdk", signalSDK)
q.Set("version", signalVersion)
q.Set("protocol", signalProtocol)
q.Set("roomData", res.RoomData)
q.Set("clientVersion", clientVersion)
q.Set("clientPlatform", clientPlatform)
return res.MediaServerURL + "?" + q.Encode()
}
func (c *Client) JoinAsGuest(alias, displayName string) (JoinResult, error) {
var res JoinResult
conf, err := c.fetchConference(alias)
if err != nil {
return res, err
}
userToken, err := c.registerGuest(conf, displayName)
if err != nil {
return res, err
}
info, err := c.tryJoinCall(conf.ChatID)
if err != nil {
return res, err
}
info.UserToken = userToken
return c.slbJoin(info, false)
}
func (c *Client) JoinAsHost(alias string) (JoinResult, error) {
var res JoinResult
conf, err := c.fetchConference(alias)
if err != nil {
return res, err
}
c.LogFn("[host] conference chatId=%s conferenceId=%s", conf.ChatID, conf.ConferenceID)
callToken, userToken, err := c.getCallToken(conf.ChatID)
if err != nil {
return res, err
}
info := callInfo{
UUID: uuid.New().String(),
ChatID: conf.ChatID,
CallToken: callToken,
UserToken: userToken,
}
c.LogFn("[host] creating media room callUUID=%s callToken=%dB userToken=%dB", info.UUID, len(info.CallToken), len(info.UserToken))
return c.slbJoin(info, true)
}
func (c *Client) CreateAndJoin() (JoinResult, string, error) {
var res JoinResult
info, err := c.createRoom()
if err != nil {
return res, "", err
}
guestLink := info.GuestLink
if guestLink == "" {
guestLink, err = c.getGuestLink(info.ChatID)
if err != nil {
return res, "", err
}
}
if info.CallToken == "" {
callToken, userToken, err := c.getCallToken(info.ChatID)
if err != nil {
return res, "", err
}
info.CallToken = callToken
if info.UserToken == "" {
info.UserToken = userToken
}
}
res, err = c.slbJoin(info, true)
if err != nil {
return res, "", err
}
return res, guestLink, nil
}
func (c *Client) resetJar() error {
jar, err := cookiejar.New(nil)
if err != nil {
return err
}
c.HTTP.Jar = jar
c.sessid = ""
return nil
}
func (c *Client) do(method, endpoint, contentType string, body io.Reader) ([]byte, int, error) {
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
return nil, 0, err
}
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Accept", "application/json, text/plain, */*")
if c.portal != "" {
req.Header.Set("Origin", c.portal)
req.Header.Set("Referer", c.portal+"/")
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
return data, resp.StatusCode, err
}
func (c *Client) restForm(action string, form url.Values) ([]byte, int, error) {
endpoint := c.portal + "/rest/" + action + ".json"
return c.do("POST", endpoint, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
}
func (c *Client) ajaxAction(action string, form url.Values) ([]byte, int, error) {
endpoint := c.portal + "/bitrix/services/main/ajax.php?action=" + action
if c.sessid != "" {
endpoint += "&sessid=" + url.QueryEscape(c.sessid)
form.Set("sessid", c.sessid)
}
return c.do("POST", endpoint, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
}
func (c *Client) fetchConference(alias string) (conferenceParams, error) {
var p conferenceParams
body, status, err := c.do("GET", c.portal+"/video/"+alias, "", nil)
if err != nil {
return p, err
}
if status != 200 {
return p, fmt.Errorf("fetch conference page: status %d", status)
}
page := string(body)
if m := reConferenceID.FindStringSubmatch(page); m != nil {
p.ConferenceID = m[1]
}
if m := reChatID.FindStringSubmatch(page); m != nil {
p.ChatID = m[1]
}
if m := reAlias.FindStringSubmatch(page); m != nil {
p.Alias = m[1]
} else {
p.Alias = alias
}
if m := reSessid.FindStringSubmatch(page); m != nil {
c.sessid = m[1]
}
if p.ConferenceID == "" || p.ChatID == "" {
return p, fmt.Errorf("conference params not found in page (conferenceId=%q chatId=%q)", p.ConferenceID, p.ChatID)
}
return p, nil
}
func (c *Client) registerGuest(p conferenceParams, displayName string) (userToken string, err error) {
form := url.Values{}
form.Set("call_auth_id", "guest")
form.Set("videoconf_id", p.ConferenceID)
form.Set("call_chat_id", p.ChatID)
form.Set("alias", p.Alias)
form.Set("user_hash", "")
if displayName != "" {
form.Set("name", displayName)
}
body, status, err := c.restForm("call.user.register", form)
if err != nil {
return "", err
}
var out struct {
Result struct {
UserToken string `json:"userToken"`
} `json:"result"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
if err := json.Unmarshal(body, &out); err != nil {
return "", fmt.Errorf("register guest: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Result.UserToken == "" {
return "", fmt.Errorf("register guest: no userToken (status %d, err %s %s)", status, out.Error, out.ErrorDescription)
}
return out.Result.UserToken, nil
}
func (c *Client) tryJoinCall(chatID string) (callInfo, error) {
var info callInfo
form := url.Values{}
form.Set("entityType", "chat")
form.Set("entityId", "chat"+chatID)
form.Set("provider", "Bitrix")
form.Set("callType", fmt.Sprintf("%d", callTypeInstant))
body, status, err := c.withRelogin(func() ([]byte, int, error) {
return c.ajaxAction("call.Call.tryJoinCall", form)
})
if err != nil {
return info, err
}
var out struct {
Status string `json:"status"`
Data struct {
Success bool `json:"success"`
Call struct {
UUID string `json:"UUID"`
ChatID json.Number `json:"CHAT_ID"`
} `json:"call"`
CallToken string `json:"callToken"`
} `json:"data"`
Errors []struct {
Message string `json:"message"`
Code string `json:"code"`
} `json:"errors"`
}
if err := json.Unmarshal(body, &out); err != nil {
return info, fmt.Errorf("tryJoinCall: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Status == "success" && !out.Data.Success {
return info, fmt.Errorf("tryJoinCall: no active call at chat%s, organizer not in the room", chatID)
}
if out.Status != "success" || out.Data.Call.UUID == "" {
return info, fmt.Errorf("tryJoinCall failed (status %d, %s, errors %+v, body %s)", status, out.Status, out.Errors, common.BodySnippet(body))
}
info.UUID = out.Data.Call.UUID
info.ChatID = out.Data.Call.ChatID.String()
info.CallToken = out.Data.CallToken
return info, nil
}
func (c *Client) slbJoin(info callInfo, mustCreate bool) (JoinResult, error) {
var res JoinResult
reqBody := slbRequest{
UserToken: info.UserToken,
IsOneToOne: false,
ClientVersion: clientVersion,
ClientPlatform: clientPlatform,
CallType: callTypeInstant,
RoomType: roomTypeSmall,
InstanceID: c.instanceID,
CallToken: info.CallToken,
Provider: "Bitrix",
IsVideo: true,
CallUUID: info.UUID,
}
payload, _ := json.Marshal(reqBody)
endpoint := slbBase + "?mustCreate=" + strconv.FormatBool(mustCreate)
body, status, err := c.do("POST", endpoint, "text/plain;charset=UTF-8", strings.NewReader(string(payload)))
if err != nil {
return res, err
}
var out struct {
Result JoinResult `json:"result"`
Error string `json:"error"`
}
if err := json.Unmarshal(body, &out); err != nil {
return res, fmt.Errorf("slb join: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Result.MediaServerURL == "" || out.Result.RoomData == "" {
return res, fmt.Errorf("slb join: missing roomData/mediaServerUrl (status %d, err %s)", status, out.Error)
}
return out.Result, nil
}
func (c *Client) currentUserID() (string, error) {
body, status, err := c.do("GET", c.portal+"/online/", "", nil)
if err != nil {
return "", err
}
if m := reUserID.FindSubmatch(body); m != nil && string(m[1]) != "0" {
return string(m[1]), nil
}
return "", fmt.Errorf("current user id not found (status %d)", status)
}
func (c *Client) createRoom() (callInfo, error) {
var info callInfo
uid, err := c.currentUserID()
if err != nil {
return info, fmt.Errorf("createRoom: %w", err)
}
form := url.Values{}
form.Set("fields[entityType]", "VIDEOCONF")
form.Set("fields[title]", "")
form.Set("fields[memberEntities][0][0]", "user")
form.Set("fields[memberEntities][0][1]", uid)
form.Set("fields[ownerId]", uid)
form.Set("fields[description]", "")
form.Set("fields[manageUsersAdd]", "member")
form.Set("fields[manageUsersDelete]", "manager")
form.Set("fields[manageUi]", "member")
form.Set("fields[manageMessages]", "member")
form.Set("fields[conferencePassword]", "")
body, status, err := c.withRelogin(func() ([]byte, int, error) {
return c.ajaxAction("im.v2.Chat.add", form)
})
if err != nil {
return info, err
}
var out struct {
Status string `json:"status"`
Data struct {
ChatID json.Number `json:"chatId"`
Alias string `json:"alias"`
Link string `json:"link"`
} `json:"data"`
Errors []struct {
Code json.Number `json:"code"`
Message string `json:"message"`
} `json:"errors"`
}
if err := json.Unmarshal(body, &out); err != nil {
return info, fmt.Errorf("createRoom: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
info.ChatID = out.Data.ChatID.String()
info.Alias = out.Data.Alias
info.GuestLink = out.Data.Link
if info.ChatID == "" {
errMsg := ""
if len(out.Errors) > 0 {
errMsg = out.Errors[0].Code.String() + " " + out.Errors[0].Message
}
return info, fmt.Errorf("createRoom: no chatId (status %d, status=%q err=%q, body %s)", status, out.Status, errMsg, common.BodySnippet(body))
}
c.LogFn("[create] videoconf chatId=%s alias=%s", info.ChatID, info.Alias)
return info, nil
}
func (c *Client) getGuestLink(chatID string) (string, error) {
form := url.Values{}
form.Set("chatId", chatID)
body, status, err := c.withRelogin(func() ([]byte, int, error) {
return c.ajaxAction("call.Call.getGuestLink", form)
})
if err != nil {
return "", err
}
var out struct {
Status string `json:"status"`
Data struct {
GuestLink string `json:"guestLink"`
} `json:"data"`
}
if err := json.Unmarshal(body, &out); err != nil {
return "", fmt.Errorf("getGuestLink: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Data.GuestLink == "" {
return "", fmt.Errorf("getGuestLink: empty (status %d)", status)
}
return out.Data.GuestLink, nil
}
func (c *Client) getCallToken(chatID string) (callToken, userToken string, err error) {
form := url.Values{}
form.Set("chatId", chatID)
body, status, err := c.withRelogin(func() ([]byte, int, error) {
return c.ajaxAction("call.Call.getCallToken", form)
})
if err != nil {
return "", "", err
}
var out struct {
Status string `json:"status"`
Data struct {
CallToken string `json:"callToken"`
UserToken string `json:"userToken"`
} `json:"data"`
}
if err := json.Unmarshal(body, &out); err != nil {
return "", "", fmt.Errorf("getCallToken: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Data.CallToken == "" {
return "", "", fmt.Errorf("getCallToken: empty (status %d, body %s)", status, common.BodySnippet(body))
}
return out.Data.CallToken, out.Data.UserToken, nil
}
+250
View File
@@ -0,0 +1,250 @@
package bitrix
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"whitelist-bypass/relay/common"
)
const authNetBase = "https://auth2.bitrix24.net"
var (
reFlowCfg = regexp.MustCompile(`b24network\.security\.flowtoken"[^>]*>(\{[^<]*\})</script>`)
reJunk = regexp.MustCompile(`[!#$%@~]`)
reJSRedirect = regexp.MustCompile(`window\.location\.href\s*=\s*['"]([^'"]+)['"]`)
)
type Credentials struct {
Email string `json:"email"`
Password string `json:"password"`
Portal string `json:"portal"`
Cookies []CookieEntry `json:"cookies,omitempty"`
}
func LoadCredentials(path string) (Credentials, error) {
var c Credentials
data, err := os.ReadFile(path)
if err != nil {
return c, err
}
if err := json.Unmarshal(data, &c); err != nil {
return c, fmt.Errorf("parse credentials %s: %w", path, err)
}
c.Email = strings.TrimSpace(c.Email)
c.Portal = strings.TrimRight(strings.TrimSpace(c.Portal), "/")
return c, nil
}
func (c *Client) loginWithPassword(email, password string) error {
if email == "" || password == "" {
return fmt.Errorf("login: no email/password")
}
if err := c.resetJar(); err != nil {
return err
}
flowToken, sessid, currentURI, err := c.bootstrapLogin()
if err != nil {
return err
}
c.LogFn("[auth] bootstrap: flowToken=%dB sessid=%v authURL=%v", len(flowToken), sessid != "", strings.Contains(currentURI, "auth2.bitrix24.net"))
if err := c.authCheckLogin(flowToken, email, sessid, currentURI); err != nil {
return err
}
c.LogFn("[auth] checkLogin OK")
if err := c.authCheck(flowToken, email, password, sessid); err != nil {
return err
}
c.LogFn("[auth] check OK")
c.email = email
c.password = password
if err := c.completeOAuth(); err != nil {
return err
}
if c.credsPath != "" {
if err := c.saveSession(); err != nil {
return fmt.Errorf("login ok but save session failed: %w", err)
}
}
return nil
}
func (c *Client) bootstrapLogin() (flowToken, sessid, currentURI string, err error) {
req, err := http.NewRequest("GET", c.portal+"/", nil)
if err != nil {
return "", "", "", err
}
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
req.Header.Set("Accept-Language", "ru,en;q=0.9")
req.Header.Set("Upgrade-Insecure-Requests", "1")
resp, err := c.HTTP.Do(req)
if err != nil {
return "", "", "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
page := string(body)
currentURI = resp.Request.URL.String()
if !strings.Contains(currentURI, "auth2.bitrix24.net") {
return "", "", "", fmt.Errorf("portal did not redirect to auth2 (landed on %s)", currentURI)
}
flowToken = computeFlowToken(page)
if m := reSessid.FindStringSubmatch(page); m != nil {
sessid = m[1]
}
return flowToken, sessid, currentURI, nil
}
func computeFlowToken(page string) string {
m := reFlowCfg.FindStringSubmatch(page)
if m == nil {
return ""
}
var cfg struct {
FTV string `json:"ftv"`
}
if err := json.Unmarshal([]byte(m[1]), &cfg); err != nil {
return ""
}
return reJunk.ReplaceAllString(cfg.FTV, "")
}
func (c *Client) authCheckLogin(flowToken, login, sessid, currentURI string) error {
form := url.Values{}
form.Set("flow-token-unique-id", flowToken)
form.Set("login", login)
form.Set("currentUri", currentURI)
form.Set("checkSocserv", "Y")
body, status, err := c.authDo("b24network.authorize.checkLogin", form, sessid)
if err != nil {
return err
}
var out struct {
Status string `json:"status"`
Data []struct {
HasAccess bool `json:"HAS_ACCESS"`
Captcha interface{} `json:"CAPTCHA"`
} `json:"data"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
if err := json.Unmarshal(body, &out); err != nil {
return fmt.Errorf("checkLogin: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Status != "success" || len(out.Data) == 0 {
return fmt.Errorf("login rejected: checkLogin (status %d, errors %+v, body %s)", status, out.Errors, common.BodySnippet(body))
}
if out.Data[0].Captcha != nil {
return fmt.Errorf("login rejected: captcha required at login step")
}
if !out.Data[0].HasAccess {
return fmt.Errorf("login rejected: account has no access")
}
return nil
}
func (c *Client) authCheck(flowToken, login, password, sessid string) error {
form := url.Values{}
form.Set("flow-token-unique-id", flowToken)
form.Set("login", login)
form.Set("password", password)
form.Set("remember", "Y")
body, status, err := c.authDo("b24network.authorize.check", form, sessid)
if err != nil {
return err
}
var out struct {
Status string `json:"status"`
Errors []struct {
Message string `json:"message"`
Code string `json:"code"`
} `json:"errors"`
}
if err := json.Unmarshal(body, &out); err != nil {
return fmt.Errorf("check: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Status != "success" || len(out.Errors) > 0 {
return fmt.Errorf("login rejected: password check (status %d, errors %+v, body %s)", status, out.Errors, common.BodySnippet(body))
}
return nil
}
func (c *Client) authDo(action string, form url.Values, sessid string) ([]byte, int, error) {
endpoint := authNetBase + "/bitrix/services/main/ajax.php?action=" + action
req, err := http.NewRequest("POST", endpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, 0, err
}
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("Origin", authNetBase)
req.Header.Set("Referer", authNetBase+"/authorization/")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
if sessid != "" {
req.Header.Set("X-Bitrix-Csrf-Token", sessid)
}
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
return body, resp.StatusCode, err
}
func (c *Client) getPage(target string) (body, final string, err error) {
req, err := http.NewRequest("GET", target, nil)
if err != nil {
return "", "", err
}
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
req.Header.Set("Accept-Language", "ru,en;q=0.9")
resp, err := c.HTTP.Do(req)
if err != nil {
return "", "", err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
return string(raw), resp.Request.URL.String(), nil
}
func (c *Client) completeOAuth() error {
target := c.portal + "/"
for hop := 0; hop < 8; hop++ {
body, final, err := c.getPage(target)
if err != nil {
return err
}
c.LogFn("[auth] oauth hop %d: final=%s len=%d", hop, final, len(body))
if next := reJSRedirect.FindStringSubmatch(body); next != nil {
target = next[1]
continue
}
if strings.HasPrefix(final, c.portal) {
if m := reSessid.FindStringSubmatch(body); m != nil {
c.sessid = m[1]
return nil
}
}
target = c.portal + "/"
body, _, err = c.getPage(target)
if err != nil {
return err
}
if m := reSessid.FindStringSubmatch(body); m != nil {
c.sessid = m[1]
}
return nil
}
return fmt.Errorf("oauth handoff did not converge")
}
+314
View File
@@ -0,0 +1,314 @@
package bitrix
import (
"fmt"
"log"
"sync"
"time"
"github.com/pion/rtp/codecs"
"github.com/pion/webrtc/v4"
"whitelist-bypass/relay/common"
"whitelist-bypass/relay/livekit"
"whitelist-bypass/relay/tunnel"
)
const (
TunnelModeAuto = ""
TunnelModeVideo = "video"
TunnelModeDC = "dc"
)
type MediaParams struct {
Signal *Signal
Alias string
Mode string
FPS int
Batch int
Reliable bool
LogFn func(string, ...any)
}
type MediaSession struct {
p MediaParams
obf *tunnel.TunnelObfuscator
sendTrack *webrtc.TrackLocalStaticSample
vp8tun *tunnel.VP8DataTunnel
mu sync.Mutex
subReliableDC *webrtc.DataChannel
pubDCHooked bool
dcStarted bool
tunFired bool
configAcked chan struct{}
configAckedOnce sync.Once
stopCh chan struct{}
OnConnected func(tunnel.DataTunnel)
}
func NewMediaSession(p MediaParams) (*MediaSession, error) {
if p.LogFn == nil {
p.LogFn = log.Printf
}
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(p.Alias))
if err != nil {
return nil, err
}
track, err := webrtc.NewTrackLocalStaticSample(
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8, ClockRate: 90000},
"tunnel", fmt.Sprintf("bitrix-tunnel-%08x", obf.LocalEpoch()))
if err != nil {
return nil, err
}
s := &MediaSession{
p: p,
obf: obf,
sendTrack: track,
vp8tun: tunnel.NewVP8DataTunnel(track, obf, p.LogFn),
configAcked: make(chan struct{}),
stopCh: make(chan struct{}),
}
p.Signal.SetOnTrack(func(remote *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {
if remote.Codec().MimeType == webrtc.MimeTypeVP8 {
go s.readVP8Track(remote)
} else {
go tunnel.DrainTrack(remote)
}
})
p.Signal.SetOnDataChannel(func(dc *webrtc.DataChannel) {
if dc.Label() != "_reliable" {
return
}
s.mu.Lock()
s.subReliableDC = dc
s.mu.Unlock()
dc.OnOpen(func() {
s.p.LogFn("[bx] sub _reliable DC open")
s.maybeStartDCTunnel()
})
})
return s, nil
}
func (s *MediaSession) MarkConfigAcked() {
s.configAckedOnce.Do(func() { close(s.configAcked) })
}
func (s *MediaSession) Stop() {
select {
case <-s.stopCh:
default:
close(s.stopCh)
}
s.vp8tun.Stop()
}
func (s *MediaSession) Start() error {
sender, err := s.p.Signal.PublishVP8(s.sendTrack, "tunnel")
if err != nil {
return err
}
go tunnel.DrainSenderRTCP(sender)
s.vp8tun.Start(s.p.FPS, s.p.Batch)
s.p.LogFn("[bx] vp8 tunnel started fps=%d batch=%d", s.p.FPS, s.p.Batch)
s.hookPubDC()
s.startVP8Role()
return nil
}
func (s *MediaSession) hookPubDC() {
dc := s.p.Signal.PubReliableDC()
if dc == nil {
return
}
s.mu.Lock()
if s.pubDCHooked {
s.mu.Unlock()
return
}
s.pubDCHooked = true
s.mu.Unlock()
dc.OnOpen(func() {
s.p.LogFn("[bx] pub _reliable DC open")
s.maybeStartDCTunnel()
})
if dc.ReadyState() == webrtc.DataChannelStateOpen {
s.maybeStartDCTunnel()
}
}
func (s *MediaSession) startVP8Role() {
var active tunnel.DataTunnel = s.vp8tun
if s.p.Mode == TunnelModeVideo && s.p.Reliable {
active = s.wrapReliable(s.vp8tun)
}
switch s.p.Mode {
case TunnelModeVideo:
go s.configPingPong(active)
s.fireOnConnected(active)
case TunnelModeAuto:
s.vp8tun.SetOnData(func(payload []byte) { s.activate(s.vp8tun, payload) })
}
}
func (s *MediaSession) maybeStartDCTunnel() {
if s.p.Mode == TunnelModeVideo {
return
}
s.mu.Lock()
subDC := s.subReliableDC
s.mu.Unlock()
pubDC := s.p.Signal.PubReliableDC()
if pubDC == nil || subDC == nil {
return
}
if pubDC.ReadyState() != webrtc.DataChannelStateOpen || subDC.ReadyState() != webrtc.DataChannelStateOpen {
return
}
s.mu.Lock()
if s.dcStarted {
s.mu.Unlock()
return
}
s.dcStarted = true
s.mu.Unlock()
subRaw, err := subDC.Detach()
if err != nil {
s.p.LogFn("[bx] detach sub _reliable: %v", err)
return
}
pubRaw, err := pubDC.Detach()
if err != nil {
s.p.LogFn("[bx] detach pub _reliable: %v", err)
return
}
readWrapped := livekit.NewDataPacketWrapper(subRaw, livekit.DataPacketKindReliable)
writeWrapped := livekit.NewDataPacketWrapper(pubRaw, livekit.DataPacketKindReliable)
dctun := tunnel.NewChunkedDCTunnelFromRaw(readWrapped, writeWrapped, s.obf, common.DCBufSize, s.p.LogFn)
s.p.LogFn("[bx] dc tunnel ready (pub+sub _reliable)")
switch s.p.Mode {
case TunnelModeDC:
s.fireOnConnected(dctun)
case TunnelModeAuto:
dctun.SetOnData(func(payload []byte) { s.activate(dctun, payload) })
}
}
func (s *MediaSession) configPingPong(tun tunnel.DataTunnel) {
tun.SendData(tunnel.EncodeVP8Config(s.vp8tun.FPS(), s.vp8tun.Batch(), 1))
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
select {
case <-s.configAcked:
return
case <-s.stopCh:
return
case <-ticker.C:
s.p.LogFn("[bx] resending vp8 config (no ack yet)")
tun.SendData(tunnel.EncodeVP8Config(s.vp8tun.FPS(), s.vp8tun.Batch(), 1))
}
}
}
func (s *MediaSession) fireOnConnected(tun tunnel.DataTunnel) {
s.mu.Lock()
if s.tunFired {
s.mu.Unlock()
return
}
s.tunFired = true
s.mu.Unlock()
if s.OnConnected != nil {
s.OnConnected(tun)
}
}
func (s *MediaSession) activate(tun tunnel.DataTunnel, payload []byte) {
s.mu.Lock()
if s.tunFired {
s.mu.Unlock()
return
}
s.tunFired = true
s.mu.Unlock()
var delivered tunnel.DataTunnel = tun
useKCP := false
if v, ok := tun.(*tunnel.VP8DataTunnel); ok && !tunnel.LooksLikeRelayFrame(payload) {
delivered = s.wrapReliable(v)
useKCP = true
}
s.p.LogFn("[bx] auto-detected active tunnel: %T", delivered)
if s.OnConnected != nil {
s.OnConnected(delivered)
}
switch v := tun.(type) {
case *tunnel.DCTunnel:
if fwd := v.OnData(); fwd != nil {
fwd(payload)
}
case *tunnel.VP8DataTunnel:
if useKCP {
if k, ok := delivered.(*tunnel.MultiTrackKCPTunnel); ok {
k.InjectSegment(payload)
}
} else if v.OnData != nil {
v.OnData(payload)
}
}
}
func (s *MediaSession) wrapReliable(vp8 *tunnel.VP8DataTunnel) tunnel.DataTunnel {
mt := tunnel.NewMultiTrackTunnel([]*tunnel.VP8DataTunnel{vp8})
wrapped := tunnel.NewMultiTrackKCPTunnel(mt, s.p.LogFn)
s.p.LogFn("[bx] per-track kcp reliability active over video tunnel")
return wrapped
}
func (s *MediaSession) readVP8Track(track *webrtc.TrackRemote) {
var vp8Pkt codecs.VP8Packet
var frameBuf []byte
var lastSeq uint16
var haveLastSeq bool
frameValid := false
for {
pkt, _, err := track.ReadRTP()
if err != nil {
return
}
if pkt == nil {
continue
}
if haveLastSeq && pkt.SequenceNumber != lastSeq+1 {
frameValid = false
frameBuf = frameBuf[:0]
}
lastSeq = pkt.SequenceNumber
haveLastSeq = true
vp8Payload, err := vp8Pkt.Unmarshal(pkt.Payload)
if err != nil {
frameValid = false
frameBuf = frameBuf[:0]
continue
}
if vp8Pkt.S == 1 {
frameBuf = frameBuf[:0]
frameValid = true
}
if !frameValid {
continue
}
frameBuf = append(frameBuf, vp8Payload...)
if !pkt.Marker {
continue
}
s.vp8tun.HandleFrame(frameBuf)
frameBuf = frameBuf[:0]
frameValid = false
}
}
+151
View File
@@ -0,0 +1,151 @@
package bitrix
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strings"
)
type CookieEntry struct {
Name string `json:"name"`
Value string `json:"value"`
Host string `json:"host"`
}
func (c *Client) LoadSession(path string) error {
creds, err := LoadCredentials(path)
if err != nil {
return err
}
c.credsPath = path
c.email = creds.Email
c.password = creds.Password
if creds.Portal != "" {
c.portal = strings.TrimRight(creds.Portal, "/")
}
byHost := map[string][]*http.Cookie{}
for _, e := range creds.Cookies {
host := e.Host
if host == "" {
host = c.portal
}
byHost[host] = append(byHost[host], &http.Cookie{Name: e.Name, Value: e.Value, Path: "/"})
}
for host, cookies := range byHost {
u, err := url.Parse(host)
if err != nil {
continue
}
c.HTTP.Jar.SetCookies(u, cookies)
}
return nil
}
func (c *Client) EnsureLogin() error {
if c.checkSession() {
c.LogFn("[auth] session valid, reusing saved cookies")
return nil
}
if c.email == "" || c.password == "" {
return fmt.Errorf("ensureLogin: no email/password")
}
c.LogFn("[auth] session dead, re-logging in")
return c.loginWithPassword(c.email, c.password)
}
func (c *Client) checkSession() bool {
body, final, err := c.getPage(c.portal + "/")
if err != nil {
return false
}
if strings.Contains(final, "auth2.bitrix24.net") {
return false
}
if m := reSessid.FindStringSubmatch(body); m != nil {
c.sessid = m[1]
return true
}
return false
}
func (c *Client) saveSession() error {
if c.credsPath == "" {
return fmt.Errorf("no creds path")
}
creds := Credentials{
Email: c.email,
Password: c.password,
Portal: c.portal,
Cookies: c.gatherCookies(),
}
raw, err := json.MarshalIndent(creds, "", " ")
if err != nil {
return err
}
tmp := c.credsPath + ".tmp"
if err := os.WriteFile(tmp, append(raw, '\n'), 0o600); err != nil {
return err
}
if err := os.Rename(tmp, c.credsPath); err != nil {
os.Remove(tmp)
return err
}
return nil
}
func (c *Client) gatherCookies() []CookieEntry {
seen := map[string]struct{}{}
var out []CookieEntry
for _, host := range c.cookieHosts() {
u, err := url.Parse(host)
if err != nil {
continue
}
for _, ck := range c.HTTP.Jar.Cookies(u) {
key := host + "|" + ck.Name
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
out = append(out, CookieEntry{Name: ck.Name, Value: ck.Value, Host: host})
}
}
return out
}
func (c *Client) cookieHosts() []string {
return []string{c.portal, authNetBase}
}
func (c *Client) withRelogin(do func() ([]byte, int, error)) ([]byte, int, error) {
body, status, err := do()
if err != nil || !looksUnauth(body, status) {
return body, status, err
}
if c.email == "" || c.password == "" {
return body, status, err
}
c.LogFn("[auth] unauthenticated response (status %d), re-logging in and retrying", status)
if lerr := c.loginWithPassword(c.email, c.password); lerr != nil {
return body, status, fmt.Errorf("relogin: %w", lerr)
}
return do()
}
func looksUnauth(body []byte, status int) bool {
if status == 401 || status == 403 {
return true
}
s := strings.TrimSpace(string(body))
if s == "" || s[0] != '{' {
return true
}
low := strings.ToLower(s)
return strings.Contains(low, "not_authorized") ||
strings.Contains(low, "unauthorized") ||
strings.Contains(low, "invalid_token") ||
strings.Contains(low, "user_not_authorized")
}
+202
View File
@@ -0,0 +1,202 @@
package bitrix
import (
"context"
"fmt"
"net"
"sync"
"time"
"github.com/pion/webrtc/v4"
"whitelist-bypass/relay/livekit"
)
type SignalConfig struct {
SignalURL string
Origin string
UserAgent string
LogFn func(string, ...any)
SettingEngine *webrtc.SettingEngine
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
OnConnected func()
OnDataChannel func(*webrtc.DataChannel)
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
}
type Signal struct {
lk *livekit.Client
logFn func(string, ...any)
mu sync.Mutex
onTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
onDC func(*webrtc.DataChannel)
pendingTracks []remoteTrack
pendingDCs []*webrtc.DataChannel
pubReliable *webrtc.DataChannel
dataChannelsUp bool
}
type remoteTrack struct {
track *webrtc.TrackRemote
receiver *webrtc.RTPReceiver
}
func ConnectSignal(cfg SignalConfig) (*Signal, error) {
logFn := cfg.LogFn
if logFn == nil {
logFn = func(string, ...any) {}
}
s := &Signal{
logFn: logFn,
onTrack: cfg.OnTrack,
onDC: cfg.OnDataChannel,
}
lk, err := livekit.NewClient(livekit.Config{
ServerURL: cfg.SignalURL,
Origin: cfg.Origin,
UserAgent: cfg.UserAgent,
Codec: livekit.JSONCodec{},
LogFn: logFn,
SettingEngine: cfg.SettingEngine,
NetDialContext: cfg.NetDialContext,
})
if err != nil {
return nil, err
}
s.lk = lk
s.lk.OnTrack = s.dispatchTrack
s.lk.OnDataChannel = s.dispatchDataChannel
s.lk.OnSubConnected = cfg.OnConnected
if err := s.lk.Connect(); err != nil {
return nil, err
}
go s.lk.PingLoop()
return s, nil
}
func (s *Signal) Run() error { return s.lk.ReadLoop() }
func (s *Signal) Close() { s.lk.Close() }
func (s *Signal) SetOnTrack(fn func(*webrtc.TrackRemote, *webrtc.RTPReceiver)) {
s.mu.Lock()
s.onTrack = fn
pending := s.pendingTracks
s.pendingTracks = nil
s.mu.Unlock()
if fn == nil {
return
}
for _, t := range pending {
fn(t.track, t.receiver)
}
}
func (s *Signal) SetOnDataChannel(fn func(*webrtc.DataChannel)) {
s.mu.Lock()
s.onDC = fn
pending := s.pendingDCs
s.pendingDCs = nil
s.mu.Unlock()
if fn == nil {
return
}
for _, dc := range pending {
fn(dc)
}
}
func (s *Signal) PubReliableDC() *webrtc.DataChannel {
s.mu.Lock()
defer s.mu.Unlock()
return s.pubReliable
}
func (s *Signal) PublishVP8(track *webrtc.TrackLocalStaticSample, name string) (*webrtc.RTPSender, error) {
select {
case <-s.lk.Joined():
case <-time.After(30 * time.Second):
return nil, fmt.Errorf("join did not arrive")
}
pubPC := s.lk.PubPC()
if pubPC == nil {
return nil, fmt.Errorf("pub pc not ready")
}
if err := s.ensureDataChannels(pubPC); err != nil {
return nil, err
}
transceiver, err := pubPC.AddTransceiverFromTrack(track, webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionSendonly,
})
if err != nil {
return nil, err
}
if err := s.lk.SendAddTrack(track.ID(), name, livekit.TrackTypeVideo, livekit.TrackSourceCamera, 1280, 720); err != nil {
return nil, err
}
s.logFn("[bx] published vp8 track cid=%s name=%s", track.ID(), name)
offer, err := pubPC.CreateOffer(nil)
if err != nil {
return nil, err
}
if err := pubPC.SetLocalDescription(offer); err != nil {
return nil, err
}
if err := s.lk.SendOffer(offer.SDP); err != nil {
return nil, err
}
return transceiver.Sender(), nil
}
func (s *Signal) dispatchTrack(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
s.mu.Lock()
fn := s.onTrack
if fn == nil {
s.pendingTracks = append(s.pendingTracks, remoteTrack{track: track, receiver: receiver})
}
s.mu.Unlock()
if fn != nil {
fn(track, receiver)
}
}
func (s *Signal) dispatchDataChannel(dc *webrtc.DataChannel) {
s.mu.Lock()
fn := s.onDC
if fn == nil {
s.pendingDCs = append(s.pendingDCs, dc)
}
s.mu.Unlock()
if fn != nil {
fn(dc)
}
}
func (s *Signal) ensureDataChannels(pubPC *webrtc.PeerConnection) error {
s.mu.Lock()
if s.dataChannelsUp {
s.mu.Unlock()
return nil
}
s.dataChannelsUp = true
s.mu.Unlock()
ordered := true
reliable, err := pubPC.CreateDataChannel("_reliable", &webrtc.DataChannelInit{Ordered: &ordered})
if err != nil {
return fmt.Errorf("create _reliable: %w", err)
}
unordered := false
var zero uint16
lossy, err := pubPC.CreateDataChannel("_lossy", &webrtc.DataChannelInit{Ordered: &unordered, MaxRetransmits: &zero})
if err != nil {
return fmt.Errorf("create _lossy: %w", err)
}
reliable.OnOpen(func() { s.logFn("[bx] pub dc _reliable open") })
lossy.OnOpen(func() { s.logFn("[bx] pub dc _lossy open") })
s.mu.Lock()
s.pubReliable = reliable
s.mu.Unlock()
return nil
}
+170
View File
@@ -0,0 +1,170 @@
package common
import (
"fmt"
"math/rand/v2"
)
type DeviceProfile struct {
UserAgent string
Platform string
BrowserType string
BrowserVersion string
DeviceBrand string
DeviceModel string
DeviceType string
OS string
OSVersion string
ScreenWidth int
ScreenHeight int
}
type deviceTemplate struct {
os string
osVersionPool []string
deviceBrandPool []string
deviceModelPool []string
browsers []browserTemplate
}
type browserTemplate struct {
browserType string
versionPool []string
userAgentFn func(osVersion, browserVersion string) string
}
var commonScreens = [][2]int{
{1280, 720}, {1366, 768}, {1440, 900}, {1536, 864},
{1600, 900}, {1680, 1050}, {1728, 1117}, {1920, 1080},
{2048, 1152}, {2560, 1440}, {2880, 1800}, {3840, 2160},
}
var deviceTemplates = []deviceTemplate{
{
os: "Mac OS",
osVersionPool: []string{"10.15.7", "11.7.10", "12.7.6", "13.6.9", "14.6.1", "15.1.0"},
deviceBrandPool: []string{"Apple"},
deviceModelPool: []string{"Macintosh"},
browsers: []browserTemplate{
{
browserType: "Chrome",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0", "149.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36",
macOSVersionForUA(osVersion), browserVersion)
},
},
{
browserType: "Safari",
versionPool: []string{"17.6", "18.0", "18.1", "18.2"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X %s) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/%s Safari/605.1.15",
macOSVersionForUA(osVersion), browserVersion)
},
},
{
browserType: "Firefox",
versionPool: []string{"128.0", "131.0", "133.0", "135.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X %s; rv:%s) Gecko/20100101 Firefox/%s",
macOSVersionForUA(osVersion), browserVersion, browserVersion)
},
},
},
},
{
os: "Windows",
osVersionPool: []string{"10", "11"},
deviceBrandPool: []string{"Dell", "Lenovo", "HP", "Asus", "Acer", "MSI"},
deviceModelPool: []string{"PC"},
browsers: []browserTemplate{
{
browserType: "Chrome",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0", "149.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36",
browserVersion)
},
},
{
browserType: "Edge",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 Edg/%s",
browserVersion, browserVersion)
},
},
{
browserType: "Firefox",
versionPool: []string{"128.0", "131.0", "133.0", "135.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:%s) Gecko/20100101 Firefox/%s",
browserVersion, browserVersion)
},
},
},
},
{
os: "Linux",
osVersionPool: []string{"x86_64", "x86_64 GNU"},
deviceBrandPool: []string{"Dell", "Lenovo", "HP", "System76", "Framework"},
deviceModelPool: []string{"PC"},
browsers: []browserTemplate{
{
browserType: "Chrome",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0", "149.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36",
browserVersion)
},
},
{
browserType: "Firefox",
versionPool: []string{"128.0", "131.0", "133.0", "135.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (X11; Linux x86_64; rv:%s) Gecko/20100101 Firefox/%s",
browserVersion, browserVersion)
},
},
},
},
}
func macOSVersionForUA(osVersion string) string {
switch osVersion {
case "10.15.7":
return "10_15_7"
case "11.7.10":
return "10_15_7"
case "12.7.6":
return "10_15_7"
case "13.6.9":
return "10_15_7"
case "14.6.1":
return "10_15_7"
case "15.1.0":
return "10_15_7"
}
return "10_15_7"
}
func RandomDeviceProfile() DeviceProfile {
tmpl := deviceTemplates[rand.IntN(len(deviceTemplates))]
browser := tmpl.browsers[rand.IntN(len(tmpl.browsers))]
osVersion := tmpl.osVersionPool[rand.IntN(len(tmpl.osVersionPool))]
browserVersion := browser.versionPool[rand.IntN(len(browser.versionPool))]
screen := commonScreens[rand.IntN(len(commonScreens))]
return DeviceProfile{
UserAgent: browser.userAgentFn(osVersion, browserVersion),
Platform: "web",
BrowserType: browser.browserType,
BrowserVersion: browserVersion,
DeviceBrand: tmpl.deviceBrandPool[rand.IntN(len(tmpl.deviceBrandPool))],
DeviceModel: tmpl.deviceModelPool[rand.IntN(len(tmpl.deviceModelPool))],
DeviceType: "pc",
OS: tmpl.os,
OSVersion: osVersion,
ScreenWidth: screen[0],
ScreenHeight: screen[1],
}
}
+9
View File
@@ -11,6 +11,15 @@ import (
const UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"
const bodySnippetLimit = 300
func BodySnippet(body []byte) string {
if len(body) > bodySnippetLimit {
return string(body[:bodySnippetLimit]) + "..."
}
return string(body)
}
func LoadCookies(path string) string {
data, err := os.ReadFile(path)
if err != nil {
+46 -7
View File
@@ -1,14 +1,22 @@
package common
import "fmt"
import (
"fmt"
"strings"
)
const (
StatusReady = "READY"
StatusConnecting = "CONNECTING"
StatusReconnecting = "RECONNECTING"
StatusTunnelConnected = "TUNNEL_CONNECTED"
StatusTunnelLost = "TUNNEL_LOST"
StatusError = "ERROR"
StatusReady = "READY"
StatusConnecting = "CONNECTING"
StatusReconnecting = "RECONNECTING"
StatusTunnelConnected = "TUNNEL_CONNECTED"
StatusTunnelLost = "TUNNEL_LOST"
StatusError = "ERROR"
)
const (
AuthErrorInvalidCredentials = "INVALID_CREDENTIALS"
AuthErrorSessionExpired = "SESSION_EXPIRED"
)
func EmitStatus(status string) {
@@ -18,3 +26,34 @@ func EmitStatus(status string) {
func EmitStatusError(msg string) {
fmt.Printf("STATUS:%s:%s\n", StatusError, msg)
}
func EmitAuthError(kind string) {
fmt.Printf("STATUS:AUTH_ERROR:%s\n", kind)
}
func looksLikeInvalidCreds(msg string) bool {
return strings.Contains(msg, `"code":1086`) ||
strings.Contains(msg, "Invalid credentials") ||
strings.Contains(msg, "login rejected")
}
func looksLikeSessionExpired(msg string) bool {
return strings.Contains(msg, "status 401") ||
strings.Contains(msg, "UnauthorizedError") ||
strings.Contains(msg, `"error":"unauthorized`) ||
strings.Contains(msg, "empty access_token") ||
strings.Contains(msg, "empty VK token")
}
func EmitAuthErrorFor(err error) {
if err == nil {
return
}
msg := err.Error()
switch {
case looksLikeInvalidCreds(msg):
EmitAuthError(AuthErrorInvalidCredentials)
case looksLikeSessionExpired(msg):
EmitAuthError(AuthErrorSessionExpired)
}
}
+4 -4
View File
@@ -25,10 +25,10 @@ type Config struct {
type Tunnel struct{}
func New(_ Config) (*Tunnel, error) { return nil, errUnsupported }
func (*Tunnel) Start() error { return errUnsupported }
func (*Tunnel) Stop() {}
func (*Tunnel) AddBypassIP(_ net.IP) error { return errUnsupported }
func New(_ Config) (*Tunnel, error) { return nil, errUnsupported }
func (*Tunnel) Start() error { return errUnsupported }
func (*Tunnel) Stop() {}
func (*Tunnel) AddBypassIP(_ net.IP) error { return errUnsupported }
func (*Tunnel) AddBypassHost(_ string) ([]net.IP, error) {
return nil, errUnsupported
}
+4 -3
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/google/uuid"
"whitelist-bypass/relay/common"
)
var ErrSessionExpired = errors.New("dion: session expired, re-login required")
@@ -114,7 +115,7 @@ type WSSConnectResponse struct {
type Session struct {
HTTPClient *http.Client
Device DeviceProfile
Device common.DeviceProfile
AccessToken string
AccessTokenExp time.Time
UserID string
@@ -132,7 +133,7 @@ func (s *Session) setBaseHeaders(req *http.Request, accessToken string) {
req.Header.Set("Accept", "*/*")
req.Header.Set("Accept-Language", "en")
req.Header.Set("X-Request-Id", uuid.New().String())
for name, value := range s.Device.Headers() {
for name, value := range deviceHeaders(s.Device) {
req.Header.Set(name, value)
}
if accessToken != "" {
@@ -175,7 +176,7 @@ func NewSession(httpClient *http.Client) (*Session, error) {
}
httpClient.Jar = jar
}
return &Session{HTTPClient: httpClient, Device: RandomDeviceProfile()}, nil
return &Session{HTTPClient: httpClient, Device: common.RandomDeviceProfile()}, nil
}
func (s *Session) RegisterGuest() (*GuestAuthResponse, error) {
+7 -16
View File
@@ -81,11 +81,11 @@ type Call struct {
vp8tun *tunnel.VP8DataTunnel
mySessionID string
peersMu sync.Mutex
peersByID map[string]*PeerEntry
subscribed map[string]bool
peerToMid map[string]string
freeMids []string
peersMu sync.Mutex
peersByID map[string]*PeerEntry
subscribed map[string]bool
peerToMid map[string]string
freeMids []string
pendingSubs []string
onConnectedFired atomic.Bool
@@ -94,7 +94,7 @@ type Call struct {
OnPeerRestart func()
OnRemoteSDP func(sdp string)
done chan struct{}
done chan struct{}
closeOnce sync.Once
}
@@ -249,7 +249,7 @@ func (c *Call) Start() error {
c.cfg.LogFn("[call] OnTrack id=%q kind=%s codec=%s ssrc=%d",
remoteTrack.ID(), remoteTrack.Kind().String(), remoteTrack.Codec().MimeType, remoteTrack.SSRC())
if remoteTrack.Codec().MimeType != webrtc.MimeTypeVP8 {
go drainTrack(remoteTrack)
go tunnel.DrainTrack(remoteTrack)
return
}
go c.readVP8Track(remoteTrack)
@@ -745,12 +745,3 @@ func (c *Call) buildVideoInStats() []ClientStatVideoIn {
}
return out
}
func drainTrack(track *webrtc.TrackRemote) {
buf := make([]byte, 1500)
for {
if _, _, err := track.Read(buf); err != nil {
return
}
}
}
+3 -166
View File
@@ -2,174 +2,11 @@ package dion
import (
"fmt"
"math/rand/v2"
"whitelist-bypass/relay/common"
)
type DeviceProfile struct {
UserAgent string
Platform string
BrowserType string
BrowserVersion string
DeviceBrand string
DeviceModel string
DeviceType string
OS string
OSVersion string
ScreenWidth int
ScreenHeight int
}
type deviceTemplate struct {
os string
osVersionPool []string
deviceBrandPool []string
deviceModelPool []string
browsers []browserTemplate
}
type browserTemplate struct {
browserType string
versionPool []string
userAgentFn func(osVersion, browserVersion string) string
}
var commonScreens = [][2]int{
{1280, 720}, {1366, 768}, {1440, 900}, {1536, 864},
{1600, 900}, {1680, 1050}, {1728, 1117}, {1920, 1080},
{2048, 1152}, {2560, 1440}, {2880, 1800}, {3840, 2160},
}
var deviceTemplates = []deviceTemplate{
{
os: "Mac OS",
osVersionPool: []string{"10.15.7", "11.7.10", "12.7.6", "13.6.9", "14.6.1", "15.1.0"},
deviceBrandPool: []string{"Apple"},
deviceModelPool: []string{"Macintosh"},
browsers: []browserTemplate{
{
browserType: "Chrome",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0", "149.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36",
macOSVersionForUA(osVersion), browserVersion)
},
},
{
browserType: "Safari",
versionPool: []string{"17.6", "18.0", "18.1", "18.2"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X %s) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/%s Safari/605.1.15",
macOSVersionForUA(osVersion), browserVersion)
},
},
{
browserType: "Firefox",
versionPool: []string{"128.0", "131.0", "133.0", "135.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X %s; rv:%s) Gecko/20100101 Firefox/%s",
macOSVersionForUA(osVersion), browserVersion, browserVersion)
},
},
},
},
{
os: "Windows",
osVersionPool: []string{"10", "11"},
deviceBrandPool: []string{"Dell", "Lenovo", "HP", "Asus", "Acer", "MSI"},
deviceModelPool: []string{"PC"},
browsers: []browserTemplate{
{
browserType: "Chrome",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0", "149.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36",
browserVersion)
},
},
{
browserType: "Edge",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 Edg/%s",
browserVersion, browserVersion)
},
},
{
browserType: "Firefox",
versionPool: []string{"128.0", "131.0", "133.0", "135.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:%s) Gecko/20100101 Firefox/%s",
browserVersion, browserVersion)
},
},
},
},
{
os: "Linux",
osVersionPool: []string{"x86_64", "x86_64 GNU"},
deviceBrandPool: []string{"Dell", "Lenovo", "HP", "System76", "Framework"},
deviceModelPool: []string{"PC"},
browsers: []browserTemplate{
{
browserType: "Chrome",
versionPool: []string{"141.0.0.0", "143.0.0.0", "145.0.0.0", "147.0.0.0", "149.0.0.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36",
browserVersion)
},
},
{
browserType: "Firefox",
versionPool: []string{"128.0", "131.0", "133.0", "135.0"},
userAgentFn: func(osVersion, browserVersion string) string {
return fmt.Sprintf("Mozilla/5.0 (X11; Linux x86_64; rv:%s) Gecko/20100101 Firefox/%s",
browserVersion, browserVersion)
},
},
},
},
}
func macOSVersionForUA(osVersion string) string {
switch osVersion {
case "10.15.7":
return "10_15_7"
case "11.7.10":
return "10_15_7"
case "12.7.6":
return "10_15_7"
case "13.6.9":
return "10_15_7"
case "14.6.1":
return "10_15_7"
case "15.1.0":
return "10_15_7"
}
return "10_15_7"
}
func RandomDeviceProfile() DeviceProfile {
tmpl := deviceTemplates[rand.IntN(len(deviceTemplates))]
browser := tmpl.browsers[rand.IntN(len(tmpl.browsers))]
osVersion := tmpl.osVersionPool[rand.IntN(len(tmpl.osVersionPool))]
browserVersion := browser.versionPool[rand.IntN(len(browser.versionPool))]
screen := commonScreens[rand.IntN(len(commonScreens))]
return DeviceProfile{
UserAgent: browser.userAgentFn(osVersion, browserVersion),
Platform: "web",
BrowserType: browser.browserType,
BrowserVersion: browserVersion,
DeviceBrand: tmpl.deviceBrandPool[rand.IntN(len(tmpl.deviceBrandPool))],
DeviceModel: tmpl.deviceModelPool[rand.IntN(len(tmpl.deviceModelPool))],
DeviceType: "pc",
OS: tmpl.os,
OSVersion: osVersion,
ScreenWidth: screen[0],
ScreenHeight: screen[1],
}
}
func (p DeviceProfile) Headers() map[string]string {
func deviceHeaders(p common.DeviceProfile) map[string]string {
return map[string]string{
"d-platform": p.Platform,
"d-browser-type": p.BrowserType,
+2 -2
View File
@@ -152,8 +152,8 @@ func IceServerEntriesToWebRTC(entries []ICEServerEntry) []webrtc.ICEServer {
func BuildPionPeer(api *webrtc.API, iceServers []ICEServerEntry) (*PionPeer, error) {
pc, err := api.NewPeerConnection(webrtc.Configuration{
ICEServers: IceServerEntriesToWebRTC(iceServers),
BundlePolicy: webrtc.BundlePolicyMaxBundle,
ICEServers: IceServerEntriesToWebRTC(iceServers),
BundlePolicy: webrtc.BundlePolicyMaxBundle,
RTCPMuxPolicy: webrtc.RTCPMuxPolicyRequire,
})
if err != nil {
+86 -86
View File
@@ -18,43 +18,43 @@ import (
)
const (
MethodServerConnected = "server:notify:main:connected"
MethodServerYouJoined = "server:you_joined"
MethodServerSubscribeResponse = "server:main:response:subscribe:conference"
MethodServerSDPAnswer = "server:sdp_answer"
MethodServerSpeakerJoined = "server:speaker_joined"
MethodServerConnected = "server:notify:main:connected"
MethodServerYouJoined = "server:you_joined"
MethodServerSubscribeResponse = "server:main:response:subscribe:conference"
MethodServerSDPAnswer = "server:sdp_answer"
MethodServerSpeakerJoined = "server:speaker_joined"
MethodServerSpeakerDisconnected = "server:speaker_disconnected"
MethodServerHeartbeat = "server:notify:main:heartbeat"
MethodServerSpeakersResponse = "server:response:speakers"
MethodServerHeartbeat = "server:notify:main:heartbeat"
MethodServerSpeakersResponse = "server:response:speakers"
MethodServerSpeakersResponseZip = "server:response:speakers_zip"
MethodClientSubscribeConference = "client:main:request:subscribe:conference"
MethodClientSDPOffer = "client:request:media:sdp_offer"
MethodClientSendICECandidates = "client:request:send_ice_candidates_zip"
MethodClientPCICEStat = "client:request:pc_ice_stat"
MethodClientTrace = "client:trace"
MethodClientConfSpeakersState = "client:request:conf_speakers_state_zip"
MethodServerConfSpeakersState = "server:response:conf_speakers_state_zip"
MethodClientGetVideoFromUser = "client:request:get_video_from_user"
MethodClientStopVideoFromUser = "client:request:stop_video_from_user"
MethodServerGetVideoFromUser = "server:response:get_video_from_user"
MethodServerStopVideoFromUser = "server:response:stop_video_from_user"
MethodClientCamStateChange = "client:request:cam_state_change"
MethodClientMicStateChange = "client:request:mic_state_change"
MethodClientScreenSharingSwitchOn = "client:request:screensharing_switch_on"
MethodClientScreenSharingSwitchOff = "client:request:screensharing_switch_off"
MethodClientGetScreenSharingFromUser = "client:request:get_screensharing_from_user"
MethodClientStopScreenSharingFromUser = "client:request:stop_screensharing_from_user"
MethodClientScreensharingQualityChange = "client:request:screensharing_quality_change"
MethodServerGetScreenSharingFromUser = "server:response:get_screensharing_from_user"
MethodClientClientStatZip = "client:request:client_stat_zip"
MethodClientKickOne = "client:request:kick_one"
MethodServerKickOneResponse = "server:response:kick_one"
MethodServerYouKicked = "server:you_kicked"
MethodServerYourCamStateChanged = "server:response:your_cam_state_changed"
MethodServerYourMicStateChanged = "server:response:your_mic_state_changed"
MethodServerSpeakerCamStateChanged = "server:speaker_cam_state_changed"
MethodServerSpeakerMicStateChanged = "server:speaker_mic_state_changed"
MethodClientSubscribeConference = "client:main:request:subscribe:conference"
MethodClientSDPOffer = "client:request:media:sdp_offer"
MethodClientSendICECandidates = "client:request:send_ice_candidates_zip"
MethodClientPCICEStat = "client:request:pc_ice_stat"
MethodClientTrace = "client:trace"
MethodClientConfSpeakersState = "client:request:conf_speakers_state_zip"
MethodServerConfSpeakersState = "server:response:conf_speakers_state_zip"
MethodClientGetVideoFromUser = "client:request:get_video_from_user"
MethodClientStopVideoFromUser = "client:request:stop_video_from_user"
MethodServerGetVideoFromUser = "server:response:get_video_from_user"
MethodServerStopVideoFromUser = "server:response:stop_video_from_user"
MethodClientCamStateChange = "client:request:cam_state_change"
MethodClientMicStateChange = "client:request:mic_state_change"
MethodClientScreenSharingSwitchOn = "client:request:screensharing_switch_on"
MethodClientScreenSharingSwitchOff = "client:request:screensharing_switch_off"
MethodClientGetScreenSharingFromUser = "client:request:get_screensharing_from_user"
MethodClientStopScreenSharingFromUser = "client:request:stop_screensharing_from_user"
MethodClientScreensharingQualityChange = "client:request:screensharing_quality_change"
MethodServerGetScreenSharingFromUser = "server:response:get_screensharing_from_user"
MethodClientClientStatZip = "client:request:client_stat_zip"
MethodClientKickOne = "client:request:kick_one"
MethodServerKickOneResponse = "server:response:kick_one"
MethodServerYouKicked = "server:you_kicked"
MethodServerYourCamStateChanged = "server:response:your_cam_state_changed"
MethodServerYourMicStateChanged = "server:response:your_mic_state_changed"
MethodServerSpeakerCamStateChanged = "server:speaker_cam_state_changed"
MethodServerSpeakerMicStateChanged = "server:speaker_mic_state_changed"
ProductVersion = "6.14.0"
SubscriptionVersion = "2.0"
@@ -152,22 +152,22 @@ type SpeakerEntry struct {
}
type ConfSpeakersStateResponse struct {
SpeakersCount int `json:"speakers_count"`
WebinarSpeakersCount int `json:"webinar_speakers_count"`
Speakers []SpeakerEntry `json:"speakers"`
SpeakersCount int `json:"speakers_count"`
WebinarSpeakersCount int `json:"webinar_speakers_count"`
Speakers []SpeakerEntry `json:"speakers"`
}
type ConfSpeakersStateRequest struct {
SessionIDs []string `json:"session_ids"`
TileParams ConfSpeakersTileParams `json:"tile_params"`
InputVideoQuality string `json:"input_video_quality"`
ScreenParams ConfSpeakersScreenParams `json:"screen_params"`
SessionIDs []string `json:"session_ids"`
TileParams ConfSpeakersTileParams `json:"tile_params"`
InputVideoQuality string `json:"input_video_quality"`
ScreenParams ConfSpeakersScreenParams `json:"screen_params"`
}
type ConfSpeakersTileParams struct {
Mode string `json:"mode"`
MosaicParams ConfSpeakersMosaicParams `json:"mosaic_params"`
IsModeBlocked bool `json:"is_mode_blocked"`
Mode string `json:"mode"`
MosaicParams ConfSpeakersMosaicParams `json:"mosaic_params"`
IsModeBlocked bool `json:"is_mode_blocked"`
}
type ConfSpeakersMosaicParams struct {
@@ -218,19 +218,19 @@ type SignalingClient struct {
sessionID string
eventID string
OnYouJoined func(YouJoinedParams)
OnSubscribeResponse func()
OnSDPAnswer func(answerSDP string, transceivers []TransceiverDesc)
OnSpeakerJoined func(SpeakerJoinedParams)
OnSpeakerDisconnected func(SpeakerDisconnectedParams)
OnConfSpeakersState func(ConfSpeakersStateResponse)
OnSpeakerCamStateChanged func(SpeakerCamStateChangedParams)
OnSpeakerMicStateChanged func(SpeakerMicStateChangedParams)
OnYouJoined func(YouJoinedParams)
OnSubscribeResponse func()
OnSDPAnswer func(answerSDP string, transceivers []TransceiverDesc)
OnSpeakerJoined func(SpeakerJoinedParams)
OnSpeakerDisconnected func(SpeakerDisconnectedParams)
OnConfSpeakersState func(ConfSpeakersStateResponse)
OnSpeakerCamStateChanged func(SpeakerCamStateChangedParams)
OnSpeakerMicStateChanged func(SpeakerMicStateChangedParams)
OnGetVideoFromUserResponse func(resp GetVideoFromUserResponse, errCode int, errMessage string)
OnGetScreenSharingFromUserResponse func(resp GetScreenSharingFromUserResponse, errCode int, errMessage string)
OnHeartbeat func()
OnUnknown func(method string, params json.RawMessage)
OnDataChannelMessage func(method string, params json.RawMessage)
OnHeartbeat func()
OnUnknown func(method string, params json.RawMessage)
OnDataChannelMessage func(method string, params json.RawMessage)
}
type SignalingDialOptions struct {
@@ -422,38 +422,38 @@ func (c *SignalingClient) SendPCIceStat() error {
}
type ClientStatVideoIn struct {
BytesReceived int64 `json:"bytes_received"`
Codec string `json:"codec"`
IsEnabled bool `json:"is_enabled"`
JitterBufferDelay float64 `json:"jitter_buffer_delay"`
JitterBufferEmittedCount int `json:"jitter_buffer_emitted_count"`
Jitter float64 `json:"jitter"`
Mid int `json:"mid"`
PacketsLost int `json:"packets_lost"`
PacketsReceived int `json:"packets_received"`
Framerate int `json:"framerate"`
FreezeCount int `json:"freeze_count"`
Resolution ClientStatResolution `json:"resolution"`
Rid string `json:"rid"`
TotalFreezesDuration int `json:"total_freezes_duration"`
SessionID string `json:"session_id"`
BytesReceived int64 `json:"bytes_received"`
Codec string `json:"codec"`
IsEnabled bool `json:"is_enabled"`
JitterBufferDelay float64 `json:"jitter_buffer_delay"`
JitterBufferEmittedCount int `json:"jitter_buffer_emitted_count"`
Jitter float64 `json:"jitter"`
Mid int `json:"mid"`
PacketsLost int `json:"packets_lost"`
PacketsReceived int `json:"packets_received"`
Framerate int `json:"framerate"`
FreezeCount int `json:"freeze_count"`
Resolution ClientStatResolution `json:"resolution"`
Rid string `json:"rid"`
TotalFreezesDuration int `json:"total_freezes_duration"`
SessionID string `json:"session_id"`
}
type ClientStatVideoOut struct {
Mid int `json:"mid"`
BytesSent int64 `json:"bytes_sent"`
Codec string `json:"codec"`
IsEnabled bool `json:"is_enabled"`
PacketsSent int `json:"packets_sent"`
RemoteStats ClientStatRemoteStats `json:"remote_stats"`
TargetBitrate int `json:"target_bitrate"`
Framerate int `json:"framerate"`
FreezeCount int `json:"freeze_count"`
Resolution ClientStatResolution `json:"resolution"`
Rid string `json:"rid"`
TotalFreezesDuration int `json:"total_freezes_duration"`
SessionID string `json:"session_id"`
ScalabilityMode string `json:"scalability_mode"`
Mid int `json:"mid"`
BytesSent int64 `json:"bytes_sent"`
Codec string `json:"codec"`
IsEnabled bool `json:"is_enabled"`
PacketsSent int `json:"packets_sent"`
RemoteStats ClientStatRemoteStats `json:"remote_stats"`
TargetBitrate int `json:"target_bitrate"`
Framerate int `json:"framerate"`
FreezeCount int `json:"freeze_count"`
Resolution ClientStatResolution `json:"resolution"`
Rid string `json:"rid"`
TotalFreezesDuration int `json:"total_freezes_duration"`
SessionID string `json:"session_id"`
ScalabilityMode string `json:"scalability_mode"`
}
type ClientStatResolution struct {
@@ -487,8 +487,8 @@ type ClientStatConnection struct {
}
type ClientStatReport struct {
ReportTimeUnixMS int64 `json:"report_time_unix_ms"`
Connection ClientStatConnection `json:"connection"`
ReportTimeUnixMS int64 `json:"report_time_unix_ms"`
Connection ClientStatConnection `json:"connection"`
Audio struct {
In ClientStatAudioIn `json:"in"`
} `json:"audio"`
+156 -115
View File
@@ -2,11 +2,9 @@ package livekit
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
@@ -41,6 +39,7 @@ type Config struct {
Token string
Origin string
UserAgent string
Codec Codec
LogFn func(string, ...any)
SettingEngine *webrtc.SettingEngine
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
@@ -54,6 +53,7 @@ type Client struct {
token string
origin string
ua string
codec Codec
settingEngine *webrtc.SettingEngine
netDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
@@ -70,26 +70,34 @@ type Client struct {
subMu sync.Mutex
pubRemoteSet bool
subRemoteSet bool
pubPending []webrtc.ICECandidateInit
subPending []webrtc.ICECandidateInit
closed atomic.Bool
joined chan struct{}
joinedOnce sync.Once
closed atomic.Bool
OnReady func()
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
OnDataChannel func(*webrtc.DataChannel)
OnPubConnected func()
OnParticipantUpdate func([]ParticipantInfo)
OnReady func()
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
OnDataChannel func(*webrtc.DataChannel)
OnPubConnected func()
OnSubConnected func()
OnParticipantUpdate func([]ParticipantInfo)
// OnRemoteCandidate fires once for every trickle ICE candidate
// arriving from the SFU. Used by the Windows joiner to install
// /32 bypass routes so the joiner's own media flows stay on the
// physical NIC instead of recursing through the tunnel.
OnRemoteCandidate func(target int, candidate webrtc.ICECandidateInit)
OnRemoteCandidate func(target int, candidate webrtc.ICECandidateInit)
// OnRemoteSDP fires when the SFU sends an SDP offer or answer.
// The SDP itself can carry candidates inline; the Windows joiner
// uses this to bypass them before any media starts flowing.
OnRemoteSDP func(target int, sdpType, sdp string)
OnRemoteSDP func(target int, sdpType, sdp string)
}
func NewClient(cfg Config) *Client {
func NewClient(cfg Config) (*Client, error) {
if cfg.Codec == nil {
return nil, fmt.Errorf("livekit: no codec")
}
logFn := cfg.LogFn
if logFn == nil {
logFn = func(string, ...any) {}
@@ -100,35 +108,31 @@ func NewClient(cfg Config) *Client {
token: cfg.Token,
origin: cfg.Origin,
ua: cfg.UserAgent,
codec: cfg.Codec,
settingEngine: cfg.SettingEngine,
netDialContext: cfg.NetDialContext,
resolveICEHost: cfg.ResolveICEHost,
}
joined: make(chan struct{}),
}, nil
}
func (c *Client) Join() JoinResponse { return c.join }
func (c *Client) Join() JoinResponse { return c.join }
func (c *Client) PubPC() *webrtc.PeerConnection { return c.pubPC }
func (c *Client) SubPC() *webrtc.PeerConnection { return c.subPC }
func (c *Client) Joined() <-chan struct{} { return c.joined }
func (c *Client) Connect() error {
u, err := url.Parse(c.wsURL)
target, err := c.codec.DialURL(c.wsURL, c.token)
if err != nil {
return fmt.Errorf("parse url: %w", err)
return err
}
u.Path = "/rtc"
q := u.Query()
q.Set("access_token", c.token)
q.Set("protocol", ProtocolVersion)
q.Set("sdk", SDKName)
q.Set("version", SDKVersion)
q.Set("auto_subscribe", "1")
q.Set("adaptive_stream", "true")
u.RawQuery = q.Encode()
headers := http.Header{}
if c.ua != "" {
headers.Set("User-Agent", c.ua)
ua := c.ua
if ua == "" {
ua = common.UserAgent
}
headers.Set("User-Agent", ua)
if c.origin != "" {
headers.Set("Origin", c.origin)
}
@@ -137,51 +141,59 @@ func (c *Client) Connect() error {
if c.netDialContext != nil {
dialer.NetDialContext = c.netDialContext
}
conn, resp, err := dialer.Dial(u.String(), headers)
conn, resp, err := dialer.Dial(target, headers)
if err != nil {
if resp != nil {
return fmt.Errorf("ws dial: %w (status %d)", err, resp.StatusCode)
return fmt.Errorf("ws dial: %w, status %d", err, resp.StatusCode)
}
return fmt.Errorf("ws dial: %w", err)
}
c.wsMu.Lock()
c.ws = conn
c.wsMu.Unlock()
c.logFn("[lk] signaling connected")
return nil
}
func (c *Client) sendSignal(payload []byte) error {
if payload == nil {
return nil
}
c.wsMu.Lock()
defer c.wsMu.Unlock()
if c.ws == nil {
return fmt.Errorf("ws not connected")
}
return c.ws.WriteMessage(websocket.BinaryMessage, payload)
return c.ws.WriteMessage(c.codec.MessageType(), payload)
}
func (c *Client) SendOffer(sdp string) error {
return c.sendSignal(encSignalRequestOffer(sessionDescription{Type: "offer", SDP: sdp}))
return c.sendSignal(c.codec.EncodeOffer(sdp))
}
func (c *Client) SendAnswer(sdp string) error {
return c.sendSignal(encSignalRequestAnswer(sessionDescription{Type: "answer", SDP: sdp}))
return c.sendSignal(c.codec.EncodeAnswer(sdp))
}
func (c *Client) SendTrickle(candidate webrtc.ICECandidateInit, target int) error {
js, _ := json.Marshal(candidate)
return c.sendSignal(encSignalRequestTrickle(trickleMsg{
CandidateInit: string(js),
Target: target,
}))
return c.sendSignal(c.codec.EncodeTrickle(candidate, target))
}
func (c *Client) SendAddTrack(cid, name string, trackType, source int, width, height uint32) error {
return c.sendSignal(encSignalRequestAddTrack(cid, name, trackType, source, width, height))
return c.sendSignal(c.codec.EncodeAddTrack(AddTrackParams{
CID: cid,
Name: name,
Type: trackType,
Source: source,
Width: width,
Height: height,
}))
}
func (c *Client) SendLeave() error { return c.sendSignal(encSignalRequestLeave()) }
func (c *Client) SendLeave() error { return c.sendSignal(c.codec.EncodeLeave()) }
func (c *Client) SendPing() error {
return c.sendSignal(encSignalRequestPing(time.Now().UnixMilli()))
return c.sendSignal(c.codec.EncodePing(time.Now().UnixMilli()))
}
func (c *Client) Close() {
@@ -190,13 +202,20 @@ func (c *Client) Close() {
}
c.wsMu.Lock()
ws := c.ws
c.ws = nil
c.wsMu.Unlock()
common.CloseWS(ws)
if c.pubPC != nil {
_ = c.pubPC.Close()
c.pubMu.Lock()
pubPC := c.pubPC
c.pubMu.Unlock()
c.subMu.Lock()
subPC := c.subPC
c.subMu.Unlock()
if pubPC != nil {
_ = pubPC.Close()
}
if c.subPC != nil {
_ = c.subPC.Close()
if subPC != nil {
_ = subPC.Close()
}
}
@@ -256,8 +275,12 @@ func (c *Client) buildPeerConnections() error {
return fmt.Errorf("create sub pc: %w", err)
}
c.pubMu.Lock()
c.pubPC = pubPC
c.pubMu.Unlock()
c.subMu.Lock()
c.subPC = subPC
c.subMu.Unlock()
pubPC.OnICECandidate(func(cand *webrtc.ICECandidate) {
if cand == nil {
@@ -284,6 +307,9 @@ func (c *Client) buildPeerConnections() error {
})
subPC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
c.logFn("[lk] sub PC state: %s", state.String())
if state == webrtc.PeerConnectionStateConnected && c.OnSubConnected != nil {
c.OnSubConnected()
}
})
pubPC.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
c.logFn("[lk] pub ICE state: %s", state.String())
@@ -305,7 +331,7 @@ func (c *Client) buildPeerConnections() error {
}
})
c.logFn("[lk] PCs created (%d ICE servers)", len(c.join.ICEServers))
c.logFn("[lk] PCs created, %d ICE servers", len(c.join.ICEServers))
for i, s := range c.join.ICEServers {
c.logFn("[lk] iceServer[%d]: urls=%v hasCred=%v", i, s.URLs, s.Username != "")
}
@@ -313,60 +339,51 @@ func (c *Client) buildPeerConnections() error {
}
func (c *Client) handleSignal(data []byte) {
sr, err := decSignalResponse(data)
ev, err := c.codec.Decode(data)
if err != nil {
c.logFn("[lk] decode signal: %v", err)
return
}
switch sr.Kind {
case signalRespJoin:
if sr.Join != nil {
c.join = *sr.Join
c.logFn("[lk] join: room=%s participant=%s subscriberPrimary=%v iceServers=%d pingTimeout=%ds pingInterval=%ds",
c.join.RoomName, c.join.ParticipantID, c.join.SubscriberPrimary, len(c.join.ICEServers),
c.join.PingTimeoutSec, c.join.PingIntervalSec)
if err := c.buildPeerConnections(); err != nil {
c.logFn("[lk] %v", err)
return
}
if c.OnReady != nil {
c.OnReady()
}
switch ev.Kind {
case EventJoin:
c.join = *ev.Join
c.logFn("[lk] join: room=%s participant=%s subscriberPrimary=%v iceServers=%d pingTimeout=%ds pingInterval=%ds",
c.join.RoomName, c.join.ParticipantID, c.join.SubscriberPrimary, len(c.join.ICEServers),
c.join.PingTimeoutSec, c.join.PingIntervalSec)
if err := c.buildPeerConnections(); err != nil {
c.logFn("[lk] %v", err)
return
}
case signalRespAnswer:
c.logFn("[lk] <- pub answer (%d bytes)", len(sr.SDP.SDP))
if sr.SDP != nil {
c.applyPubAnswer(sr.SDP.SDP)
c.joinedOnce.Do(func() { close(c.joined) })
if c.OnReady != nil {
c.OnReady()
}
case signalRespOffer:
c.logFn("[lk] <- sub offer (%d bytes)", len(sr.SDP.SDP))
if sr.SDP != nil {
c.applySubOfferAndAnswer(sr.SDP.SDP)
}
case signalRespTrickle:
if sr.Trickle != nil {
c.logFn("[lk] <- trickle target=%d", sr.Trickle.Target)
c.applyRemoteTrickle(*sr.Trickle)
}
case signalRespRefreshToken:
if sr.Token != "" {
c.token = sr.Token
c.logFn("[lk] token refreshed")
}
case signalRespLeave:
if sr.Leave != nil {
case EventAnswer:
c.logFn("[lk] pub answer received, %d bytes", len(ev.SDP))
c.applyPubAnswer(ev.SDP)
case EventOffer:
c.logFn("[lk] sub offer received, %d bytes", len(ev.SDP))
c.applySubOfferAndAnswer(ev.SDP)
case EventTrickle:
c.logFn("[lk] trickle target=%d", ev.Trickle.Target)
c.applyRemoteTrickle(*ev.Trickle)
case EventToken:
c.token = ev.Token
c.logFn("[lk] token refreshed")
case EventLeave:
if ev.Leave != nil {
c.logFn("[lk] ignored leave reason=%s action=%s",
DisconnectReasonName(sr.Leave.Reason), LeaveActionName(sr.Leave.Action))
DisconnectReasonName(ev.Leave.Reason), LeaveActionName(ev.Leave.Action))
} else {
c.logFn("[lk] ignored leave")
}
case signalRespUpdate:
if c.OnParticipantUpdate != nil && len(sr.Participants) > 0 {
c.OnParticipantUpdate(sr.Participants)
case EventUpdate:
if c.OnParticipantUpdate != nil {
c.OnParticipantUpdate(ev.Participants)
}
default:
if common.Debug {
c.logFn("[lk] <- signal kind=%d (%d bytes)", sr.Kind, len(data))
c.logFn("[lk] unhandled signal, %d bytes", len(data))
}
}
}
@@ -385,6 +402,7 @@ func (c *Client) applyPubAnswer(sdp string) {
return
}
c.pubRemoteSet = true
c.drainPendingLocked(c.pubPC, &c.pubPending)
}
func (c *Client) applySubOfferAndAnswer(sdp string) {
@@ -392,21 +410,26 @@ func (c *Client) applySubOfferAndAnswer(sdp string) {
c.OnRemoteSDP(TargetSubscriber, "offer", sdp)
}
c.subMu.Lock()
defer c.subMu.Unlock()
if c.subPC == nil {
c.subMu.Unlock()
return
}
if err := c.subPC.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: sdp}); err != nil {
subPC := c.subPC
if err := subPC.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: sdp}); err != nil {
c.subMu.Unlock()
c.logFn("[lk] set sub remote offer: %v", err)
return
}
c.subRemoteSet = true
answer, err := c.subPC.CreateAnswer(nil)
c.drainPendingLocked(subPC, &c.subPending)
c.subMu.Unlock()
answer, err := subPC.CreateAnswer(nil)
if err != nil {
c.logFn("[lk] create sub answer: %v", err)
return
}
if err := c.subPC.SetLocalDescription(answer); err != nil {
if err := subPC.SetLocalDescription(answer); err != nil {
c.logFn("[lk] set sub local answer: %v", err)
return
}
@@ -415,44 +438,57 @@ func (c *Client) applySubOfferAndAnswer(sdp string) {
}
}
func (c *Client) applyRemoteTrickle(m trickleMsg) {
if m.CandidateInit == "" {
return
}
var ic webrtc.ICECandidateInit
if err := json.Unmarshal([]byte(m.CandidateInit), &ic); err != nil {
c.logFn("[lk] decode trickle candidate: %v", err)
return
func (c *Client) drainPendingLocked(pc *webrtc.PeerConnection, pending *[]webrtc.ICECandidateInit) {
for _, ic := range *pending {
if err := pc.AddICECandidate(ic); err != nil {
c.logFn("[lk] add pending candidate: %v", err)
}
}
*pending = nil
}
func (c *Client) applyRemoteTrickle(m TrickleEvent) {
if c.OnRemoteCandidate != nil {
c.OnRemoteCandidate(m.Target, ic)
c.OnRemoteCandidate(m.Target, m.Candidate)
}
switch m.Target {
case TargetPublisher:
c.pubMu.Lock()
ready := c.pubRemoteSet
c.pubMu.Unlock()
if ready {
_ = c.pubPC.AddICECandidate(ic)
}
case TargetSubscriber:
c.subMu.Lock()
ready := c.subRemoteSet
c.subMu.Unlock()
if ready {
_ = c.subPC.AddICECandidate(ic)
}
mu := &c.subMu
pc := &c.subPC
ready := &c.subRemoteSet
pending := &c.subPending
if m.Target == TargetPublisher {
mu = &c.pubMu
pc = &c.pubPC
ready = &c.pubRemoteSet
pending = &c.pubPending
}
mu.Lock()
defer mu.Unlock()
if *pc == nil || !*ready {
*pending = append(*pending, m.Candidate)
return
}
if err := (*pc).AddICECandidate(m.Candidate); err != nil {
c.logFn("[lk] add candidate: %v", err)
}
}
func (c *Client) ReadLoop() error {
defer c.Close()
c.wsMu.Lock()
ws := c.ws
c.wsMu.Unlock()
if ws == nil {
return fmt.Errorf("ws not connected")
}
for {
mt, data, err := c.ws.ReadMessage()
mt, data, err := ws.ReadMessage()
if err != nil {
if c.closed.Load() {
return nil
}
return err
}
if mt != websocket.BinaryMessage {
if !c.codec.Accepts(mt) {
continue
}
c.handleSignal(data)
@@ -460,6 +496,11 @@ func (c *Client) ReadLoop() error {
}
func (c *Client) PingLoop() {
select {
case <-c.joined:
case <-time.After(30 * time.Second):
return
}
period := PingPeriod
if c.join.PingIntervalSec > 0 {
period = time.Duration(c.join.PingIntervalSec) * time.Second
+334
View File
@@ -0,0 +1,334 @@
package livekit
import (
"encoding/json"
"fmt"
"net/url"
"github.com/gorilla/websocket"
"github.com/pion/webrtc/v4"
)
const (
EventOther = iota
EventJoin
EventAnswer
EventOffer
EventTrickle
EventUpdate
EventLeave
EventToken
)
type TrickleEvent struct {
Candidate webrtc.ICECandidateInit
Target int
}
type Event struct {
Kind int
Join *JoinResponse
SDP string
Trickle *TrickleEvent
Participants []ParticipantInfo
Token string
Leave *LeaveInfo
}
type AddTrackParams struct {
CID string
Name string
Type int
Source int
Width uint32
Height uint32
}
type Codec interface {
DialURL(serverURL, token string) (string, error)
MessageType() int
Accepts(messageType int) bool
Decode(data []byte) (Event, error)
EncodeOffer(sdp string) []byte
EncodeAnswer(sdp string) []byte
EncodeTrickle(candidate webrtc.ICECandidateInit, target int) []byte
EncodeAddTrack(p AddTrackParams) []byte
EncodePing(timestamp int64) []byte
EncodeLeave() []byte
}
type ProtoCodec struct{}
func (ProtoCodec) DialURL(serverURL, token string) (string, error) {
u, err := url.Parse(serverURL)
if err != nil {
return "", fmt.Errorf("parse url: %w", err)
}
u.Path = "/rtc"
q := u.Query()
q.Set("access_token", token)
q.Set("protocol", ProtocolVersion)
q.Set("sdk", SDKName)
q.Set("version", SDKVersion)
q.Set("auto_subscribe", "1")
q.Set("adaptive_stream", "true")
u.RawQuery = q.Encode()
return u.String(), nil
}
func (ProtoCodec) MessageType() int { return websocket.BinaryMessage }
func (ProtoCodec) Accepts(messageType int) bool { return messageType == websocket.BinaryMessage }
func (ProtoCodec) Decode(data []byte) (Event, error) {
sr, err := decSignalResponse(data)
if err != nil {
return Event{}, err
}
var ev Event
switch sr.Kind {
case signalRespJoin:
if sr.Join == nil {
return ev, nil
}
ev.Kind = EventJoin
ev.Join = sr.Join
case signalRespAnswer:
if sr.SDP == nil {
return ev, nil
}
ev.Kind = EventAnswer
ev.SDP = sr.SDP.SDP
case signalRespOffer:
if sr.SDP == nil {
return ev, nil
}
ev.Kind = EventOffer
ev.SDP = sr.SDP.SDP
case signalRespTrickle:
if sr.Trickle == nil || sr.Trickle.CandidateInit == "" {
return ev, nil
}
var ic webrtc.ICECandidateInit
if err := json.Unmarshal([]byte(sr.Trickle.CandidateInit), &ic); err != nil {
return ev, fmt.Errorf("decode trickle candidate: %w", err)
}
ev.Kind = EventTrickle
ev.Trickle = &TrickleEvent{Candidate: ic, Target: sr.Trickle.Target}
case signalRespRefreshToken:
if sr.Token == "" {
return ev, nil
}
ev.Kind = EventToken
ev.Token = sr.Token
case signalRespLeave:
ev.Kind = EventLeave
ev.Leave = sr.Leave
case signalRespUpdate:
if len(sr.Participants) == 0 {
return ev, nil
}
ev.Kind = EventUpdate
ev.Participants = sr.Participants
}
return ev, nil
}
func (ProtoCodec) EncodeOffer(sdp string) []byte {
return encSignalRequestOffer(sessionDescription{Type: "offer", SDP: sdp})
}
func (ProtoCodec) EncodeAnswer(sdp string) []byte {
return encSignalRequestAnswer(sessionDescription{Type: "answer", SDP: sdp})
}
func (ProtoCodec) EncodeTrickle(candidate webrtc.ICECandidateInit, target int) []byte {
js, _ := json.Marshal(candidate)
return encSignalRequestTrickle(trickleMsg{CandidateInit: string(js), Target: target})
}
func (ProtoCodec) EncodeAddTrack(p AddTrackParams) []byte {
return encSignalRequestAddTrack(p.CID, p.Name, p.Type, p.Source, p.Width, p.Height)
}
func (ProtoCodec) EncodePing(timestamp int64) []byte {
return encSignalRequestPing(timestamp)
}
func (ProtoCodec) EncodeLeave() []byte { return encSignalRequestLeave() }
const (
jsonTargetPublisher = "PUBLISHER"
jsonTargetSubscriber = "SUBSCRIBER"
)
type jsonSDP struct {
SDP string `json:"sdp"`
Type string `json:"type"`
}
type jsonTrickle struct {
CandidateInit string `json:"candidateInit"`
Target string `json:"target"`
}
type jsonICEServer struct {
URLs []string `json:"urls"`
Username string `json:"username"`
Credential string `json:"credential"`
}
type jsonJoin struct {
RoomID string `json:"roomId"`
PingInterval int32 `json:"pingInterval"`
ICEServers []jsonICEServer `json:"iceServers"`
Local struct {
SID string `json:"sid"`
Name string `json:"name"`
} `json:"localParticipant"`
}
type jsonVideoLayer struct {
Quality string `json:"quality"`
Width uint32 `json:"width"`
Height uint32 `json:"height"`
}
type jsonAddTrack struct {
CID string `json:"cid"`
Name string `json:"name"`
Type string `json:"type"`
Source string `json:"source"`
Width uint32 `json:"width"`
Height uint32 `json:"height"`
Layers []jsonVideoLayer `json:"layers"`
}
type JSONCodec struct{}
func (JSONCodec) DialURL(serverURL, _ string) (string, error) { return serverURL, nil }
func (JSONCodec) MessageType() int { return websocket.TextMessage }
func (JSONCodec) Accepts(messageType int) bool {
return messageType == websocket.TextMessage || messageType == websocket.BinaryMessage
}
func (JSONCodec) Decode(data []byte) (Event, error) {
var envelope map[string]json.RawMessage
if err := json.Unmarshal(data, &envelope); err != nil {
return Event{}, err
}
var ev Event
for kind, raw := range envelope {
switch kind {
case "joinResponse":
var ji jsonJoin
if err := json.Unmarshal(raw, &ji); err != nil {
return ev, fmt.Errorf("joinResponse: %w", err)
}
join := JoinResponse{
RoomName: ji.RoomID,
ParticipantSID: ji.Local.SID,
ParticipantID: ji.Local.Name,
PingIntervalSec: ji.PingInterval,
}
for _, is := range ji.ICEServers {
join.ICEServers = append(join.ICEServers, ICEServer{
URLs: is.URLs,
Username: is.Username,
Credential: is.Credential,
})
}
ev.Kind = EventJoin
ev.Join = &join
return ev, nil
case "offer", "answer":
var m jsonSDP
if err := json.Unmarshal(raw, &m); err != nil {
return ev, fmt.Errorf("%s: %w", kind, err)
}
if kind == "offer" {
ev.Kind = EventOffer
} else {
ev.Kind = EventAnswer
}
ev.SDP = m.SDP
return ev, nil
case "trickle":
var m jsonTrickle
if err := json.Unmarshal(raw, &m); err != nil {
return ev, fmt.Errorf("trickle: %w", err)
}
if m.CandidateInit == "" {
return ev, nil
}
var ic webrtc.ICECandidateInit
if err := json.Unmarshal([]byte(m.CandidateInit), &ic); err != nil {
return ev, fmt.Errorf("decode trickle candidate: %w", err)
}
target := TargetPublisher
if m.Target == jsonTargetSubscriber {
target = TargetSubscriber
}
ev.Kind = EventTrickle
ev.Trickle = &TrickleEvent{Candidate: ic, Target: target}
return ev, nil
}
}
return ev, nil
}
func (JSONCodec) encode(envelope string, payload any) []byte {
body, err := json.Marshal(map[string]any{envelope: payload})
if err != nil {
return nil
}
return body
}
func (c JSONCodec) EncodeOffer(sdp string) []byte {
return c.encode("offer", jsonSDP{SDP: sdp, Type: "offer"})
}
func (c JSONCodec) EncodeAnswer(sdp string) []byte {
return c.encode("answer", jsonSDP{SDP: sdp, Type: "answer"})
}
func (c JSONCodec) EncodeTrickle(candidate webrtc.ICECandidateInit, target int) []byte {
js, err := json.Marshal(candidate)
if err != nil {
return nil
}
wire := jsonTrickle{CandidateInit: string(js), Target: jsonTargetPublisher}
if target == TargetSubscriber {
wire.Target = jsonTargetSubscriber
}
return c.encode("trickle", wire)
}
func (c JSONCodec) EncodeAddTrack(p AddTrackParams) []byte {
kind := "VIDEO"
if p.Type == TrackTypeAudio {
kind = "AUDIO"
}
source := "CAMERA"
if p.Source == TrackSourceScreenShare {
source = "SCREEN_SHARE"
}
return c.encode("addTrack", jsonAddTrack{
CID: p.CID,
Name: p.Name,
Type: kind,
Source: source,
Width: p.Width,
Height: p.Height,
Layers: []jsonVideoLayer{{Quality: "HIGH", Width: p.Width, Height: p.Height}},
})
}
func (c JSONCodec) EncodePing(timestamp int64) []byte {
return c.encode("pingReq", map[string]any{"timestamp": timestamp, "rtt": 0})
}
func (JSONCodec) EncodeLeave() []byte { return nil }
+52
View File
@@ -0,0 +1,52 @@
package livekit
import (
"github.com/pion/datachannel"
)
type DataPacketWrapper struct {
inner datachannel.ReadWriteCloser
kind int
}
func NewDataPacketWrapper(inner datachannel.ReadWriteCloser, kind int) *DataPacketWrapper {
return &DataPacketWrapper{inner: inner, kind: kind}
}
func (w *DataPacketWrapper) ReadDataChannel(p []byte) (int, bool, error) {
buf := make([]byte, len(p))
for {
n, isString, err := w.inner.ReadDataChannel(buf)
if err != nil {
return 0, false, err
}
if n == 0 {
continue
}
payload, ok := DecodeDataPacketUser(buf[:n])
if !ok || len(payload) == 0 {
continue
}
copied := copy(p, payload)
return copied, isString, nil
}
}
func (w *DataPacketWrapper) WriteDataChannel(p []byte, isString bool) (int, error) {
wire := EncodeDataPacketUser(p, w.kind)
if _, err := w.inner.WriteDataChannel(wire, isString); err != nil {
return 0, err
}
return len(p), nil
}
func (w *DataPacketWrapper) Read(p []byte) (int, error) {
n, _, err := w.ReadDataChannel(p)
return n, err
}
func (w *DataPacketWrapper) Write(p []byte) (int, error) {
return w.WriteDataChannel(p, false)
}
func (w *DataPacketWrapper) Close() error { return w.inner.Close() }
+29 -29
View File
@@ -3,26 +3,26 @@ package livekit
import "fmt"
const (
signalReqOffer = 1
signalReqAnswer = 2
signalReqTrickle = 3
signalReqAddTrack = 4
signalReqLeave = 8
signalReqPingLegacy = 14
signalReqPingReq = 16
signalReqOffer = 1
signalReqAnswer = 2
signalReqTrickle = 3
signalReqAddTrack = 4
signalReqLeave = 8
signalReqPingLegacy = 14
signalReqPingReq = 16
signalRespJoin = 1
signalRespAnswer = 2
signalRespOffer = 3
signalRespTrickle = 4
signalRespUpdate = 5
signalRespTrackPublished = 6
signalRespLeave = 8
signalRespRoomUpdate = 11
signalRespRefreshToken = 16
signalRespPongResp = 20
signalRespRequestResponse = 22
signalRespTrackSubscribed = 23
signalRespJoin = 1
signalRespAnswer = 2
signalRespOffer = 3
signalRespTrickle = 4
signalRespUpdate = 5
signalRespTrackPublished = 6
signalRespLeave = 8
signalRespRoomUpdate = 11
signalRespRefreshToken = 16
signalRespPongResp = 20
signalRespRequestResponse = 22
signalRespTrackSubscribed = 23
sdpFieldType = 1
sdpFieldSDP = 2
@@ -179,16 +179,16 @@ type iceServer struct {
}
type joinResponse struct {
RoomSID string
RoomName string
ParticipantSID string
ParticipantID string
ServerVersion string
ServerRegion string
ICEServers []iceServer
SubscriberPrimary bool
PingTimeoutSec int32
PingIntervalSec int32
RoomSID string
RoomName string
ParticipantSID string
ParticipantID string
ServerVersion string
ServerRegion string
ICEServers []iceServer
SubscriberPrimary bool
PingTimeoutSec int32
PingIntervalSec int32
}
type signalResponse struct {
+4
View File
@@ -143,6 +143,10 @@ func main() {
c := android.NewDionHeadlessJoiner(log.Printf)
c.OnConnected = newPersistentJoinerBridge(nil)
c.Run()
case "bitrix-headless-joiner":
c := android.NewBitrixHeadlessJoiner(log.Printf)
c.OnConnected = newPersistentJoinerBridge(c.MarkConfigAcked)
c.Run()
default:
fmt.Fprintf(os.Stderr, "Unknown mode: %s\n", *mode)
os.Exit(1)
@@ -0,0 +1,46 @@
package android
import (
"log"
"strings"
"whitelist-bypass/relay/common"
joiner "whitelist-bypass/relay/pion/headless-joiner-common"
"whitelist-bypass/relay/tunnel"
)
type BitrixHeadlessJoiner struct {
inner *joiner.BitrixHeadlessJoiner
OnConnected func(tunnel.DataTunnel)
}
func NewBitrixHeadlessJoiner(logFn func(string, ...any)) *BitrixHeadlessJoiner {
if logFn == nil {
logFn = log.Printf
}
inner := joiner.NewBitrixHeadlessJoiner(logFn, RequestResolve, StatusEmitter{}, PCConfigurer{})
wrapper := &BitrixHeadlessJoiner{inner: inner}
inner.OnConnected = func(tun tunnel.DataTunnel) {
if wrapper.OnConnected != nil {
wrapper.OnConnected(tun)
}
}
return wrapper
}
func (j *BitrixHeadlessJoiner) MarkConfigAcked() { j.inner.MarkConfigAcked() }
func (j *BitrixHeadlessJoiner) Run() {
j.inner.Status.EmitStatus(common.StatusReady)
for {
line, err := ReadStdinLine()
if err != nil {
log.Printf("bitrix-joiner: stdin closed: %v", err)
return
}
if strings.HasPrefix(line, "JOIN:") {
j.inner.RunWithParams(strings.TrimPrefix(line, "JOIN:"))
return
}
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ func RequestResolve(hostname string) (string, error) {
type StatusEmitter struct{}
func (StatusEmitter) EmitStatus(status string) { common.EmitStatus(status) }
func (StatusEmitter) EmitStatus(status string) { common.EmitStatus(status) }
func (StatusEmitter) EmitStatusError(msg string) { common.EmitStatusError(msg) }
type PCConfigurer struct{}
@@ -0,0 +1,300 @@
package joiner
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pion/webrtc/v4"
"whitelist-bypass/relay/bitrix"
"whitelist-bypass/relay/common"
"whitelist-bypass/relay/tunnel"
)
type BitrixHeadlessJoiner struct {
logFn func(string, ...any)
OnConnected func(tunnel.DataTunnel)
ResolveFn ResolveFunc
Status StatusEmitter
PCConfig PeerConnectionConfigurer
joinLink string
displayName string
portal string
alias string
tunnelMode string
vp8FPS int
vp8Batch int
reliable bool
sessMu sync.Mutex
sig *bitrix.Signal
ms *bitrix.MediaSession
closeMu sync.Mutex
closed bool
stopCh chan struct{}
stopOnce sync.Once
reconnectAttempt atomic.Int32
}
func NewBitrixHeadlessJoiner(logFn func(string, ...any), resolveFn ResolveFunc, status StatusEmitter, pcConfig PeerConnectionConfigurer) *BitrixHeadlessJoiner {
return &BitrixHeadlessJoiner{
logFn: logFn,
ResolveFn: resolveFn,
Status: status,
PCConfig: pcConfig,
stopCh: make(chan struct{}),
}
}
func (j *BitrixHeadlessJoiner) MarkConfigAcked() {
j.sessMu.Lock()
ms := j.ms
j.sessMu.Unlock()
if ms != nil {
ms.MarkConfigAcked()
}
}
func (j *BitrixHeadlessJoiner) RunWithParams(jsonParams string) {
var params struct {
JoinLink string `json:"joinLink"`
DisplayName string `json:"displayName"`
TunnelMode string `json:"tunnelMode"`
VP8FPS int `json:"vp8Fps"`
VP8Batch int `json:"vp8Batch"`
Reliable bool `json:"reliable"`
DualTrack bool `json:"dualTrack"`
}
if err := json.Unmarshal([]byte(jsonParams), &params); err != nil {
j.logFn("bitrix-joiner: failed to parse params: %v", err)
j.Status.EmitStatusError("bad params: " + err.Error())
return
}
j.joinLink = params.JoinLink
j.displayName = params.DisplayName
if j.displayName == "" {
j.displayName = "Joiner"
}
if strings.EqualFold(params.TunnelMode, "dc") {
j.tunnelMode = bitrix.TunnelModeDC
} else {
j.tunnelMode = bitrix.TunnelModeVideo
}
j.vp8FPS = params.VP8FPS
if j.vp8FPS <= 0 {
j.vp8FPS = 24
}
j.vp8Batch = params.VP8Batch
if j.vp8Batch <= 0 {
j.vp8Batch = 30
}
j.reliable = params.Reliable
u, err := url.Parse(j.joinLink)
if err != nil {
j.logFn("bitrix-joiner: bad join link: %v", err)
j.Status.EmitStatusError("bad join link: " + err.Error())
return
}
j.portal = u.Scheme + "://" + u.Host
j.alias = strings.TrimPrefix(u.Path, "/video/")
if j.alias == "" || j.portal == "://" {
j.logFn("bitrix-joiner: link missing portal or /video/CODE: %s", j.joinLink)
j.Status.EmitStatusError("bad join link")
return
}
j.logFn("bitrix-joiner: portal=%s alias=%s mode=%s vp8Fps=%d vp8Batch=%d reliable=%v",
j.portal, j.alias, j.tunnelMode, j.vp8FPS, j.vp8Batch, j.reliable)
j.Status.EmitStatus(common.StatusConnecting)
if err := j.runOnce(); err != nil {
j.logFn("bitrix-joiner: %v", err)
j.Status.EmitStatusError(err.Error())
return
}
for {
if j.isClosed() {
return
}
j.Status.EmitStatus(common.StatusTunnelLost)
j.resetSessionState()
if !j.waitBeforeRetry(int(j.reconnectAttempt.Load())) {
return
}
j.reconnectAttempt.Add(1)
if j.isClosed() {
return
}
j.logFn("bitrix-joiner: reconnect attempt #%d", j.reconnectAttempt.Load())
j.Status.EmitStatus(common.StatusReconnecting)
if err := j.runOnce(); err != nil {
j.logFn("bitrix-joiner: %v, will retry", err)
}
}
}
func (j *BitrixHeadlessJoiner) Close() {
j.closeMu.Lock()
j.closed = true
j.closeMu.Unlock()
j.stopOnce.Do(func() { close(j.stopCh) })
j.resetSessionState()
}
func (j *BitrixHeadlessJoiner) runOnce() error {
userAgent := common.RandomDeviceProfile().UserAgent
c, err := bitrix.NewClient(j.portal, userAgent)
if err != nil {
return fmt.Errorf("new client: %w", err)
}
c.HTTP.Transport = j.makeTransport()
c.LogFn = j.logFn
res, err := c.JoinAsGuest(j.alias, j.displayName)
if err != nil {
return fmt.Errorf("join as guest: %w", err)
}
j.logFn("bitrix-joiner: roomId=%s mediaServer=%s", res.RoomID, res.MediaServerURL)
settingEngine := webrtc.SettingEngine{}
if j.PCConfig != nil {
j.PCConfig.ConfigureSettingEngine(&settingEngine)
}
var once sync.Once
connected := make(chan struct{})
sig, err := bitrix.ConnectSignal(bitrix.SignalConfig{
SignalURL: bitrix.SignalURL(res),
Origin: j.portal,
UserAgent: userAgent,
LogFn: j.logFn,
SettingEngine: &settingEngine,
NetDialContext: j.makeDialContext(),
OnConnected: func() {
once.Do(func() { close(connected) })
},
})
if err != nil {
return fmt.Errorf("signal connect: %w", err)
}
ms, err := bitrix.NewMediaSession(bitrix.MediaParams{
Signal: sig,
Alias: j.alias,
Mode: j.tunnelMode,
FPS: j.vp8FPS,
Batch: j.vp8Batch,
Reliable: j.reliable,
LogFn: j.logFn,
})
if err != nil {
sig.Close()
return fmt.Errorf("media session: %w", err)
}
ms.OnConnected = func(tun tunnel.DataTunnel) {
j.reconnectAttempt.Store(0)
j.Status.EmitStatus(common.StatusTunnelConnected)
j.logFn("bitrix-joiner: === TUNNEL CONNECTED === %T", tun)
if j.OnConnected != nil {
j.OnConnected(tun)
}
}
j.setSession(sig, ms)
done := make(chan struct{})
go func() {
if err := sig.Run(); err != nil {
j.logFn("bitrix-joiner: signal run ended: %s", common.MaskError(err))
}
close(done)
}()
select {
case <-connected:
case <-done:
return fmt.Errorf("signal closed before media connect")
case <-j.stopCh:
sig.Close()
return nil
}
if err := ms.Start(); err != nil {
sig.Close()
return fmt.Errorf("media start: %w", err)
}
select {
case <-done:
case <-j.stopCh:
sig.Close()
}
return nil
}
func (j *BitrixHeadlessJoiner) makeDialContext() func(ctx context.Context, network, addr string) (net.Conn, error) {
if j.ResolveFn == nil {
return nil
}
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
resolvedIP, err := j.ResolveFn(host)
if err != nil {
return nil, err
}
return (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, network, resolvedIP+":"+port)
}
}
func (j *BitrixHeadlessJoiner) makeTransport() *http.Transport {
return &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DialContext: j.makeDialContext(),
}
}
func (j *BitrixHeadlessJoiner) setSession(sig *bitrix.Signal, ms *bitrix.MediaSession) {
j.sessMu.Lock()
j.sig = sig
j.ms = ms
j.sessMu.Unlock()
}
func (j *BitrixHeadlessJoiner) resetSessionState() {
j.sessMu.Lock()
sig := j.sig
ms := j.ms
j.sig = nil
j.ms = nil
j.sessMu.Unlock()
if ms != nil {
ms.Stop()
}
if sig != nil {
sig.Close()
}
}
func (j *BitrixHeadlessJoiner) waitBeforeRetry(attempt int) bool {
return waitReconnectBackoff(attempt, j.logFn, "bitrix-joiner", j.stopCh, j.isClosed)
}
func (j *BitrixHeadlessJoiner) isClosed() bool {
j.closeMu.Lock()
defer j.closeMu.Unlock()
return j.closed
}
+8 -10
View File
@@ -15,7 +15,6 @@ import (
"whitelist-bypass/relay/common"
)
type vkConfig struct {
AppID string `json:"appID"`
ApiVersion string `json:"apiVersion"`
@@ -46,7 +45,6 @@ func RunVKAuth(joinLink string, displayName string, logFn func(string, ...any),
}
client := &http.Client{Timeout: 60 * time.Second, Transport: transport}
httpPost := func(targetURL string, form url.Values, extraHeaders map[string]string) (map[string]interface{}, error) {
req, _ := http.NewRequest("POST", targetURL, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
@@ -185,15 +183,15 @@ func RunVKAuth(joinLink string, displayName string, logFn func(string, ...any),
captchaAttempt = "1"
}
callParams = url.Values{
"v": {cfg.ApiVersion},
"vk_join_link": {joinLink},
"name": {displayName},
"captcha_key": {""},
"captcha_sid": {captchaErr.captchaSid},
"v": {cfg.ApiVersion},
"vk_join_link": {joinLink},
"name": {displayName},
"captcha_key": {""},
"captcha_sid": {captchaErr.captchaSid},
"is_sound_captcha": {"0"},
"success_token": {successToken},
"captcha_ts": {captchaErr.captchaTs},
"captcha_attempt": {captchaAttempt},
"success_token": {successToken},
"captcha_ts": {captchaErr.captchaTs},
"captcha_attempt": {captchaAttempt},
}
continue
}
+2 -10
View File
@@ -322,13 +322,13 @@ func (h *VKHeadlessJoiner) joinCall() error {
var joinResp VKJoinResponse
if jsonErr := json.Unmarshal(raw, &joinResp); jsonErr != nil {
return fmt.Errorf("decode join response: %w (body: %s)", jsonErr, truncateBody(raw))
return fmt.Errorf("decode join response: %w (body: %s)", jsonErr, common.BodySnippet(raw))
}
if joinResp.Endpoint == "" {
if rotten := detectVKAuthRotten(raw); rotten != nil {
return rotten
}
return fmt.Errorf("empty endpoint in join response: %s", truncateBody(raw))
return fmt.Errorf("empty endpoint in join response: %s", common.BodySnippet(raw))
}
h.joinResp = &joinResp
@@ -361,14 +361,6 @@ func detectVKAuthRotten(raw []byte) *vkAuthRottenError {
return nil
}
func truncateBody(raw []byte) string {
const maxLen = 200
if len(raw) > maxLen {
return string(raw[:maxLen]) + "..."
}
return string(raw)
}
func (h *VKHeadlessJoiner) connectSFU() {
endpoint := h.joinResp.WtEndpoint
if endpoint == "" {
+3 -3
View File
@@ -13,9 +13,9 @@ import (
)
type tmPCState struct {
pc *webrtc.PeerConnection
remoteSet bool
pending []webrtc.ICECandidateInit
pc *webrtc.PeerConnection
remoteSet bool
pending []webrtc.ICECandidateInit
}
type TelemostClient struct {
+35 -28
View File
@@ -60,20 +60,17 @@ func NewDCTunnel(dc *webrtc.DataChannel, obf *TunnelObfuscator, readBuf int, log
t.onClose()
}
})
go t.statsLoop()
return t
}
t.raw = raw
go t.readLoop()
go t.statsLoop()
return t
}
func NewDCTunnelFromRaw(dc *webrtc.DataChannel, raw datachannel.ReadWriteCloser, obf *TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
t := &DCTunnel{dc: dc, raw: raw, obf: obf, readBuf: readBuf, logFn: logFn}
go t.readLoop()
go t.statsLoop()
return t
}
@@ -85,19 +82,18 @@ func NewChunkedDCTunnel(readRaw datachannel.ReadWriteCloser, writeDC *webrtc.Dat
}
t := &DCTunnel{raw: readRaw, writeRaw: writeRaw, obf: obf, readBuf: readBuf, logFn: logFn, chunked: true}
go t.readLoop()
go t.statsLoop()
return t
}
func NewChunkedDCTunnelFromRaw(readRaw, writeRaw datachannel.ReadWriteCloser, obf *TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
t := &DCTunnel{raw: readRaw, writeRaw: writeRaw, obf: obf, readBuf: readBuf, logFn: logFn, chunked: true}
go t.readLoop()
go t.statsLoop()
return t
}
func (t *DCTunnel) readLoop() {
buf := make([]byte, t.readBuf)
var stats dcStats
for {
n, isString, err := t.raw.ReadDataChannel(buf)
if err != nil {
@@ -119,6 +115,9 @@ func (t *DCTunnel) readLoop() {
} else if n > 0 {
t.deliverMessage(buf[:n])
}
if common.Debug {
t.logStats(&stats)
}
}
}
@@ -255,30 +254,38 @@ func (t *DCTunnel) OnData() func([]byte) { return t.onData }
func (t *DCTunnel) SetOnClose(fn func()) { t.onClose = fn }
func (t *DCTunnel) Reconfigure(fps, batch int) {}
func (t *DCTunnel) statsLoop() {
if !common.Debug {
type dcStats struct {
last time.Time
lastRecv uint64
lastSend uint64
lastRecvMsgs uint64
lastSendMsgs uint64
}
func (t *DCTunnel) logStats(s *dcStats) {
recv := t.recvBytes.Load()
send := t.sendBytes.Load()
recvMsgs := t.recvMsgs.Load()
sendMsgs := t.sendMsgs.Load()
now := time.Now()
elapsed := now.Sub(s.last)
if s.last.IsZero() || elapsed < 2*time.Second {
if s.last.IsZero() {
s.last = now
}
return
}
var lastRecv, lastSend uint64
var lastRecvMsgs, lastSendMsgs uint64
for {
time.Sleep(2 * time.Second)
recv := t.recvBytes.Load()
send := t.sendBytes.Load()
recvMsgs := t.recvMsgs.Load()
sendMsgs := t.sendMsgs.Load()
recvDelta := recv - lastRecv
sendDelta := send - lastSend
recvMsgsDelta := recvMsgs - lastRecvMsgs
sendMsgsDelta := sendMsgs - lastSendMsgs
lastRecv = recv
lastSend = send
lastRecvMsgs = recvMsgs
lastSendMsgs = sendMsgs
if recvDelta > 0 || sendDelta > 0 {
fmt.Printf("DC-STATS: recv=%dKB/s(%dmsg) send=%dKB/s(%dmsg)\n",
recvDelta/2/1024, recvMsgsDelta/2,
sendDelta/2/1024, sendMsgsDelta/2)
}
secs := elapsed.Seconds()
recvDelta := recv - s.lastRecv
sendDelta := send - s.lastSend
if recvDelta > 0 || sendDelta > 0 {
fmt.Printf("DC-STATS: recv=%dKB/s(%dmsg) send=%dKB/s(%dmsg)\n",
uint64(float64(recvDelta)/secs)/1024, uint64(float64(recvMsgs-s.lastRecvMsgs)/secs),
uint64(float64(sendDelta)/secs)/1024, uint64(float64(sendMsgs-s.lastSendMsgs)/secs))
}
s.last = now
s.lastRecv = recv
s.lastSend = send
s.lastRecvMsgs = recvMsgs
s.lastSendMsgs = sendMsgs
}
+30
View File
@@ -0,0 +1,30 @@
package tunnel
import (
"github.com/pion/webrtc/v4"
"whitelist-bypass/relay/common"
)
func DrainSenderRTCP(sender *webrtc.RTPSender) {
if sender == nil {
return
}
buf := make([]byte, 1500)
for {
if _, _, err := sender.Read(buf); err != nil {
return
}
}
}
func DrainTrack(track *webrtc.TrackRemote) {
if track == nil {
return
}
buf := make([]byte, common.UDPBufSize)
for {
if _, _, err := track.Read(buf); err != nil {
return
}
}
}
+5 -5
View File
@@ -25,11 +25,11 @@ var vp8Interframe = []byte{
}
const (
vp8KeepaliveLen = 20
vp8InterframeLen = 17
epochFieldLen = 4
keepaliveHdrLen = vp8KeepaliveLen + epochFieldLen
interframeHdrLen = vp8InterframeLen + epochFieldLen
vp8KeepaliveLen = 20
vp8InterframeLen = 17
epochFieldLen = 4
keepaliveHdrLen = vp8KeepaliveLen + epochFieldLen
interframeHdrLen = vp8InterframeLen + epochFieldLen
)
var ErrEmptySecret = errors.New("tunnel: obfuscator requires a non-empty secret")
-15
View File
@@ -1,15 +0,0 @@
package tunnel
import "github.com/pion/webrtc/v4"
func DrainSenderRTCP(sender *webrtc.RTPSender) {
if sender == nil {
return
}
buf := make([]byte, 1500)
for {
if _, _, err := sender.Read(buf); err != nil {
return
}
}
}
+1 -1
View File
@@ -247,7 +247,7 @@ func (s *SymmetricScreenTunnel) SetOnData(fn func([]byte)) {
s.cam.SetOnData(fn)
}
func (s *SymmetricScreenTunnel) SetOnClose(fn func()) { s.cam.SetOnClose(fn) }
func (s *SymmetricScreenTunnel) SetOnClose(fn func()) { s.cam.SetOnClose(fn) }
func (s *SymmetricScreenTunnel) Reconfigure(fps, batch int) {
s.cam.Reconfigure(fps, batch)
s.screen.Reconfigure(fps, batch)
-53
View File
@@ -1,53 +0,0 @@
package wbstream
import (
"github.com/pion/datachannel"
"whitelist-bypass/relay/livekit"
)
type dataPacketWrapper struct {
inner datachannel.ReadWriteCloser
kind int
}
func newDataPacketWrapper(inner datachannel.ReadWriteCloser, kind int) *dataPacketWrapper {
return &dataPacketWrapper{inner: inner, kind: kind}
}
func (w *dataPacketWrapper) ReadDataChannel(p []byte) (int, bool, error) {
buf := make([]byte, len(p))
for {
n, isString, err := w.inner.ReadDataChannel(buf)
if err != nil {
return 0, false, err
}
if n == 0 {
continue
}
payload, ok := livekit.DecodeDataPacketUser(buf[:n])
if !ok || len(payload) == 0 {
continue
}
copied := copy(p, payload)
return copied, isString, nil
}
}
func (w *dataPacketWrapper) WriteDataChannel(p []byte, isString bool) (int, error) {
wire := livekit.EncodeDataPacketUser(p, w.kind)
if _, err := w.inner.WriteDataChannel(wire, isString); err != nil {
return 0, err
}
return len(p), nil
}
func (w *dataPacketWrapper) Read(p []byte) (int, error) {
n, _, err := w.ReadDataChannel(p)
return n, err
}
func (w *dataPacketWrapper) Write(p []byte) (int, error) {
return w.WriteDataChannel(p, false)
}
func (w *dataPacketWrapper) Close() error { return w.inner.Close() }
+24 -24
View File
@@ -61,12 +61,13 @@ type Session struct {
pubReliableDCReady bool
subReliableDC *webrtc.DataChannel
vp8tun *tunnel.MultiTrackTunnel
kcptun *tunnel.MultiTrackKCPTunnel
dctun *tunnel.DCTunnel
mu sync.Mutex
tunFired bool
done chan struct{}
vp8tun *tunnel.MultiTrackTunnel
kcptun *tunnel.MultiTrackKCPTunnel
dctun *tunnel.DCTunnel
dcStarted bool
mu sync.Mutex
tunFired bool
done chan struct{}
peersBySID map[string]peerEntry // SID -> first-seen time + state
kickedSIDs map[string]bool // SIDs we kicked; SFU may still echo them as Active until it processes the kick
@@ -104,16 +105,21 @@ func (s *Session) MarkConfigAcked() {
func (s *Session) Done() <-chan struct{} { return s.done }
func (s *Session) Start() error {
s.lk = livekit.NewClient(livekit.Config{
lk, err := livekit.NewClient(livekit.Config{
ServerURL: s.cfg.ServerURL,
Token: s.cfg.RoomToken,
Origin: Origin,
UserAgent: common.UserAgent,
Codec: livekit.ProtoCodec{},
LogFn: s.cfg.LogFn,
SettingEngine: s.cfg.SettingEngine,
NetDialContext: s.cfg.NetDialContext,
ResolveICEHost: s.cfg.ResolveICEHost,
})
if err != nil {
return err
}
s.lk = lk
s.lk.OnReady = s.onLKReady
s.lk.OnTrack = s.onRemoteTrack
s.lk.OnDataChannel = s.onRemoteDataChannel
@@ -312,10 +318,6 @@ func (s *Session) configPingPong(tun tunnel.DataTunnel, trackCount int) {
func (s *Session) maybeStartDCTunnel() {
s.mu.Lock()
if s.dctun != nil {
s.mu.Unlock()
return
}
pubDC := s.pubReliableDC
subDC := s.subReliableDC
pubReady := s.pubReliableDCReady
@@ -326,6 +328,14 @@ func (s *Session) maybeStartDCTunnel() {
if subDC.ReadyState() != webrtc.DataChannelStateOpen {
return
}
s.mu.Lock()
if s.dcStarted {
s.mu.Unlock()
return
}
s.dcStarted = true
s.mu.Unlock()
subRaw, err := subDC.Detach()
if err != nil {
s.cfg.LogFn("[lk] detach sub DC: %v", err)
@@ -336,16 +346,13 @@ func (s *Session) maybeStartDCTunnel() {
s.cfg.LogFn("[lk] detach pub DC: %v", err)
return
}
readWrapped := newDataPacketWrapper(subRaw, livekit.DataPacketKindReliable)
writeWrapped := newDataPacketWrapper(pubRaw, livekit.DataPacketKindReliable)
readWrapped := livekit.NewDataPacketWrapper(subRaw, livekit.DataPacketKindReliable)
writeWrapped := livekit.NewDataPacketWrapper(pubRaw, livekit.DataPacketKindReliable)
readBuf := s.cfg.ReadBuf
if readBuf == 0 {
readBuf = common.DCBufSize
}
dctun := tunnel.NewChunkedDCTunnelFromRaw(readWrapped, writeWrapped, s.cfg.Obfuscator, readBuf, s.cfg.LogFn)
if dctun == nil {
return
}
s.mu.Lock()
s.dctun = dctun
s.mu.Unlock()
@@ -575,14 +582,7 @@ func (s *Session) rearmAutoDetect() {
func (s *Session) onRemoteTrack(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
go func() {
buf := make([]byte, common.UDPBufSize)
for {
if _, _, err := track.Read(buf); err != nil {
return
}
}
}()
go tunnel.DrainTrack(track)
return
}
go s.readVP8Track(track)