fix wbstream token rotation
This commit is contained in:
1 parent
ba84102774
commit
76e2d8b1cf
3 files changed
+149
-27
No files matched your search
@@ -34,6 +34,17 @@ function parseAuthError(msg: string): AuthErrorKind | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function cookieFileHasCookie(filePath: string, name: string | undefined): Promise<boolean> {
|
||||||
|
if (!name) return false;
|
||||||
|
try {
|
||||||
|
const raw = await fs.readFile(filePath, 'utf8');
|
||||||
|
const entries = JSON.parse(raw) as Array<{ name?: string; value?: string }>;
|
||||||
|
return Array.isArray(entries) && entries.some((entry) => entry.name === name && !!entry.value);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class HeadlessLauncher {
|
export class HeadlessLauncher {
|
||||||
private relayPath: string;
|
private relayPath: string;
|
||||||
private bitrixPath: string;
|
private bitrixPath: string;
|
||||||
@@ -139,7 +150,10 @@ export class HeadlessLauncher {
|
|||||||
tab.tunnelMode = config.tunnelMode;
|
tab.tunnelMode = config.tunnelMode;
|
||||||
const cookiesPath = this.cookies.cookieFilePath(platform);
|
const cookiesPath = this.cookies.cookieFilePath(platform);
|
||||||
const dionCookieFile = platform === Platform.Dion ? new DionCookieFile(cookiesPath) : null;
|
const dionCookieFile = platform === Platform.Dion ? new DionCookieFile(cookiesPath) : null;
|
||||||
const fileHasSession = dionCookieFile != null && await dionCookieFile.hasSession();
|
const fileHasSession =
|
||||||
|
platform === Platform.WBStream
|
||||||
|
? await cookieFileHasCookie(cookiesPath, config.refreshCookie)
|
||||||
|
: dionCookieFile != null && (await dionCookieFile.hasSession());
|
||||||
let cookies = await this.cookies.getCookiesForDomains(config.cookieDomains);
|
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.refreshCookie);
|
||||||
if (needsLogin) {
|
if (needsLogin) {
|
||||||
@@ -198,7 +212,9 @@ export class HeadlessLauncher {
|
|||||||
}
|
}
|
||||||
if (authError === 'expired') {
|
if (authError === 'expired') {
|
||||||
if (dionCookieFile) await dionCookieFile.clearTokens();
|
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.authCookie);
|
||||||
|
await this.cookies.clearAuthCookies(config.cookieDomains, config.refreshCookie);
|
||||||
if (this.host.getTab(tabId) === tab) this.startHeadless(tabId, platform, args);
|
if (this.host.getTab(tabId) === tab) this.startHeadless(tabId, platform, args);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
+48
-23
@@ -65,31 +65,58 @@ func main() {
|
|||||||
}
|
}
|
||||||
rawCookies := common.LoadCookies(*cookiesPath)
|
rawCookies := common.LoadCookies(*cookiesPath)
|
||||||
deviceID := common.CookieValue(rawCookies, "__wb_device_id")
|
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 'Export Cookies' button")
|
|
||||||
}
|
|
||||||
cookieHeader := common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
|
cookieHeader := common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
|
||||||
persistCookies := func(rotated map[string]string) {
|
persistEntries := func(updates map[string]string) {
|
||||||
if len(rotated) == 0 {
|
if len(updates) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if werr := common.UpdateCookieFile(*cookiesPath, rotated); werr != nil {
|
if werr := common.UpdateCookieFile(*cookiesPath, updates); werr != nil {
|
||||||
log.Printf("[auth] warn: persist rotated cookies: %v", werr)
|
log.Printf("[auth] warn: persist cookie file entries: %v", werr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
rawCookies = common.LoadCookies(*cookiesPath)
|
rawCookies = common.LoadCookies(*cookiesPath)
|
||||||
cookieHeader = common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
|
cookieHeader = common.FilterCookies(rawCookies, wbstream.WBStreamCookieAllowlist)
|
||||||
log.Printf("[auth] persisted %d rotated cookie(s)", len(rotated))
|
log.Printf("[auth] persisted %d cookie file entries", len(updates))
|
||||||
}
|
}
|
||||||
bearer, rotated, err := wbstream.RefreshAccessToken(nil, cookieHeader, deviceID)
|
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))
|
||||||
|
}
|
||||||
|
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 {
|
if err != nil {
|
||||||
common.EmitAuthErrorFor(err)
|
common.EmitAuthErrorFor(err)
|
||||||
log.Fatalf("[auth] slide-v3 refresh: %v", err)
|
log.Fatalf("[auth] slide-v3 refresh: %v", err)
|
||||||
}
|
}
|
||||||
persistCookies(rotated)
|
roomID, roomToken, accessToken, serverURL, err = wbstream.AuthAsLoggedIn(nil, cookieHeader, bearer, requestedRoom, *displayName)
|
||||||
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 {
|
||||||
common.EmitAuthErrorFor(err)
|
common.EmitAuthErrorFor(err)
|
||||||
log.Fatalf("[auth] %v", err)
|
log.Fatalf("[auth] %v", err)
|
||||||
@@ -176,23 +203,21 @@ func main() {
|
|||||||
}
|
}
|
||||||
time.Sleep(3 * time.Second)
|
time.Sleep(3 * time.Second)
|
||||||
|
|
||||||
newBearer, rotated, 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
|
|
||||||
persistCookies(rotated)
|
|
||||||
_, newRoomToken, newAccessToken, newServerURL, err := wbstream.AuthAsLoggedIn(nil, cookieHeader, bearer, roomID, *displayName)
|
_, 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, refreshing bearer", err)
|
||||||
|
newBearer, refreshErr := refreshBearer()
|
||||||
|
if refreshErr != nil {
|
||||||
|
log.Printf("[rejoin] slide-v3 refresh failed: %v, retrying in 5s", refreshErr)
|
||||||
|
} else {
|
||||||
|
bearer = newBearer
|
||||||
|
}
|
||||||
time.Sleep(5 * time.Second)
|
time.Sleep(5 * time.Second)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
roomToken = newRoomToken
|
roomToken = newRoomToken
|
||||||
accessToken = newAccessToken
|
accessToken = newAccessToken
|
||||||
serverURL = newServerURL
|
serverURL = newServerURL
|
||||||
log.Printf("[rejoin] refreshed token for room=%s server=%s", roomID, serverURL)
|
log.Printf("[rejoin] rejoined room=%s server=%s", roomID, serverURL)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+84
-3
@@ -16,6 +16,7 @@ import (
|
|||||||
const (
|
const (
|
||||||
APIBase = "https://stream.wb.ru"
|
APIBase = "https://stream.wb.ru"
|
||||||
Origin = "https://stream.wb.ru"
|
Origin = "https://stream.wb.ru"
|
||||||
|
AccessTokenEntry = "wb_access_token"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ParseRoomID accepts a bare room id, a wbstream://<id> link, or a
|
// ParseRoomID accepts a bare room id, a wbstream://<id> link, or a
|
||||||
@@ -259,7 +260,13 @@ var ModeratorPermissions = []string{
|
|||||||
type slideV3Response struct {
|
type slideV3Response struct {
|
||||||
Payload struct {
|
Payload struct {
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
|
Sticker string `json:"sticker"`
|
||||||
} `json:"payload"`
|
} `json:"payload"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type slideV3ConfirmResponse struct {
|
||||||
|
Error string `json:"error"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRequestID() string {
|
func newRequestID() string {
|
||||||
@@ -273,13 +280,13 @@ func newRequestID() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func RefreshAccessToken(client *http.Client, cookieHeader, deviceID string) (string, map[string]string, error) {
|
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))
|
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 "", nil, err
|
return "", nil, err
|
||||||
}
|
}
|
||||||
if deviceID == "" {
|
|
||||||
deviceID = newRequestID()
|
|
||||||
}
|
|
||||||
req.Header.Set("wb-apptype", "web")
|
req.Header.Set("wb-apptype", "web")
|
||||||
req.Header.Set("X-Real-IP", "")
|
req.Header.Set("X-Real-IP", "")
|
||||||
req.Header.Set("deviceId", deviceID)
|
req.Header.Set("deviceId", deviceID)
|
||||||
@@ -307,12 +314,86 @@ func RefreshAccessToken(client *http.Client, cookieHeader, deviceID string) (str
|
|||||||
if err := json.Unmarshal(raw, &r); err != nil {
|
if err := json.Unmarshal(raw, &r); err != nil {
|
||||||
return "", nil, fmt.Errorf("slide-v3 decode: %w", err)
|
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 == "" {
|
if r.Payload.AccessToken == "" {
|
||||||
return "", nil, fmt.Errorf("slide-v3: empty access_token in response: %s", string(raw))
|
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
|
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) {
|
func joinAndGetDetails(client *http.Client, accessToken, roomID, displayName string) (string, string, string, string, error) {
|
||||||
var err error
|
var err error
|
||||||
if roomID == "" {
|
if roomID == "" {
|
||||||
|
|||||||
Reference in new issue
Block a user