revert wbstream refresh logic
This commit is contained in:
1 parent
98312a5965
commit
ad8635fd91
11 files changed
+52
-291
No files matched your search
@@ -24,11 +24,12 @@ 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 WBSTREAM_API_ORIGIN = 'https://stream.wb.ru';
|
||||
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 WBSTREAM_ACCESS_TOKEN_COOKIE = 'wb_access_token';
|
||||
export const BITRIX_SESSION_COOKIE = 'BITRIX_SM_UIDH';
|
||||
export const BITRIX_AUTH_NET_HOST = 'https://auth2.bitrix24.net';
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
YANDEX_COOKIE_DOMAINS,
|
||||
DION_COOKIE_DOMAINS,
|
||||
WBSTREAM_COOKIE_DOMAINS,
|
||||
WBSTREAM_API_ORIGIN,
|
||||
WBSTREAM_ACCESS_TOKEN_COOKIE,
|
||||
BITRIX_COOKIE_DOMAINS,
|
||||
BITRIX_SESSION_COOKIE,
|
||||
BITRIX_AUTH_NET_HOST,
|
||||
@@ -242,25 +244,28 @@ export class CookieStore {
|
||||
return buildStoredZip(entries);
|
||||
}
|
||||
|
||||
async setWBStreamDeviceId(id: string): Promise<void> {
|
||||
if (!id) return;
|
||||
async setWBStreamAccessToken(token: string): Promise<void> {
|
||||
if (!token) 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;
|
||||
const existing = await ses.cookies.get({
|
||||
url: `${WBSTREAM_API_ORIGIN}/`,
|
||||
name: WBSTREAM_ACCESS_TOKEN_COOKIE,
|
||||
});
|
||||
if (existing.length > 0 && existing[0].value === token) return;
|
||||
try {
|
||||
await ses.cookies.set({
|
||||
url: 'https://stream.wb.ru/',
|
||||
name: '__wb_device_id',
|
||||
value: id,
|
||||
url: `${WBSTREAM_API_ORIGIN}/`,
|
||||
name: WBSTREAM_ACCESS_TOKEN_COOKIE,
|
||||
value: token,
|
||||
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}`);
|
||||
console.log(`[wb-access-token] persisted len=${token.length}`);
|
||||
} catch (err) {
|
||||
console.log(`[wb-device-id] failed to persist:`, err);
|
||||
console.log(`[wb-access-token] failed to persist:`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,10 +157,10 @@ export class HeadlessLauncher {
|
||||
const dionCookieFile = platform === Platform.Dion ? new DionCookieFile(cookiesPath) : null;
|
||||
const fileHasSession =
|
||||
platform === Platform.WBStream
|
||||
? await cookieFileHasCookie(cookiesPath, config.refreshCookie)
|
||||
? await cookieFileHasCookie(cookiesPath, config.authCookie)
|
||||
: dionCookieFile != null && (await dionCookieFile.hasSession());
|
||||
let cookies = await this.cookies.getCookiesForDomains(config.cookieDomains);
|
||||
const needsLogin = !fileHasSession && !cookies.some((c) => c.name === config.refreshCookie);
|
||||
const needsLogin = !fileHasSession && !cookies.some((c) => c.name === config.authCookie);
|
||||
if (needsLogin) {
|
||||
if (tab.isBot) {
|
||||
const reply = `Please log into ${config.platformName} in the creator app first, then try again.`;
|
||||
@@ -219,7 +219,6 @@ export class HeadlessLauncher {
|
||||
if (dionCookieFile) await dionCookieFile.clearTokens();
|
||||
if (platform === Platform.WBStream) await fs.unlink(cookiesPath).catch(() => {});
|
||||
await this.cookies.clearAuthCookies(config.cookieDomains, config.authCookie);
|
||||
await this.cookies.clearAuthCookies(config.cookieDomains, config.refreshCookie);
|
||||
if (this.host.getTab(tabId) === tab) this.startHeadless(tabId, platform, args);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -11,13 +11,12 @@ import {
|
||||
VK_AUTH_COOKIE,
|
||||
YANDEX_AUTH_COOKIE,
|
||||
DION_AUTH_COOKIE,
|
||||
WBSTREAM_AUTH_COOKIE,
|
||||
WBSTREAM_ACCESS_TOKEN_COOKIE,
|
||||
} from '../constants';
|
||||
|
||||
export interface PlatformConfig {
|
||||
tunnelMode: TunnelMode;
|
||||
authCookie: string;
|
||||
refreshCookie: string;
|
||||
loginUrl: string;
|
||||
cookieDomains: string[];
|
||||
platformName: string;
|
||||
@@ -31,7 +30,6 @@ 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',
|
||||
@@ -43,7 +41,6 @@ export const PLATFORM_CONFIG: Partial<Record<Platform, PlatformConfig>> = {
|
||||
[Platform.Telemost]: {
|
||||
tunnelMode: TunnelMode.HeadlessTelemost,
|
||||
authCookie: YANDEX_AUTH_COOKIE,
|
||||
refreshCookie: YANDEX_AUTH_COOKIE,
|
||||
loginUrl: YANDEX_LOGIN_URL,
|
||||
cookieDomains: YANDEX_COOKIE_DOMAINS,
|
||||
platformName: 'Yandex',
|
||||
@@ -55,7 +52,6 @@ export const PLATFORM_CONFIG: Partial<Record<Platform, PlatformConfig>> = {
|
||||
[Platform.Dion]: {
|
||||
tunnelMode: TunnelMode.HeadlessDion,
|
||||
authCookie: DION_AUTH_COOKIE,
|
||||
refreshCookie: DION_AUTH_COOKIE,
|
||||
loginUrl: DION_LOGIN_URL,
|
||||
cookieDomains: DION_COOKIE_DOMAINS,
|
||||
platformName: 'DION',
|
||||
@@ -66,14 +62,13 @@ export const PLATFORM_CONFIG: Partial<Record<Platform, PlatformConfig>> = {
|
||||
},
|
||||
[Platform.WBStream]: {
|
||||
tunnelMode: TunnelMode.HeadlessWBStream,
|
||||
authCookie: WBSTREAM_AUTH_COOKIE,
|
||||
refreshCookie: 'wbx-refresh',
|
||||
authCookie: WBSTREAM_ACCESS_TOKEN_COOKIE,
|
||||
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'],
|
||||
loginWaitCookies: [WBSTREAM_ACCESS_TOKEN_COOKIE],
|
||||
},
|
||||
};
|
||||
@@ -239,7 +239,7 @@ export class TabManager {
|
||||
return this.cookies.buildCookiesZip();
|
||||
}
|
||||
|
||||
setWBStreamDeviceId(id: string): Promise<void> {
|
||||
return this.cookies.setWBStreamDeviceId(id);
|
||||
setWBStreamAccessToken(token: string): Promise<void> {
|
||||
return this.cookies.setWBStreamAccessToken(token);
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,3 @@ export function extractTaggedCallLink(msg: string, platform: Platform): { tabId:
|
||||
if (!match) return null;
|
||||
return { tabId: match[1].trim(), link: match[2].trim() };
|
||||
}
|
||||
|
||||
export function parseWBDeviceId(msg: string): string | null {
|
||||
const match = msg.match(/\[WB_DEVICE_ID\]\s+(\S+)/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
@@ -3,9 +3,15 @@ import * as path from 'path';
|
||||
import { TabManager } from './tab-manager';
|
||||
import { VkAutoclick } from '../autoclick/vk';
|
||||
import { TelemostAutoclick } from '../autoclick/telemost';
|
||||
import { SESSION_PARTITION, USER_AGENT, WINDOW_WIDTH, WINDOW_HEIGHT } from '../constants';
|
||||
import {
|
||||
SESSION_PARTITION,
|
||||
USER_AGENT,
|
||||
WINDOW_WIDTH,
|
||||
WINDOW_HEIGHT,
|
||||
WBSTREAM_API_ORIGIN,
|
||||
} from '../constants';
|
||||
import { Platform } from '../types';
|
||||
import { parseCallStatus, extractTaggedCallLink, parseWBDeviceId } from './util/log-tags';
|
||||
import { parseCallStatus, extractTaggedCallLink } from './util/log-tags';
|
||||
|
||||
function stripCSP(ses: Session): void {
|
||||
ses.webRequest.onHeadersReceived((details, callback) => {
|
||||
@@ -25,6 +31,14 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
|
||||
ses.setPermissionCheckHandler(() => true);
|
||||
ses.setUserAgent(USER_AGENT);
|
||||
|
||||
ses.webRequest.onBeforeSendHeaders({ urls: [`${WBSTREAM_API_ORIGIN}/*`] }, (details, callback) => {
|
||||
const authorization = details.requestHeaders['Authorization'] ?? details.requestHeaders['authorization'];
|
||||
if (typeof authorization === 'string' && authorization.startsWith('Bearer ')) {
|
||||
tabManager.setWBStreamAccessToken(authorization.slice('Bearer '.length)).catch(() => {});
|
||||
}
|
||||
callback({ requestHeaders: details.requestHeaders });
|
||||
});
|
||||
|
||||
app.on('session-created', stripCSP);
|
||||
|
||||
const win = new BrowserWindow({
|
||||
@@ -46,19 +60,6 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
|
||||
|
||||
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) => {
|
||||
wvContents.on('before-input-event', (_e, input) => {
|
||||
if (input.key === 'F12') wvContents.openDevTools();
|
||||
@@ -72,13 +73,6 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
|
||||
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) => {
|
||||
const wcId = wvContents.id;
|
||||
if (!autoclickers.has(wcId)) {
|
||||
@@ -109,11 +103,6 @@ export function createWindow(tabManager: TabManager): BrowserWindow {
|
||||
handleBotCallLink(tabManager, msg, Platform.VK);
|
||||
handleBotCallLink(tabManager, msg, Platform.Telemost);
|
||||
|
||||
const deviceId = parseWBDeviceId(msg);
|
||||
if (deviceId) {
|
||||
tabManager.setWBStreamDeviceId(deviceId).catch(() => {});
|
||||
}
|
||||
|
||||
const callStatus = parseCallStatus(msg);
|
||||
if (callStatus) {
|
||||
console.log('[MAIN] Cached status for', callStatus.tabId, ':', callStatus.status);
|
||||
|
||||
+3
-3
@@ -60,7 +60,7 @@
|
||||
3. Нажмите **Export Cookies** - получится `cookies.zip` с файлами `cookies-vk.json`, `cookies-yandex.json`, `cookies-wbstream.json`, `cookies-dion.json`, `cookies-bitrix.json`
|
||||
4. Распакуйте и скопируйте нужные файлы на сервер
|
||||
|
||||
`cookies-dion.json`, `cookies-bitrix.json` и `cookies-wbstream.json` creator перезаписывает на ходу, когда обновляет токен или перелогинивается - эти три файла должны быть доступны процессу на запись. VK и Telemost только читаются.
|
||||
`cookies-dion.json` и `cookies-bitrix.json` creator перезаписывает на ходу, когда обновляет токен или перелогинивается - эти два файла должны быть доступны процессу на запись. VK, Telemost и WB Stream только читаются.
|
||||
|
||||
> **Bitrix:** портал, зарегистрированный на `gmail.com`, падает при создании звонка с `403 invalid signature`. Заводите портал на другой почте: проверены `mail.ru` и `onetimemail.com.au`.
|
||||
|
||||
@@ -363,7 +363,7 @@ curl -L https://raw.githubusercontent.com/kulikov0/whitelist-bypass/main/headles
|
||||
# отредактируйте .env: VK_TOKEN, VK_GROUP_ID, VK_USER_IDS
|
||||
# положите рядом cookies-vk.json, cookies-yandex.json, cookies-wbstream.json, cookies-dion.json, cookies-bitrix.json
|
||||
# (для платформ, которые не используете - создайте файл с содержимым `[]`)
|
||||
sudo chown 999:999 cookies-dion.json cookies-bitrix.json cookies-wbstream.json
|
||||
sudo chown 999:999 cookies-dion.json cookies-bitrix.json
|
||||
docker compose up -d
|
||||
docker compose logs -f
|
||||
```
|
||||
@@ -393,7 +393,7 @@ docker compose pull && docker compose up -d
|
||||
| `ALLOW_PRIVATE_DST` | нет | `0` | `--allow-private-dst`, включается значением `1` |
|
||||
| `ALLOW_LOOPBACK_DST` | нет | `0` | `--allow-loopback`, включается значением `1`. В контейнере это loopback самого контейнера, если не задан `network_mode: host` |
|
||||
|
||||
> `cookies-dion.json`, `cookies-bitrix.json` и `cookies-wbstream.json` монтируются без `:ro` - creator перезаписывает их при обновлении токена, поэтому на хосте они должны принадлежать uid 999 (иначе `save cookies failed: permission denied`). VK и Telemost только читаются.
|
||||
> `cookies-dion.json` и `cookies-bitrix.json` монтируются без `:ro` - creator перезаписывает их при обновлении токена, поэтому на хосте они должны принадлежать uid 999 (иначе `save cookies failed: permission denied`). VK, Telemost и WB Stream монтируются с `:ro`.
|
||||
|
||||
> Если WebRTC-туннель не доходит через сетевой бридж Docker (UDP может отбрасываться), добавьте в `docker-compose.yml` строку `network_mode: host` под сервисом `bot`.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ services:
|
||||
# don't use, or remove the corresponding line.
|
||||
- ./cookies-vk.json:/data/cookies-vk.json:ro
|
||||
- ./cookies-yandex.json:/data/cookies-yandex.json:ro
|
||||
- ./cookies-wbstream.json:/data/cookies-wbstream.json
|
||||
- ./cookies-wbstream.json:/data/cookies-wbstream.json:ro
|
||||
- ./cookies-dion.json:/data/cookies-dion.json
|
||||
- ./cookies-bitrix.json:/data/cookies-bitrix.json
|
||||
# Per-session creator logs persist here.
|
||||
|
||||
@@ -67,59 +67,14 @@ func main() {
|
||||
log.Fatalf("[auth] --cookies is required")
|
||||
}
|
||||
rawCookies := common.LoadCookies(*cookiesPath)
|
||||
deviceID := common.CookieValue(rawCookies, "__wb_device_id")
|
||||
cookieHeader := common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
|
||||
persistEntries := func(updates map[string]string) {
|
||||
if len(updates) == 0 {
|
||||
return
|
||||
}
|
||||
if werr := common.UpdateCookieFile(*cookiesPath, updates); werr != nil {
|
||||
log.Printf("[auth] warn: persist cookie file entries: %v", werr)
|
||||
return
|
||||
}
|
||||
rawCookies = common.LoadCookies(*cookiesPath)
|
||||
cookieHeader = common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
|
||||
log.Printf("[auth] persisted %d cookie file entries", len(updates))
|
||||
}
|
||||
refreshBearer := func() (string, error) {
|
||||
if deviceID == "" {
|
||||
return "", fmt.Errorf("cookies file is missing __wb_device_id, re-export via creator-app")
|
||||
}
|
||||
token, rotated, refreshErr := wbstream.RefreshAccessToken(nil, cookieHeader, deviceID)
|
||||
if refreshErr != nil {
|
||||
return "", refreshErr
|
||||
}
|
||||
updates := make(map[string]string, len(rotated)+1)
|
||||
for name, value := range rotated {
|
||||
updates[name] = value
|
||||
}
|
||||
updates[wbstream.AccessTokenEntry] = token
|
||||
persistEntries(updates)
|
||||
return token, nil
|
||||
}
|
||||
bearer := common.CookieValue(rawCookies, wbstream.AccessTokenEntry)
|
||||
if bearer == "" {
|
||||
var refreshErr error
|
||||
bearer, refreshErr = refreshBearer()
|
||||
if refreshErr != nil {
|
||||
common.EmitAuthErrorFor(refreshErr)
|
||||
log.Fatalf("[auth] slide-v3 refresh: %v", refreshErr)
|
||||
}
|
||||
log.Printf("[auth] bearer minted via slide-v3 len=%d", len(bearer))
|
||||
} else {
|
||||
log.Printf("[auth] bearer loaded from cookies file len=%d", len(bearer))
|
||||
common.EmitAuthError(common.AuthErrorSessionExpired)
|
||||
log.Fatalf("[auth] cookies file has no %s, log into WB Stream in the creator app and export the cookies again", wbstream.AccessTokenEntry)
|
||||
}
|
||||
log.Printf("[auth] bearer loaded from cookies file len=%d", len(bearer))
|
||||
requestedRoom := wbstream.ParseRoomID(*roomFlag)
|
||||
roomID, roomToken, accessToken, serverURL, err := wbstream.AuthAsLoggedIn(nil, cookieHeader, bearer, requestedRoom, *displayName)
|
||||
if err != nil {
|
||||
log.Printf("[auth] stored bearer rejected: %v, refreshing", err)
|
||||
bearer, err = refreshBearer()
|
||||
if err != nil {
|
||||
common.EmitAuthErrorFor(err)
|
||||
log.Fatalf("[auth] slide-v3 refresh: %v", err)
|
||||
}
|
||||
roomID, roomToken, accessToken, serverURL, err = wbstream.AuthAsLoggedIn(nil, cookieHeader, bearer, requestedRoom, *displayName)
|
||||
}
|
||||
roomID, roomToken, accessToken, serverURL, err := wbstream.AuthAsLoggedIn(nil, bearer, requestedRoom, *displayName)
|
||||
if err != nil {
|
||||
common.EmitAuthErrorFor(err)
|
||||
log.Fatalf("[auth] %v", err)
|
||||
@@ -206,15 +161,9 @@ func main() {
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
_, newRoomToken, newAccessToken, newServerURL, err := wbstream.AuthAsLoggedIn(nil, cookieHeader, bearer, roomID, *displayName)
|
||||
_, newRoomToken, newAccessToken, newServerURL, err := wbstream.AuthAsLoggedIn(nil, bearer, roomID, *displayName)
|
||||
if err != nil {
|
||||
log.Printf("[rejoin] auth failed: %v, refreshing bearer", err)
|
||||
newBearer, refreshErr := refreshBearer()
|
||||
if refreshErr != nil {
|
||||
log.Printf("[rejoin] slide-v3 refresh failed: %v, retrying in 5s", refreshErr)
|
||||
} else {
|
||||
bearer = newBearer
|
||||
}
|
||||
log.Printf("[rejoin] auth failed: %v, retrying in 5s", err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
+3
-175
@@ -2,7 +2,6 @@ package wbstream
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -84,32 +83,6 @@ func httpDo(client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
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 = headless.ChromeWindows.HTTPClient().Transport
|
||||
}
|
||||
return base.RoundTrip(req)
|
||||
}
|
||||
|
||||
func clientWithCookies(client *http.Client, cookieHeader string) *http.Client {
|
||||
if cookieHeader == "" {
|
||||
return client
|
||||
}
|
||||
if client == nil {
|
||||
client = headless.ChromeWindows.HTTPClient()
|
||||
}
|
||||
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)
|
||||
@@ -231,21 +204,13 @@ func AuthAndGetToken(client *http.Client, roomID, displayName string) (string, s
|
||||
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")
|
||||
func AuthAsLoggedIn(client *http.Client, accessToken, roomID, displayName string) (string, string, string, string, error) {
|
||||
if accessToken == "" {
|
||||
return "", "", "", "", fmt.Errorf("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",
|
||||
}
|
||||
|
||||
var ModeratorPermissions = []string{
|
||||
"ROOM_PERMISSION_SEND_CHAT",
|
||||
"ROOM_PERMISSION_SHARE_AUDIO",
|
||||
@@ -257,143 +222,6 @@ var ModeratorPermissions = []string{
|
||||
"ROOM_PERMISSION_LOCAL_RECORD",
|
||||
}
|
||||
|
||||
type slideV3Response struct {
|
||||
Payload struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
Sticker string `json:"sticker"`
|
||||
} `json:"payload"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type slideV3ConfirmResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
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, map[string]string, error) {
|
||||
if deviceID == "" {
|
||||
return "", nil, fmt.Errorf("slide-v3: device id is required")
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, "https://auth-stream.wb.ru/v2/auth/slide-v3", bytes.NewReader(nil))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
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)
|
||||
|
||||
resp, err := httpDo(client, req)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
rotated := make(map[string]string)
|
||||
for _, ck := range resp.Cookies() {
|
||||
if ck.Value != "" {
|
||||
rotated[ck.Name] = ck.Value
|
||||
}
|
||||
}
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", nil, fmt.Errorf("slide-v3: status %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
var r slideV3Response
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return "", nil, fmt.Errorf("slide-v3 decode: %w", err)
|
||||
}
|
||||
if r.Error != "" {
|
||||
return "", nil, fmt.Errorf("slide-v3: %s", string(raw))
|
||||
}
|
||||
if r.Payload.AccessToken == "" {
|
||||
return "", nil, fmt.Errorf("slide-v3: empty access_token in response: %s", string(raw))
|
||||
}
|
||||
if err := confirmRefresh(client, mergeCookies(cookieHeader, rotated), deviceID, r.Payload.Sticker); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return r.Payload.AccessToken, rotated, nil
|
||||
}
|
||||
|
||||
func confirmRefresh(client *http.Client, cookieHeader, deviceID, sticker string) error {
|
||||
if sticker == "" {
|
||||
return fmt.Errorf("slide-v3-confirm: slide-v3 returned no sticker")
|
||||
}
|
||||
body, err := json.Marshal(map[string]string{"sticker": sticker})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, "https://auth-stream.wb.ru/v2/auth/slide-v3-confirm", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
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)
|
||||
|
||||
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("slide-v3-confirm: status %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
var confirmed slideV3ConfirmResponse
|
||||
if err := json.Unmarshal(raw, &confirmed); err != nil {
|
||||
return fmt.Errorf("slide-v3-confirm decode: %w", err)
|
||||
}
|
||||
if confirmed.Error != "" {
|
||||
return fmt.Errorf("slide-v3-confirm: %s", confirmed.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mergeCookies(cookieHeader string, updates map[string]string) string {
|
||||
if len(updates) == 0 {
|
||||
return cookieHeader
|
||||
}
|
||||
replaced := make(map[string]bool, len(updates))
|
||||
var merged []string
|
||||
for _, part := range strings.Split(cookieHeader, ";") {
|
||||
trimmed := strings.TrimSpace(part)
|
||||
eq := strings.IndexByte(trimmed, '=')
|
||||
if eq == -1 {
|
||||
continue
|
||||
}
|
||||
name := trimmed[:eq]
|
||||
if value, ok := updates[name]; ok {
|
||||
merged = append(merged, name+"="+value)
|
||||
replaced[name] = true
|
||||
continue
|
||||
}
|
||||
merged = append(merged, trimmed)
|
||||
}
|
||||
for name, value := range updates {
|
||||
if !replaced[name] {
|
||||
merged = append(merged, name+"="+value)
|
||||
}
|
||||
}
|
||||
return strings.Join(merged, "; ")
|
||||
}
|
||||
|
||||
func joinAndGetDetails(client *http.Client, accessToken, roomID, displayName string) (string, string, string, string, error) {
|
||||
var err error
|
||||
if roomID == "" {
|
||||
|
||||
Reference in new issue
Block a user