add wbstream auth support

This commit is contained in:
kulikov0 committed 2026-05-16 07:33:50 +02:00
1 parent 221c4f595f
commit b341370904
18 files changed
+373 -77

No files matched your search

+1
View File
@@ -12,6 +12,7 @@
<div class="tab-action-btn" id="btnVkCookies" title="Export VK cookies to vk-cookies.json for headless mode">VK Cookies</div> <div class="tab-action-btn" id="btnVkCookies" title="Export VK cookies to vk-cookies.json for headless mode">VK Cookies</div>
<div class="tab-action-btn" id="btnYandexCookies" title="Export Yandex cookies to cookies-yandex.json for headless mode">Yandex Cookies</div> <div class="tab-action-btn" id="btnYandexCookies" title="Export Yandex cookies to cookies-yandex.json for headless mode">Yandex Cookies</div>
<div class="tab-action-btn" id="btnDionCookies" title="Export DION cookies to cookies-dion.json for headless mode">DION Cookies</div> <div class="tab-action-btn" id="btnDionCookies" title="Export DION cookies to cookies-dion.json for headless mode">DION Cookies</div>
<div class="tab-action-btn" id="btnWBStreamCookies" title="Export WB Stream cookies to cookies-wbstream.json for headless mode">WB Cookies</div>
<div class="tab-action-btn settings" id="btnSettings" title="Settings">Settings</div> <div class="tab-action-btn settings" id="btnSettings" title="Settings">Settings</div>
<div class="tab-action-btn bot" id="tabBot">Bot: Off</div> <div class="tab-action-btn bot" id="tabBot">Bot: Off</div>
</div> </div>
+5 -2
View File
@@ -17,21 +17,24 @@ export const DION_URL = 'https://dion.vc/';
export const VK_LOGIN_URL = 'https://vk.com/'; export const VK_LOGIN_URL = 'https://vk.com/';
export const YANDEX_LOGIN_URL = 'https://passport.yandex.ru/auth?retpath=https%3A%2F%2Ftelemost.yandex.ru%2F'; 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 DION_LOGIN_URL = 'https://dion.vc/login';
export const WBSTREAM_LOGIN_URL = 'https://stream.wb.ru/login';
export const VK_AUTH_COOKIE = 'remixsid'; export const VK_AUTH_COOKIE = 'remixsid';
export const YANDEX_AUTH_COOKIE = 'Session_id'; export const YANDEX_AUTH_COOKIE = 'Session_id';
export const DION_AUTH_COOKIE = 'vc-refresh-token'; export const DION_AUTH_COOKIE = 'vc-refresh-token';
export const WBSTREAM_AUTH_COOKIE = 'x_wbaas_token';
export const SESSION_PARTITION = 'persist:creator'; export const SESSION_PARTITION = 'persist:creator';
export const WINDOW_WIDTH = 1200; export const WINDOW_WIDTH = 1200;
export const WINDOW_HEIGHT = 800; export const WINDOW_HEIGHT = 800;
export const USER_AGENT = export const USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ' + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'; 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
export const VK_COOKIE_DOMAINS = ['vk.com', 'vk.ru']; export const VK_COOKIE_DOMAINS = ['vk.com', 'vk.ru'];
export const YANDEX_COOKIE_DOMAINS = ['yandex.ru', 'yandex.net', 'ya.ru']; export const YANDEX_COOKIE_DOMAINS = ['yandex.ru', 'yandex.net', 'ya.ru'];
export const DION_COOKIE_DOMAINS = ['dion.vc']; export const DION_COOKIE_DOMAINS = ['dion.vc'];
export const WBSTREAM_COOKIE_DOMAINS = ['stream.wb.ru', 'wb.ru', 'wildberries.ru'];
export enum Selector { export enum Selector {
VK_ADMIT = '[data-testid="calls_waiting_hall_promote"]', VK_ADMIT = '[data-testid="calls_waiting_hall_promote"]',
+6 -1
View File
@@ -1,4 +1,4 @@
import { app } from 'electron'; import { app, protocol } from 'electron';
import { TabManager } from './tab-manager'; import { TabManager } from './tab-manager';
import { createWindow } from './window'; import { createWindow } from './window';
import { registerIpcHandlers } from './ipc'; import { registerIpcHandlers } from './ipc';
@@ -7,7 +7,12 @@ const tabManager = new TabManager();
registerIpcHandlers(tabManager); registerIpcHandlers(tabManager);
protocol.registerSchemesAsPrivileged([
{ scheme: 'wbstream', privileges: { standard: true, secure: true, supportFetchAPI: true } },
]);
app.whenReady().then(() => { app.whenReady().then(() => {
protocol.handle('wbstream', () => new Response(null, { status: 204 }));
const win = createWindow(tabManager); const win = createWindow(tabManager);
tabManager.mainWindow = win; tabManager.mainWindow = win;
}); });
+2
View File
@@ -9,6 +9,7 @@ import {
VK_COOKIE_DOMAINS, VK_COOKIE_DOMAINS,
YANDEX_COOKIE_DOMAINS, YANDEX_COOKIE_DOMAINS,
DION_COOKIE_DOMAINS, DION_COOKIE_DOMAINS,
WBSTREAM_COOKIE_DOMAINS,
} from '../constants'; } from '../constants';
import { TunnelMode, Platform, BotSettings, HeadlessStartArgs } from '../types'; import { TunnelMode, Platform, BotSettings, HeadlessStartArgs } from '../types';
@@ -101,6 +102,7 @@ export function registerIpcHandlers(tabManager: TabManager): void {
let domains: string[]; let domains: string[];
if (domain === 'yandex') domains = YANDEX_COOKIE_DOMAINS; if (domain === 'yandex') domains = YANDEX_COOKIE_DOMAINS;
else if (domain === 'dion') domains = DION_COOKIE_DOMAINS; else if (domain === 'dion') domains = DION_COOKIE_DOMAINS;
else if (domain === 'wbstream') domains = WBSTREAM_COOKIE_DOMAINS;
else domains = VK_COOKIE_DOMAINS; else domains = VK_COOKIE_DOMAINS;
const filtered = all.filter((cookie) => { const filtered = all.filter((cookie) => {
return cookie.domain != null && domains.some((d) => cookie.domain!.includes(d)); return cookie.domain != null && domains.some((d) => cookie.domain!.includes(d));
+82 -22
View File
@@ -23,12 +23,15 @@ import {
VK_COOKIE_DOMAINS, VK_COOKIE_DOMAINS,
YANDEX_COOKIE_DOMAINS, YANDEX_COOKIE_DOMAINS,
DION_COOKIE_DOMAINS, DION_COOKIE_DOMAINS,
WBSTREAM_COOKIE_DOMAINS,
VK_LOGIN_URL, VK_LOGIN_URL,
YANDEX_LOGIN_URL, YANDEX_LOGIN_URL,
DION_LOGIN_URL, DION_LOGIN_URL,
WBSTREAM_LOGIN_URL,
VK_AUTH_COOKIE, VK_AUTH_COOKIE,
YANDEX_AUTH_COOKIE, YANDEX_AUTH_COOKIE,
DION_AUTH_COOKIE, DION_AUTH_COOKIE,
WBSTREAM_AUTH_COOKIE,
LOG_CAPTURE_SNIPPET, LOG_CAPTURE_SNIPPET,
} from '../constants'; } from '../constants';
import { BotManager } from '../bot/bot-manager'; import { BotManager } from '../bot/bot-manager';
@@ -278,6 +281,16 @@ export class TabManager {
binaryPath: this.headlessVKPath, binaryPath: this.headlessVKPath,
getCookies: () => this.getVKCookies(), getCookies: () => this.getVKCookies(),
}; };
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,
getCookies: () => this.getWBStreamCookies(),
};
default: default:
return null; return null;
} }
@@ -306,22 +319,6 @@ export class TabManager {
return; return;
} }
if (platform === Platform.WBStream) {
tab.tunnelMode = TunnelMode.HeadlessWBStream;
this.killRelay(tabId, tab);
const wbArgs = ['--resources', 'default'];
if (joinTarget) wbArgs.push('--room', joinTarget);
const proc = spawn(this.headlessWBStreamPath, wbArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
});
tab.relay = proc;
this.attachProcessOutput(proc, tabId);
proc.on('close', (code) => {
this.sendLog(tabId, `Headless exited with code ${code}`);
});
return;
}
const config = this.headlessConfig(platform); const config = this.headlessConfig(platform);
if (!config) { if (!config) {
this.sendLog(tabId, `Unsupported headless platform: ${platform}`); this.sendLog(tabId, `Unsupported headless platform: ${platform}`);
@@ -329,12 +326,19 @@ export class TabManager {
} }
tab.tunnelMode = config.tunnelMode; tab.tunnelMode = config.tunnelMode;
let cookies = await config.getCookies(); let cookies = await config.getCookies();
if (!cookies.some((c) => c.name === config.authCookie)) { const refreshCookie = platform === Platform.WBStream ? 'wbx-refresh' : config.authCookie;
const needsLogin = !cookies.some((c) => c.name === refreshCookie);
if (needsLogin) {
this.sendLog(tabId, `No ${config.platformName} session found, opening login.`); this.sendLog(tabId, `No ${config.platformName} session found, opening login.`);
if (this._mainWindow && !this._mainWindow.isDestroyed()) { if (this._mainWindow && !this._mainWindow.isDestroyed()) {
this._mainWindow.webContents.send(IPC.LOGIN_REQUIRED, { tabId, url: config.loginUrl }); this._mainWindow.webContents.send(IPC.LOGIN_REQUIRED, { tabId, url: config.loginUrl });
} }
await this.waitForLogin(config.cookieDomains, config.authCookie); 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 {
await this.waitForLogin(config.cookieDomains, config.authCookie);
}
if (this._mainWindow && !this._mainWindow.isDestroyed()) { if (this._mainWindow && !this._mainWindow.isDestroyed()) {
this._mainWindow.webContents.send(IPC.LOGIN_DONE, { tabId }); this._mainWindow.webContents.send(IPC.LOGIN_DONE, { tabId });
} }
@@ -363,11 +367,8 @@ export class TabManager {
proc.on('close', async (code) => { proc.on('close', async (code) => {
this.sendLog(tabId, `Headless exited with code ${code}`); this.sendLog(tabId, `Headless exited with code ${code}`);
if (sawAuthFailure) { if (sawAuthFailure) {
this.sendLog(tabId, `${config.platformName} session rejected (401), clearing and re-prompting login.`);
await this.clearAuthCookies(config.cookieDomains, config.authCookie); await this.clearAuthCookies(config.cookieDomains, config.authCookie);
if (this.tabs.get(tabId) === tab) { if (this.tabs.get(tabId) === tab) this.startHeadless(tabId, platform, args);
this.startHeadless(tabId, platform, args);
}
} }
}); });
} }
@@ -483,4 +484,63 @@ export class TabManager {
.map((c) => ({ name: c.name, value: c.value })); .map((c) => ({ name: c.name, value: c.value }));
} }
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();
});
});
}
async getWBStreamCookies(): Promise<{ name: string; value: string }[]> {
const ses = session.fromPartition(SESSION_PARTITION);
const all = await ses.cookies.get({});
return all
.filter((c) => c.domain != null && WBSTREAM_COOKIE_DOMAINS.some((d) => c.domain!.includes(d)))
.map((c) => ({ name: c.name, value: c.value }));
}
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);
}
}
} }
+33
View File
@@ -67,11 +67,39 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
const autoclickers = new Map<number, { telemost: TelemostAutoclick; vk: VkAutoclick }>(); const autoclickers = new Map<number, { telemost: TelemostAutoclick; vk: VkAutoclick }>();
const wbDeviceIdHook = `(function(){
try {
var key = 'wb_auth_api_device_id';
var existing = localStorage.getItem(key);
if (existing) console.log('[WB_DEVICE_ID]', existing);
var orig = Storage.prototype.setItem;
Storage.prototype.setItem = function(k, v) {
if (k === key) console.log('[WB_DEVICE_ID]', v);
return orig.apply(this, arguments);
};
} catch (e) {}
})();`;
win.webContents.on('did-attach-webview', (_e, wvContents) => { win.webContents.on('did-attach-webview', (_e, wvContents) => {
wvContents.on('before-input-event', (_e, input) => { wvContents.on('before-input-event', (_e, input) => {
if (input.key === 'F12') wvContents.openDevTools(); if (input.key === 'F12') wvContents.openDevTools();
}); });
wvContents.on('will-navigate', (event, url) => {
if (!url.startsWith('http://') && !url.startsWith('https://')) event.preventDefault();
});
wvContents.setWindowOpenHandler(({ url }) => {
if (!url.startsWith('http://') && !url.startsWith('https://')) return { action: 'deny' };
return { action: 'allow' };
});
wvContents.on('dom-ready', () => {
const url = wvContents.getURL();
if (url.includes('stream.wb.ru')) {
wvContents.executeJavaScript(wbDeviceIdHook, true).catch(() => {});
}
});
wvContents.on('did-navigate', (_e, url) => { wvContents.on('did-navigate', (_e, url) => {
const wcId = wvContents.id; const wcId = wvContents.id;
if (!autoclickers.has(wcId)) { if (!autoclickers.has(wcId)) {
@@ -102,6 +130,11 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
handleBotCallLink(tabManager, msg, Platform.VK); handleBotCallLink(tabManager, msg, Platform.VK);
handleBotCallLink(tabManager, msg, Platform.Telemost); handleBotCallLink(tabManager, msg, Platform.Telemost);
const deviceIdMatch = msg.match(/\[WB_DEVICE_ID\]\s+(\S+)/);
if (deviceIdMatch) {
tabManager.setWBStreamDeviceId(deviceIdMatch[1]).catch(() => {});
}
const callStatus = parseCallStatus(msg); const callStatus = parseCallStatus(msg);
if (callStatus) { if (callStatus) {
console.log('[MAIN] Cached status for', callStatus.tabId, ':', callStatus.status); console.log('[MAIN] Cached status for', callStatus.tabId, ':', callStatus.status);
+4 -4
View File
@@ -1,5 +1,5 @@
import { Platform, Bridge, LogPanel, TunnelMode, Webview } from '../types'; import { Platform, Bridge, LogPanel, TunnelMode, Webview } from '../types';
import { SESSION_PARTITION, HOOK_POLL_INTERVAL_MS, CALL_CREATOR_INJECT_DELAY_MS } from '../constants'; import { SESSION_PARTITION, HOOK_POLL_INTERVAL_MS, CALL_CREATOR_INJECT_DELAY_MS, USER_AGENT } from '../constants';
import { RendererTabManager } from './tab-manager'; import { RendererTabManager } from './tab-manager';
declare const window: Window & { bridge: Bridge }; declare const window: Window & { bridge: Bridge };
@@ -40,9 +40,9 @@ export function renderContent(tm: RendererTabManager): void {
} }
welcome.style.display = 'none'; welcome.style.display = 'none';
logsPanel.style.display = 'flex';
const activeTab = tm.tabs[tm.activeTabId]; const activeTab = tm.tabs[tm.activeTabId];
logsPanel.style.display = activeTab.loginWebview ? 'none' : 'flex';
hookPanel.style.display = activeTab.headless ? 'none' : 'flex'; hookPanel.style.display = activeTab.headless ? 'none' : 'flex';
logsPanel.classList.toggle('relay-only', activeTab.headless === true); logsPanel.classList.toggle('relay-only', activeTab.headless === true);
if (activeTab.loginWebview) { if (activeTab.loginWebview) {
@@ -152,7 +152,7 @@ export function attachLoginWebview(tm: RendererTabManager, tabId: string, url: s
const webview = document.createElement('webview') as unknown as Webview; const webview = document.createElement('webview') as unknown as Webview;
webview.setAttribute('src', url); webview.setAttribute('src', url);
webview.setAttribute('partition', SESSION_PARTITION); webview.setAttribute('partition', SESSION_PARTITION);
webview.setAttribute('useragent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'); webview.setAttribute('useragent', USER_AGENT);
webview.classList.add('webview-full'); webview.classList.add('webview-full');
webview.dataset.tabId = tabId; webview.dataset.tabId = tabId;
document.getElementById('content')!.appendChild(webview); document.getElementById('content')!.appendChild(webview);
@@ -185,7 +185,7 @@ export function loadURL(tm: RendererTabManager, url: string): void {
webview.setAttribute('partition', SESSION_PARTITION); webview.setAttribute('partition', SESSION_PARTITION);
webview.setAttribute('nodeintegration', ''); webview.setAttribute('nodeintegration', '');
webview.setAttribute('nodeintegrationinsubframes', ''); webview.setAttribute('nodeintegrationinsubframes', '');
webview.setAttribute('useragent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'); webview.setAttribute('useragent', USER_AGENT);
webview.classList.add('webview-full'); webview.classList.add('webview-full');
webview.dataset.tabId = tm.activeTabId; webview.dataset.tabId = tm.activeTabId;
document.getElementById('content')!.appendChild(webview); document.getElementById('content')!.appendChild(webview);
+7
View File
@@ -83,6 +83,13 @@ function bindActionBarEvents(): void {
'No DION cookies found.\nPlease log into DION (dion.vc) first.', 'No DION cookies found.\nPlease log into DION (dion.vc) first.',
); );
}); });
document.getElementById('btnWBStreamCookies')!.addEventListener('click', () => {
exportCookies(
'wbstream',
'cookies-wbstream.json',
'No WB Stream cookies found.\nPlease log into stream.wb.ru first.',
);
});
document.getElementById('btnSettings')!.addEventListener('click', openSettings); document.getElementById('btnSettings')!.addEventListener('click', openSettings);
document.getElementById('tabBot')!.addEventListener('click', () => { document.getElementById('tabBot')!.addEventListener('click', () => {
if (!tm.botSettings.token || !tm.botSettings.groupId) { if (!tm.botSettings.token || !tm.botSettings.groupId) {
+5 -5
View File
@@ -7,7 +7,6 @@ import (
"os" "os"
"os/signal" "os/signal"
"runtime/debug" "runtime/debug"
"strings"
"syscall" "syscall"
"whitelist-bypass/relay/common" "whitelist-bypass/relay/common"
@@ -16,7 +15,7 @@ import (
) )
func main() { func main() {
roomFlag := flag.String("room", "", "WB Stream room id or wbstream://<id> (required)") roomFlag := flag.String("room", "", "WB Stream room id, wbstream://<id>, or https://stream.wb.ru/room/<id> (required)")
displayName := flag.String("name", "Joiner", "display name in the room") displayName := flag.String("name", "Joiner", "display name in the room")
socksPort := flag.Int("socks-port", 1080, "SOCKS5 listen port") socksPort := flag.Int("socks-port", 1080, "SOCKS5 listen port")
socksUser := flag.String("socks-user", "", "SOCKS5 username (optional)") socksUser := flag.String("socks-user", "", "SOCKS5 username (optional)")
@@ -47,12 +46,12 @@ func main() {
} }
common.MaskingEnabled = true common.MaskingEnabled = true
roomID := strings.TrimPrefix(strings.TrimSpace(*roomFlag), "wbstream://") roomID := wbstream.ParseRoomID(*roomFlag)
id, roomToken, _, err := wbstream.AuthAndGetToken(nil, roomID, *displayName) id, roomToken, _, serverURL, err := wbstream.AuthAndGetToken(nil, roomID, *displayName)
if err != nil { if err != nil {
log.Fatalf("[auth] %v", err) log.Fatalf("[auth] %v", err)
} }
log.Printf("[auth] room=%s mode=%s", id, *tunnelMode) log.Printf("[auth] room=%s server=%s mode=%s", id, serverURL, *tunnelMode)
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(id)) obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(id))
if err != nil { if err != nil {
@@ -62,6 +61,7 @@ func main() {
sess := wbstream.NewSession(wbstream.SessionConfig{ sess := wbstream.NewSession(wbstream.SessionConfig{
RoomToken: roomToken, RoomToken: roomToken,
ServerURL: serverURL,
DisplayName: *displayName, DisplayName: *displayName,
TunnelMode: *tunnelMode, TunnelMode: *tunnelMode,
Obfuscator: obf, Obfuscator: obf,
+32 -9
View File
@@ -6,7 +6,6 @@ import (
"log" "log"
"os" "os"
"runtime/debug" "runtime/debug"
"strings"
"time" "time"
"whitelist-bypass/relay/common" "whitelist-bypass/relay/common"
@@ -15,7 +14,8 @@ import (
) )
func main() { func main() {
roomFlag := flag.String("room", "", "WB Stream room id or wbstream://<id> (empty = create new)") cookiesPath := flag.String("cookies", "", "path to cookies-wbstream.json")
roomFlag := flag.String("room", "", "WB Stream room id, wbstream://<id>, or https://stream.wb.ru/room/<id> (empty = create new)")
displayName := flag.String("name", "Headless", "display name in the room") displayName := flag.String("name", "Headless", "display name in the room")
resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited, custom") resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited, custom")
customReadBuf := flag.Int("read-buf", 0, "DC read buffer size in bytes, used with -resources custom") customReadBuf := flag.Int("read-buf", 0, "DC read buffer size in bytes, used with -resources custom")
@@ -53,12 +53,26 @@ func main() {
common.MaskingEnabled = true common.MaskingEnabled = true
log.Printf("[config] resources=%s read-buf=%d mem-limit=%d", *resources, readBuf, memLimit) log.Printf("[config] resources=%s read-buf=%d mem-limit=%d", *resources, readBuf, memLimit)
requestedRoom := strings.TrimPrefix(strings.TrimSpace(*roomFlag), "wbstream://") if *cookiesPath == "" {
roomID, roomToken, accessToken, err := wbstream.AuthAndGetToken(nil, requestedRoom, *displayName) log.Fatalf("[auth] --cookies is required")
}
rawCookies := common.LoadCookies(*cookiesPath)
deviceID := common.CookieValue(rawCookies, "__wb_device_id")
if deviceID == "" {
log.Fatalf("[auth] cookies file is missing __wb_device_id; re-export via creator-app's 'WB Cookies' button")
}
cookieHeader := common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
bearer, err := wbstream.RefreshAccessToken(nil, cookieHeader, deviceID)
if err != nil {
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 { if err != nil {
log.Fatalf("[auth] %v", err) log.Fatalf("[auth] %v", err)
} }
log.Printf("[auth] room=%s", roomID) log.Printf("[auth] room=%s server=%s", roomID, serverURL)
if *writeFile != "" { if *writeFile != "" {
f, err := os.OpenFile(*writeFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(*writeFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
@@ -77,9 +91,10 @@ func main() {
log.Printf("[obf] key-source=%q localEpoch=0x%08x", roomID, obf.LocalEpoch()) log.Printf("[obf] key-source=%q localEpoch=0x%08x", roomID, obf.LocalEpoch())
var activeBridge *tunnel.RelayBridge var activeBridge *tunnel.RelayBridge
makeSession := func(token, access string) *wbstream.Session { makeSession := func(token, access, server string) *wbstream.Session {
sess := wbstream.NewSession(wbstream.SessionConfig{ sess := wbstream.NewSession(wbstream.SessionConfig{
RoomToken: token, RoomToken: token,
ServerURL: server,
DisplayName: *displayName, DisplayName: *displayName,
Obfuscator: obf, Obfuscator: obf,
LogFn: log.Printf, LogFn: log.Printf,
@@ -115,7 +130,7 @@ func main() {
fmt.Println("") fmt.Println("")
for { for {
sess := makeSession(roomToken, accessToken) sess := makeSession(roomToken, accessToken, serverURL)
if err := sess.Start(); err != nil { if err := sess.Start(); err != nil {
log.Printf("[session] start failed: %v, retrying in 5s", err) log.Printf("[session] start failed: %v, retrying in 5s", err)
sess.Close() sess.Close()
@@ -131,7 +146,14 @@ func main() {
} }
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
_, newRoomToken, newAccessToken, err := wbstream.AuthAndGetToken(nil, roomID, *displayName) newBearer, refreshErr := wbstream.RefreshAccessToken(nil, cookieHeader, deviceID)
if refreshErr != nil {
log.Printf("[rejoin] slide-v3 refresh failed: %v, retrying in 5s", refreshErr)
time.Sleep(5 * time.Second)
continue
}
bearer = newBearer
_, newRoomToken, newAccessToken, newServerURL, err := wbstream.AuthAsLoggedIn(nil, cookieHeader, bearer, roomID, *displayName)
if err != nil { if err != nil {
log.Printf("[rejoin] auth failed: %v, retrying in 5s", err) log.Printf("[rejoin] auth failed: %v, retrying in 5s", err)
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)
@@ -139,6 +161,7 @@ func main() {
} }
roomToken = newRoomToken roomToken = newRoomToken
accessToken = newAccessToken accessToken = newAccessToken
log.Printf("[rejoin] refreshed token for room=%s", roomID) serverURL = newServerURL
log.Printf("[rejoin] refreshed token for room=%s server=%s", roomID, serverURL)
} }
} }
+4 -3
View File
@@ -322,12 +322,12 @@ func runWBStream(link, name, mode string, fps, batch int,
onConnected func(tunnel.DataTunnel), onConnected func(tunnel.DataTunnel),
onCandidate func(int, string), onCandidate func(int, string),
) { ) {
id := strings.TrimPrefix(strings.TrimSpace(link), "wbstream://") id := wbstream.ParseRoomID(link)
roomID, roomToken, _, err := wbstream.AuthAndGetToken(nil, id, name) roomID, roomToken, _, serverURL, err := wbstream.AuthAndGetToken(nil, id, name)
if err != nil { if err != nil {
log.Fatalf("[wb] auth: %v", err) log.Fatalf("[wb] auth: %v", err)
} }
log.Printf("[wb] room=%s mode=%s", roomID, mode) log.Printf("[wb] room=%s server=%s mode=%s", roomID, serverURL, mode)
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(roomID)) obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(roomID))
if err != nil { if err != nil {
@@ -336,6 +336,7 @@ func runWBStream(link, name, mode string, fps, batch int,
sess := wbstream.NewSession(wbstream.SessionConfig{ sess := wbstream.NewSession(wbstream.SessionConfig{
RoomToken: roomToken, RoomToken: roomToken,
ServerURL: serverURL,
DisplayName: name, DisplayName: name,
TunnelMode: mode, TunnelMode: mode,
Obfuscator: obf, Obfuscator: obf,
+31 -1
View File
@@ -9,7 +9,7 @@ import (
"strings" "strings"
) )
const UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36" 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"
func LoadCookies(path string) string { func LoadCookies(path string) string {
data, err := os.ReadFile(path) data, err := os.ReadFile(path)
@@ -30,6 +30,36 @@ func LoadCookies(path string) string {
return strings.Join(parts, "; ") return strings.Join(parts, "; ")
} }
func CookieValue(cookieHeader, name string) string {
for _, part := range strings.Split(cookieHeader, ";") {
part = strings.TrimSpace(part)
eq := strings.IndexByte(part, '=')
if eq != -1 && part[:eq] == name {
return part[eq+1:]
}
}
return ""
}
func FilterCookies(cookieHeader string, allow []string) string {
allowed := make(map[string]struct{}, len(allow))
for _, n := range allow {
allowed[n] = struct{}{}
}
var out []string
for _, part := range strings.Split(cookieHeader, ";") {
trimmed := strings.TrimSpace(part)
eq := strings.IndexByte(trimmed, '=')
if eq == -1 {
continue
}
if _, ok := allowed[trimmed[:eq]]; ok {
out = append(out, trimmed)
}
}
return strings.Join(out, "; ")
}
func HttpGet(endpoint string) ([]byte, error) { func HttpGet(endpoint string) ([]byte, error) {
req, _ := http.NewRequest("GET", endpoint, nil) req, _ := http.NewRequest("GET", endpoint, nil)
req.Header.Set("User-Agent", UserAgent) req.Header.Set("User-Agent", UserAgent)
@@ -61,12 +61,13 @@ func (j *WBStreamHeadlessJoiner) RunWithParams(jsonParams string) {
j.logFn("wbstream-joiner: room=%s name=%s vp8Fps=%d vp8Batch=%d", params.RoomID, params.DisplayName, params.VP8FPS, params.VP8Batch) j.logFn("wbstream-joiner: room=%s name=%s vp8Fps=%d vp8Batch=%d", params.RoomID, params.DisplayName, params.VP8FPS, params.VP8Batch)
j.Status.EmitStatus(common.StatusConnecting) j.Status.EmitStatus(common.StatusConnecting)
roomID, roomToken, _, err := wbstream.AuthAndGetToken(httpClient, params.RoomID, params.DisplayName) roomID, roomToken, _, serverURL, err := wbstream.AuthAndGetToken(httpClient, params.RoomID, params.DisplayName)
if err != nil { if err != nil {
j.logFn("wbstream-joiner: auth failed: %v", err) j.logFn("wbstream-joiner: auth failed: %v", err)
j.Status.EmitStatusError("auth: " + err.Error()) j.Status.EmitStatusError("auth: " + err.Error())
return return
} }
j.logFn("wbstream-joiner: server=%s", serverURL)
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(roomID)) obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(roomID))
if err != nil { if err != nil {
@@ -85,6 +86,7 @@ func (j *WBStreamHeadlessJoiner) RunWithParams(jsonParams string) {
sess := wbstream.NewSession(wbstream.SessionConfig{ sess := wbstream.NewSession(wbstream.SessionConfig{
RoomToken: roomToken, RoomToken: roomToken,
ServerURL: serverURL,
DisplayName: params.DisplayName, DisplayName: params.DisplayName,
TunnelMode: params.TunnelMode, TunnelMode: params.TunnelMode,
Obfuscator: obf, Obfuscator: obf,
-4
View File
@@ -18,10 +18,6 @@ var vp8Keepalive = []byte{
0x99, 0x84, 0x88, 0xfc, 0x99, 0x84, 0x88, 0xfc,
} }
// vp8Interframe is a valid VP8 P-frame header. SFUs that VP8-validate forwarded
// packets accept payloads following a P-frame header much more loosely than
// after a keyframe header, so data frames use this prefix while keepalives keep
// the keyframe-shaped vp8Keepalive prefix.
var vp8Interframe = []byte{ var vp8Interframe = []byte{
0xb1, 0x01, 0x00, 0x08, 0x11, 0x18, 0x00, 0x18, 0xb1, 0x01, 0x00, 0x08, 0x11, 0x18, 0x00, 0x18,
0x00, 0x18, 0x58, 0x2f, 0xf4, 0x00, 0x08, 0x00, 0x00, 0x18, 0x58, 0x2f, 0xf4, 0x00, 0x08, 0x00,
+156 -24
View File
@@ -2,6 +2,7 @@ package wbstream
import ( import (
"bytes" "bytes"
"crypto/rand"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@@ -14,10 +15,33 @@ import (
const ( const (
APIBase = "https://stream.wb.ru" APIBase = "https://stream.wb.ru"
WSURL = "wss://rtc-el-01.wb.ru"
Origin = "https://stream.wb.ru" Origin = "https://stream.wb.ru"
) )
// ParseRoomID accepts a bare room id, a wbstream://<id> link, or a
// https://stream.wb.ru/room/<id> URL and returns the room id.
func ParseRoomID(input string) string {
trimmed := strings.TrimSpace(input)
if trimmed == "" {
return ""
}
if rest, ok := strings.CutPrefix(trimmed, "wbstream://"); ok {
return strings.Trim(rest, "/")
}
if strings.HasPrefix(trimmed, "http://") || strings.HasPrefix(trimmed, "https://") {
u, err := url.Parse(trimmed)
if err == nil {
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
for i := 0; i < len(parts)-1; i++ {
if parts[i] == "room" && parts[i+1] != "" {
return parts[i+1]
}
}
}
}
return strings.Trim(trimmed, "/")
}
type guestRegisterRequest struct { type guestRegisterRequest struct {
DisplayName string `json:"displayName"` DisplayName string `json:"displayName"`
Device guestDeviceCfg `json:"device"` Device guestDeviceCfg `json:"device"`
@@ -41,8 +65,9 @@ type createRoomResponse struct {
RoomID string `json:"roomId"` RoomID string `json:"roomId"`
} }
type tokenResponse struct { type connectionDetailsResponse struct {
RoomToken string `json:"roomToken"` RoomToken string `json:"roomToken"`
ServerURL string `json:"serverUrl"`
} }
func httpDo(client *http.Client, req *http.Request) (*http.Response, error) { func httpDo(client *http.Client, req *http.Request) (*http.Response, error) {
@@ -53,6 +78,38 @@ func httpDo(client *http.Client, req *http.Request) (*http.Response, error) {
return client.Do(req) return client.Do(req)
} }
type cookieTransport struct {
base http.RoundTripper
cookie string
}
func (t *cookieTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Cookie", t.cookie)
base := t.base
if base == nil {
base = http.DefaultTransport
}
return base.RoundTrip(req)
}
func clientWithCookies(client *http.Client, cookieHeader string) *http.Client {
if cookieHeader == "" {
return client
}
if client == nil {
client = &http.Client{}
}
wrapped := *client
wrapped.Transport = &cookieTransport{base: client.Transport, cookie: cookieHeader}
return &wrapped
}
func setBearer(req *http.Request, accessToken string) {
if accessToken != "" {
req.Header.Set("Authorization", "Bearer "+accessToken)
}
}
func RegisterGuest(client *http.Client, displayName string) (string, error) { func RegisterGuest(client *http.Client, displayName string) (string, error) {
body, _ := json.Marshal(guestRegisterRequest{ body, _ := json.Marshal(guestRegisterRequest{
DisplayName: displayName, DisplayName: displayName,
@@ -94,7 +151,7 @@ func CreateRoom(client *http.Client, accessToken string) (string, error) {
return "", err return "", err
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+accessToken) setBearer(req, accessToken)
resp, err := httpDo(client, req) resp, err := httpDo(client, req)
if err != nil { if err != nil {
@@ -120,7 +177,7 @@ func JoinRoom(client *http.Client, accessToken, roomID string) error {
return err return err
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+accessToken) setBearer(req, accessToken)
resp, err := httpDo(client, req) resp, err := httpDo(client, req)
if err != nil { if err != nil {
@@ -134,51 +191,126 @@ func JoinRoom(client *http.Client, accessToken, roomID string) error {
return nil return nil
} }
func GetRoomToken(client *http.Client, accessToken, roomID, displayName string) (string, error) { func GetConnectionDetails(client *http.Client, accessToken, roomID, displayName string) (string, string, error) {
tokenURL := fmt.Sprintf("%s/api-room-manager/api/v1/room/%s/token?deviceType=PARTICIPANT_DEVICE_TYPE_WEB_DESKTOP&displayName=%s", detailsURL := fmt.Sprintf("%s/api-room-manager/v2/room/%s/connection-details?deviceType=PARTICIPANT_DEVICE_TYPE_WEB_DESKTOP&displayName=%s",
APIBase, roomID, url.QueryEscape(displayName)) APIBase, roomID, url.QueryEscape(displayName))
req, err := http.NewRequest(http.MethodGet, tokenURL, nil) req, err := http.NewRequest(http.MethodGet, detailsURL, nil)
if err != nil {
return "", "", err
}
setBearer(req, accessToken)
resp, err := httpDo(client, req)
if err != nil {
return "", "", err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", "", fmt.Errorf("connection-details: status %d: %s", resp.StatusCode, string(raw))
}
var r connectionDetailsResponse
if err := json.Unmarshal(raw, &r); err != nil {
return "", "", fmt.Errorf("connection-details decode: %w", err)
}
return r.RoomToken, r.ServerURL, nil
}
func AuthAndGetToken(client *http.Client, roomID, displayName string) (string, string, string, string, error) {
accessToken, err := RegisterGuest(client, displayName)
if err != nil {
return "", "", "", "", fmt.Errorf("register guest: %w", err)
}
return joinAndGetDetails(client, accessToken, roomID, displayName)
}
func AuthAsLoggedIn(client *http.Client, cookieHeader, accessToken, roomID, displayName string) (string, string, string, string, error) {
if cookieHeader == "" && accessToken == "" {
return "", "", "", "", fmt.Errorf("cookies or access token required for logged-in auth")
}
client = clientWithCookies(client, cookieHeader)
return joinAndGetDetails(client, accessToken, roomID, displayName)
}
var WBStreamCookieAllowlist = []string{
"wbx-refresh",
"x_wbaas_token",
"_wbauid",
"wbx-validation-key",
}
type slideV3Response struct {
Payload struct {
AccessToken string `json:"access_token"`
} `json:"payload"`
}
func newRequestID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "00000000-0000-0000-0000-000000000000"
}
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
func RefreshAccessToken(client *http.Client, cookieHeader, deviceID string) (string, error) {
req, err := http.NewRequest(http.MethodPost, "https://auth-stream.wb.ru/v2/auth/slide-v3", bytes.NewReader(nil))
if err != nil { if err != nil {
return "", err return "", err
} }
req.Header.Set("Authorization", "Bearer "+accessToken) if deviceID == "" {
deviceID = newRequestID()
}
req.Header.Set("wb-apptype", "web")
req.Header.Set("X-Real-IP", "")
req.Header.Set("deviceId", deviceID)
req.Header.Set("X-Request-ID", newRequestID())
req.Header.Set("Origin", Origin)
req.Header.Set("Referer", Origin+"/")
req.Header.Set("Cookie", cookieHeader)
req.Header.Set("User-Agent", common.UserAgent)
resp, err := httpDo(client, req) if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
if err != nil { if err != nil {
return "", err return "", err
} }
defer resp.Body.Close() defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body) raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("get-token: status %d: %s", resp.StatusCode, string(raw)) return "", fmt.Errorf("slide-v3: status %d: %s", resp.StatusCode, string(raw))
} }
var r slideV3Response
var r tokenResponse
if err := json.Unmarshal(raw, &r); err != nil { if err := json.Unmarshal(raw, &r); err != nil {
return "", fmt.Errorf("get-token decode: %w", err) return "", fmt.Errorf("slide-v3 decode: %w", err)
} }
return r.RoomToken, nil if r.Payload.AccessToken == "" {
return "", fmt.Errorf("slide-v3: empty access_token in response: %s", string(raw))
}
return r.Payload.AccessToken, nil
} }
func AuthAndGetToken(client *http.Client, roomID, displayName string) (string, string, string, error) { func joinAndGetDetails(client *http.Client, accessToken, roomID, displayName string) (string, string, string, string, error) {
accessToken, err := RegisterGuest(client, displayName) var err error
if err != nil {
return "", "", "", fmt.Errorf("register guest: %w", err)
}
if roomID == "" { if roomID == "" {
roomID, err = CreateRoom(client, accessToken) roomID, err = CreateRoom(client, accessToken)
if err != nil { if err != nil {
return "", "", "", fmt.Errorf("create room: %w", err) return "", "", "", "", fmt.Errorf("create room: %w", err)
} }
} }
if err := JoinRoom(client, accessToken, roomID); err != nil { if err := JoinRoom(client, accessToken, roomID); err != nil {
return "", "", "", fmt.Errorf("join room: %w", err) return "", "", "", "", fmt.Errorf("join room: %w", err)
} }
roomToken, err := GetRoomToken(client, accessToken, roomID, displayName) roomToken, serverURL, err := GetConnectionDetails(client, accessToken, roomID, displayName)
if err != nil { if err != nil {
return "", "", "", fmt.Errorf("get token: %w", err) return "", "", "", "", fmt.Errorf("get connection details: %w", err)
} }
return roomID, roomToken, accessToken, nil return roomID, roomToken, accessToken, serverURL, nil
} }
func KickParticipant(client *http.Client, accessToken, roomID, participantID string) error { func KickParticipant(client *http.Client, accessToken, roomID, participantID string) error {
+2 -1
View File
@@ -31,6 +31,7 @@ const (
type SessionConfig struct { type SessionConfig struct {
RoomToken string RoomToken string
ServerURL string
DisplayName string DisplayName string
TunnelMode string TunnelMode string
Obfuscator *tunnel.TunnelObfuscator Obfuscator *tunnel.TunnelObfuscator
@@ -84,7 +85,7 @@ func (s *Session) Done() <-chan struct{} { return s.done }
func (s *Session) Start() error { func (s *Session) Start() error {
s.lk = livekit.NewClient(livekit.Config{ s.lk = livekit.NewClient(livekit.Config{
ServerURL: WSURL, ServerURL: s.cfg.ServerURL,
Token: s.cfg.RoomToken, Token: s.cfg.RoomToken,
Origin: Origin, Origin: Origin,
UserAgent: common.UserAgent, UserAgent: common.UserAgent,