repair ack, refactor e2e tests

This commit is contained in:
kulikov0 committed 2026-09-12 20:36:19 +02:00
1 parent 9e5357eaa8
commit 88a0b5f1b9
42 files changed
+1732 -792

No files matched your search

+149 -7
View File
@@ -39,13 +39,16 @@ type Client struct {
HTTP *http.Client
LogFn func(string, ...any)
portal string
sessid string
userAgent string
instanceID string
email string
password string
credsPath string
portal string
sessid string
userAgent string
instanceID string
email string
password string
credsPath string
chatID string
conferenceID string
selfUserID string
}
type JoinResult struct {
@@ -69,6 +72,13 @@ type callInfo struct {
GuestLink string
}
type PullConfigResult struct {
WebSocket string
ChannelID string
Hostname string
Revision int
}
type slbRequest struct {
UserToken string `json:"userToken"`
IsOneToOne bool `json:"isOneToOne"`
@@ -115,6 +125,8 @@ func (c *Client) JoinAsGuest(alias, displayName string) (JoinResult, error) {
if err != nil {
return res, err
}
c.chatID = conf.ChatID
c.conferenceID = conf.ConferenceID
userToken, err := c.registerGuest(conf, displayName)
if err != nil {
return res, err
@@ -134,6 +146,7 @@ func (c *Client) JoinAsHost(alias string) (JoinResult, error) {
return res, err
}
c.LogFn("[host] conference chatId=%s conferenceId=%s", conf.ChatID, conf.ConferenceID)
c.chatID = conf.ChatID
callToken, userToken, err := c.getCallToken(conf.ChatID)
if err != nil {
return res, err
@@ -154,6 +167,7 @@ func (c *Client) CreateAndJoin() (JoinResult, string, error) {
if err != nil {
return res, "", err
}
c.chatID = info.ChatID
guestLink := info.GuestLink
if guestLink == "" {
guestLink, err = c.getGuestLink(info.ChatID)
@@ -216,6 +230,15 @@ func (c *Client) restForm(action string, form url.Values) ([]byte, int, error) {
return c.do("POST", endpoint, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
}
func (c *Client) restFormAuthed(action string, form url.Values) ([]byte, int, error) {
endpoint := c.portal + "/rest/" + action + ".json"
if c.sessid != "" {
form.Set("sessid", c.sessid)
endpoint += "?sessid=" + url.QueryEscape(c.sessid)
}
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 != "" {
@@ -426,6 +449,125 @@ func (c *Client) createRoom() (callInfo, error) {
return info, nil
}
func (c *Client) KickUser(userID string) error {
if c.chatID == "" {
return fmt.Errorf("kick: no active chatId")
}
if userID == "" {
return fmt.Errorf("kick: empty userId")
}
form := url.Values{}
form.Set("chatId", c.chatID)
form.Set("userId", userID)
body, status, err := c.withRelogin(func() ([]byte, int, error) {
return c.ajaxAction("im.v2.Chat.deleteUser", form)
})
if err != nil {
return err
}
var out struct {
Status string `json:"status"`
Errors []struct {
Code json.Number `json:"code"`
Message string `json:"message"`
} `json:"errors"`
}
if err := json.Unmarshal(body, &out); err != nil {
return fmt.Errorf("kick: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if len(out.Errors) > 0 {
return fmt.Errorf("kick: chatId=%s userId=%s rejected (status %d, %s %s)", c.chatID, userID, status, out.Errors[0].Code.String(), out.Errors[0].Message)
}
c.LogFn("[kick] removed userId=%s from chatId=%s", userID, c.chatID)
return nil
}
func (c *Client) SelfUserID() (string, error) {
if c.selfUserID != "" {
return c.selfUserID, nil
}
id, err := c.currentUserID()
if err != nil {
return "", err
}
c.selfUserID = id
return id, nil
}
func (c *Client) callHash() string {
if c.HTTP == nil || c.HTTP.Jar == nil {
return ""
}
u, err := url.Parse(c.portal)
if err != nil {
return ""
}
for _, ck := range c.HTTP.Jar.Cookies(u) {
if ck.Name == "BITRIX_CALL_HASH" {
return ck.Value
}
}
return ""
}
func (c *Client) PullConfig() (PullConfigResult, error) {
var pc PullConfigResult
form := url.Values{}
form.Set("CACHE", "N")
var body []byte
var status int
var err error
if hash := c.callHash(); hash != "" {
form.Set("call_auth_id", hash)
form.Set("videoconf_id", c.conferenceID)
form.Set("call_chat_id", c.chatID)
body, status, err = c.restForm("pull.config.get", form)
} else {
body, status, err = c.withRelogin(func() ([]byte, int, error) {
return c.restFormAuthed("pull.config.get", form)
})
}
if err != nil {
return pc, err
}
var out struct {
Result struct {
Server struct {
WebSocket string `json:"websocket"`
} `json:"server"`
API struct {
RevisionWeb int `json:"revision_web"`
} `json:"api"`
Channels struct {
Shared struct {
ID string `json:"id"`
} `json:"shared"`
Private struct {
ID string `json:"id"`
} `json:"private"`
} `json:"channels"`
} `json:"result"`
Error string `json:"error"`
}
if err := json.Unmarshal(body, &out); err != nil {
return pc, fmt.Errorf("pull config: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Result.Server.WebSocket == "" || out.Result.Channels.Private.ID == "" {
return pc, fmt.Errorf("pull config: missing websocket/channel (status %d, body %s)", status, common.BodySnippet(body))
}
pc.WebSocket = out.Result.Server.WebSocket
pc.ChannelID = out.Result.Channels.Private.ID
if out.Result.Channels.Shared.ID != "" {
pc.ChannelID += "/" + out.Result.Channels.Shared.ID
}
pc.Revision = out.Result.API.RevisionWeb
pc.Hostname = c.portal
if u, perr := url.Parse(c.portal); perr == nil && u.Host != "" {
pc.Hostname = u.Host
}
return pc, nil
}
func (c *Client) getGuestLink(chatID string) (string, error) {
form := url.Values{}
form.Set("chatId", chatID)
+40
View File
@@ -0,0 +1,40 @@
package bitrix
import "sync"
type KickManager struct {
kick func(userID string) error
selfID string
logFn func(string, ...any)
mu sync.Mutex
active string
}
func NewKickManager(kick func(userID string) error, selfID string, logFn func(string, ...any)) *KickManager {
return &KickManager{kick: kick, selfID: selfID, logFn: logFn}
}
func (m *KickManager) OnUserJoined(userID string) {
if userID == "" || userID == m.selfID {
return
}
m.mu.Lock()
old := m.active
if old == userID {
m.mu.Unlock()
return
}
m.active = userID
m.mu.Unlock()
if old == "" {
m.logFn("[bx] active call guest userId=%s", userID)
return
}
if err := m.kick(old); err != nil {
m.logFn("[bx] kick failed userId=%s: %v", old, err)
return
}
m.logFn("[bx] kicked previous guest userId=%s, new active=%s", old, userID)
}
+215
View File
@@ -0,0 +1,215 @@
package bitrix
import (
"encoding/binary"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"github.com/gorilla/websocket"
"whitelist-bypass/relay/common"
)
const (
pullWireVarint = 0
pullWireFixed64 = 1
pullWireBytes = 2
pullWireFixed32 = 5
pullMaxDepth = 8
)
type PullClient struct {
cfg PullConfigResult
ua string
origin string
logFn func(string, ...any)
mu sync.Mutex
ws *websocket.Conn
closed bool
onUsersAnswered func([]string)
onUserLeave func(string)
}
func NewPullClient(cfg PullConfigResult, ua, origin string, logFn func(string, ...any)) *PullClient {
return &PullClient{cfg: cfg, ua: ua, origin: origin, logFn: logFn}
}
func (p *PullClient) SetOnUsersAnswered(fn func([]string)) { p.onUsersAnswered = fn }
func (p *PullClient) SetOnUserLeave(fn func(string)) { p.onUserLeave = fn }
func (p *PullClient) dialURL() string {
q := url.Values{}
q.Set("CHANNEL_ID", p.cfg.ChannelID)
q.Set("binaryMode", "true")
if p.cfg.Hostname != "" {
q.Set("hostname", p.cfg.Hostname)
}
if p.cfg.Revision > 0 {
q.Set("revision", fmt.Sprintf("%d", p.cfg.Revision))
}
sep := "?"
if strings.Contains(p.cfg.WebSocket, "?") {
sep = "&"
}
return p.cfg.WebSocket + sep + q.Encode()
}
func (p *PullClient) connect() error {
headers := http.Header{}
if p.ua != "" {
headers.Set("User-Agent", p.ua)
}
if p.origin != "" {
headers.Set("Origin", p.origin)
}
conn, resp, err := websocket.DefaultDialer.Dial(p.dialURL(), headers)
if err != nil {
if resp != nil {
return fmt.Errorf("subws2 dial: %w, status %d", err, resp.StatusCode)
}
return fmt.Errorf("subws2 dial: %w", err)
}
p.mu.Lock()
p.ws = conn
p.mu.Unlock()
p.logFn("[bx] subws2 connected")
return nil
}
func (p *PullClient) Run() error {
if err := p.connect(); err != nil {
return err
}
for {
p.mu.Lock()
ws := p.ws
closed := p.closed
p.mu.Unlock()
if closed || ws == nil {
return nil
}
_, data, err := ws.ReadMessage()
if err != nil {
p.mu.Lock()
closed = p.closed
p.mu.Unlock()
if closed {
return nil
}
return fmt.Errorf("subws2 read: %w", err)
}
p.handleFrame(data)
}
}
func (p *PullClient) Close() {
p.mu.Lock()
p.closed = true
ws := p.ws
p.ws = nil
p.mu.Unlock()
if ws != nil {
common.CloseWS(ws)
}
}
func (p *PullClient) handleFrame(frame []byte) {
for _, body := range extractPullBodies(frame) {
var msg struct {
ModuleID string `json:"module_id"`
Command string `json:"command"`
Params struct {
Senders []struct {
SenderID json.Number `json:"senderId"`
} `json:"senders"`
UserID json.Number `json:"userId"`
} `json:"params"`
}
if err := json.Unmarshal(body, &msg); err != nil {
continue
}
switch {
case msg.ModuleID == "call" && strings.Contains(msg.Command, "usersAnswered"):
var ids []string
for _, s := range msg.Params.Senders {
if id := s.SenderID.String(); id != "" {
ids = append(ids, id)
}
}
if len(ids) > 0 && p.onUsersAnswered != nil {
p.onUsersAnswered(ids)
}
case msg.ModuleID == "im" && msg.Command == "chatUserLeave":
if uid := msg.Params.UserID.String(); uid != "" && p.onUserLeave != nil {
p.onUserLeave(uid)
}
}
}
}
func extractPullBodies(buf []byte) [][]byte {
return collectPullBodies(buf, nil, 0)
}
func collectPullBodies(buf []byte, out [][]byte, depth int) [][]byte {
if depth > pullMaxDepth {
return out
}
for len(buf) > 0 {
value, rest, ok := nextPullField(buf)
if !ok {
return out
}
buf = rest
switch {
case len(value) == 0:
case value[0] == '{':
out = append(out, value)
default:
out = collectPullBodies(value, out, depth+1)
}
}
return out
}
func nextPullField(buf []byte) (value, rest []byte, ok bool) {
tag, n := binary.Uvarint(buf)
if n <= 0 {
return nil, nil, false
}
buf = buf[n:]
switch tag & 7 {
case pullWireVarint:
_, m := binary.Uvarint(buf)
if m <= 0 {
return nil, nil, false
}
return nil, buf[m:], true
case pullWireFixed64:
return skipPullFixed(buf, 8)
case pullWireFixed32:
return skipPullFixed(buf, 4)
case pullWireBytes:
l, m := binary.Uvarint(buf)
if m <= 0 || l > uint64(len(buf)-m) {
return nil, nil, false
}
end := m + int(l)
return buf[m:end], buf[end:], true
}
return nil, nil, false
}
func skipPullFixed(buf []byte, size int) (value, rest []byte, ok bool) {
if len(buf) < size {
return nil, nil, false
}
return nil, buf[size:], true
}
+2
View File
@@ -115,6 +115,8 @@ func (s *Signal) SetOnDataChannel(fn func(*webrtc.DataChannel)) {
}
}
func (s *Signal) LocalUserID() string { return s.lk.Join().LocalUserID }
func (s *Signal) PubReliableDC() *webrtc.DataChannel {
s.mu.Lock()
defer s.mu.Unlock()
+32
View File
@@ -39,6 +39,38 @@ func LoadCookies(path string) string {
return strings.Join(parts, "; ")
}
func UpdateCookieFile(path string, updates map[string]string) error {
if len(updates) == 0 {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
var raw []map[string]any
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
seen := make(map[string]bool, len(updates))
for _, c := range raw {
name, _ := c["name"].(string)
if v, ok := updates[name]; ok {
c["value"] = v
seen[name] = true
}
}
for name, v := range updates {
if !seen[name] {
raw = append(raw, map[string]any{"name": name, "value": v})
}
}
out, err := json.MarshalIndent(raw, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, out, 0o600)
}
func CookieValue(cookieHeader, name string) string {
for _, part := range strings.Split(cookieHeader, ";") {
part = strings.TrimSpace(part)
+8
View File
@@ -92,6 +92,7 @@ type Call struct {
OnConnected func(tunnel.DataTunnel)
OnPeerRestart func()
OnKicked func()
OnRemoteSDP func(sdp string)
done chan struct{}
@@ -186,6 +187,13 @@ func (c *Call) Start() error {
default:
}
}
signaling.OnKicked = func() {
c.cfg.LogFn("[call] server kicked us, tearing down")
if c.OnKicked != nil {
c.OnKicked()
}
c.Close()
}
signaling.OnSpeakerJoined = c.handleSpeakerJoined
signaling.OnSpeakerDisconnected = c.handleSpeakerDisconnected
signaling.OnSpeakerCamStateChanged = c.handleSpeakerCamStateChanged
+6
View File
@@ -229,6 +229,7 @@ type SignalingClient struct {
OnGetVideoFromUserResponse func(resp GetVideoFromUserResponse, errCode int, errMessage string)
OnGetScreenSharingFromUserResponse func(resp GetScreenSharingFromUserResponse, errCode int, errMessage string)
OnHeartbeat func()
OnKicked func()
OnUnknown func(method string, params json.RawMessage)
OnDataChannelMessage func(method string, params json.RawMessage)
}
@@ -652,6 +653,11 @@ func (c *SignalingClient) dispatch(frame Frame) {
if c.OnHeartbeat != nil {
c.OnHeartbeat()
}
case MethodServerYouKicked:
c.logFn("dion: server:you_kicked")
if c.OnKicked != nil {
c.OnKicked()
}
case MethodServerGetVideoFromUser:
var resp GetVideoFromUserResponse
_ = json.Unmarshal(frame.Params, &resp)
+4 -2
View File
@@ -183,8 +183,9 @@ type jsonJoin struct {
PingInterval int32 `json:"pingInterval"`
ICEServers []jsonICEServer `json:"iceServers"`
Local struct {
SID string `json:"sid"`
Name string `json:"name"`
SID string `json:"sid"`
Name string `json:"name"`
UserID string `json:"userId"`
} `json:"localParticipant"`
}
@@ -231,6 +232,7 @@ func (JSONCodec) Decode(data []byte) (Event, error) {
RoomName: ji.RoomID,
ParticipantSID: ji.Local.SID,
ParticipantID: ji.Local.Name,
LocalUserID: ji.Local.UserID,
PingIntervalSec: ji.PingInterval,
}
for _, is := range ji.ICEServers {
+1
View File
@@ -183,6 +183,7 @@ type joinResponse struct {
RoomName string
ParticipantSID string
ParticipantID string
LocalUserID string
ServerVersion string
ServerRegion string
ICEServers []iceServer
@@ -40,6 +40,7 @@ type BitrixHeadlessJoiner struct {
sessMu sync.Mutex
sig *bitrix.Signal
ms *bitrix.MediaSession
pull *bitrix.PullClient
closeMu sync.Mutex
closed bool
@@ -235,6 +236,8 @@ func (j *BitrixHeadlessJoiner) runOnce() error {
return nil
}
j.startKickWatch(c, sig, userAgent)
if err := ms.Start(); err != nil {
sig.Close()
return fmt.Errorf("media start: %w", err)
@@ -279,13 +282,47 @@ func (j *BitrixHeadlessJoiner) setSession(sig *bitrix.Signal, ms *bitrix.MediaSe
j.sessMu.Unlock()
}
func (j *BitrixHeadlessJoiner) startKickWatch(c *bitrix.Client, sig *bitrix.Signal, userAgent string) {
selfID := sig.LocalUserID()
if selfID == "" {
j.logFn("bitrix-joiner: self userId unknown, kick-detect disabled")
return
}
pc, err := c.PullConfig()
if err != nil {
j.logFn("bitrix-joiner: pull config failed, kick-detect disabled: %s", common.MaskError(err))
return
}
pull := bitrix.NewPullClient(pc, userAgent, j.portal, j.logFn)
pull.SetOnUserLeave(func(uid string) {
if uid != selfID {
return
}
j.logFn("bitrix-joiner: kicked from conference (userId=%s), shutting down", uid)
go j.Close()
})
j.sessMu.Lock()
j.pull = pull
j.sessMu.Unlock()
go func() {
if err := pull.Run(); err != nil {
j.logFn("bitrix-joiner: subws2 pull ended: %s", common.MaskError(err))
}
}()
}
func (j *BitrixHeadlessJoiner) resetSessionState() {
j.sessMu.Lock()
sig := j.sig
ms := j.ms
pull := j.pull
j.sig = nil
j.ms = nil
j.pull = nil
j.sessMu.Unlock()
if pull != nil {
pull.Close()
}
if ms != nil {
ms.Stop()
}
@@ -130,6 +130,10 @@ func (j *DionHeadlessJoiner) runOnce(httpClient *http.Client, slug, displayName
j.OnConnected(tun)
}
}
call.OnKicked = func() {
j.logFn("dion-joiner: kicked from conference, shutting down")
go j.Close()
}
j.mu.Lock()
if j.closed {
+3 -3
View File
@@ -14,9 +14,9 @@ import (
const (
defaultVP8FPS = 24
defaultVP8Batch = 30
keepaliveIdlePeriod = 5 * time.Second
keepaliveIdleMin = 3 * time.Second
keepaliveIdleMax = 8 * time.Second
keepaliveIdlePeriod = 100 * time.Millisecond
keepaliveIdleMin = 60 * time.Millisecond
keepaliveIdleMax = 200 * time.Millisecond
keepalivePadMax = 176
sendQueueDepth = 128
+13 -7
View File
@@ -267,10 +267,10 @@ func newRequestID() string {
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) {
func RefreshAccessToken(client *http.Client, cookieHeader, deviceID string) (string, map[string]string, error) {
req, err := http.NewRequest(http.MethodPost, "https://auth-stream.wb.ru/v2/auth/slide-v3", bytes.NewReader(nil))
if err != nil {
return "", err
return "", nil, err
}
if deviceID == "" {
deviceID = newRequestID()
@@ -289,21 +289,27 @@ func RefreshAccessToken(client *http.Client, cookieHeader, deviceID string) (str
}
resp, err := client.Do(req)
if err != nil {
return "", err
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 "", fmt.Errorf("slide-v3: status %d: %s", resp.StatusCode, string(raw))
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 "", fmt.Errorf("slide-v3 decode: %w", err)
return "", nil, fmt.Errorf("slide-v3 decode: %w", err)
}
if r.Payload.AccessToken == "" {
return "", 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))
}
return r.Payload.AccessToken, nil
return r.Payload.AccessToken, rotated, nil
}
func joinAndGetDetails(client *http.Client, accessToken, roomID, displayName string) (string, string, string, string, error) {