From b4d5a05556c6b5d064b152dd1c35c6b135af66b2 Mon Sep 17 00:00:00 2001
From: kiper292
Date: Wed, 18 Mar 2026 10:59:41 +0500
Subject: [PATCH 01/11] Add multi-user sessions and session ID support
Introduce multi-user proxy sessions: add an English README and update the Russian README. Server: implement SessionManager and UserSession to aggregate DTLS streams by a 16-byte session ID, create a single UDP backend per session, and deliver backend->client traffic using round-robin across active DTLS streams. Simplify per-connection logic (read session ID after DTLS handshake, reuse backend, improved accept/handshake/error handling). Client: add -session-id flag, generate or parse a 16-byte UUID, send the session ID immediately after establishing each DTLS stream, and propagate sessionID through connection loops. These changes improve stability (prevent endpoint thrashing) and enable multiple simultaneous users per proxy server.
---
README.en.md | 90 ++++++++++++++++
README.md | 12 +++
client/main.go | 62 ++++++++---
server/main.go | 279 ++++++++++++++++++++++++++++++-------------------
4 files changed, 321 insertions(+), 122 deletions(-)
create mode 100644 README.en.md
diff --git a/README.en.md b/README.en.md
new file mode 100644
index 0000000..6037f91
--- /dev/null
+++ b/README.en.md
@@ -0,0 +1,90 @@
+# Good TURN
+[Russian version](README.md)
+
+Tunnels WireGuard/Hysteria traffic through VK Calls or Yandex Telemost TURN servers. Packets are encrypted with DTLS 1.2 and then sent in parallel streams via TCP or UDP to the TURN server using the STUN ChannelData protocol. From there, they are forwarded via UDP to your server, decrypted, and passed to WireGuard. TURN credentials are generated from the meeting link.
+
+**Update: Multi-user Proxy Server**
+The current implementation supports multiple simultaneous users through a single proxy server.
+- **Session Identification:** The client generates a unique 16-byte UUID at startup.
+- **Stream Aggregation:** The server groups all incoming DTLS connections from a single client by its UUID.
+- **Stable Backend:** For each session, exactly one UDP connection is created to the WireGuard server. This prevents the "endpoint thrashing" issue and increases stability.
+- **Load Balancing:** Outgoing traffic from the server to the client is distributed among all active DTLS streams of the user (Round-Robin).
+
+For educational purposes only!
+
+## Setup
+You will need:
+1. A link to an active VK call: create your own (requires a VK account) or search for `"https://vk.com/call/join/"`. Links are valid forever unless "end call for all" is clicked.
+2. Or a link to a Yandex Telemost call: `"https://telemost.yandex.ru/j/"`. Better not to search for these as conference participants are visible.
+3. A VPS with WireGuard installed.
+4. For Android: Download Termux from F-Droid.
+
+### Server
+```bash
+./server -listen 0.0.0.0:56000 -connect 127.0.0.1:
+```
+
+### Client
+#### Android
+
+**Recommended method:**
+Use the native Android app [vk-turn-proxy-android](https://github.com/MYSOREZ/vk-turn-proxy-android).
+- In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
+- **Add the app to WireGuard exceptions (Excluded Applications). Click "Save".**
+
+**Alternative method (via Termux):**
+- In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
+- **Add Termux to WireGuard exceptions. Click "Save".**
+
+In Termux:
+```bash
+termux-wake-lock
+```
+The phone will not enter deep sleep. To disable:
+```bash
+termux-wake-unlock
+```
+Copy the binary to a local folder and grant execution rights:
+```bash
+cp /sdcard/Download/client-android ./
+chmod 777 ./client-android
+```
+Run:
+```bash
+./client-android -peer :56000 -vk-link -listen 127.0.0.1:9000
+```
+Additional flags:
+- `-session-id `: set a fixed session ID (32 hex characters).
+
+Or:
+```bash
+./client-android -udp -turn 5.255.211.241 -peer :56000 -yandex-link -listen 127.0.0.1:9000
+```
+
+#### Linux
+In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
+
+The script will add routes to the necessary IPs:
+```bash
+./client-linux -peer :56000 -vk-link -listen 127.0.0.1:9000 | sudo routes.sh
+```
+
+#### Windows
+In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
+
+In PowerShell as Administrator (so the script can add routes):
+```powershell
+./client.exe -peer :56000 -vk-link -listen 127.0.0.1:9000 | routes.ps1
+```
+
+### If it doesn't work
+Use the `-turn` option to manually specify a TURN server address.
+If TCP doesn't work, try adding the `-udp` flag.
+Add `-n 1` for a more stable single-stream connection (limited to 5 Mbps for VK).
+
+## Yandex Telemost
+**UPD. TELEMOST IS CLOSED**
+Unlike VK, Yandex servers do not limit speed, so the default is `-n 1`.
+
+## Direct mode
+With the `-no-dtls` flag, you can send packets without DTLS obfuscation and connect to regular WireGuard servers. This may result in a ban from VK/Yandex.
diff --git a/README.md b/README.md
index 8d56e74..e8dd5c2 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,15 @@
# Good TURN
+[English version](README.en.md)
+
Проброс трафика WireGuard/Hysteria через TURN сервера VK звонков или Яндекс телемоста. Пакеты шифруются DTLS 1.2, затем параллельными потоками через TCP или UDP отправляются на TURN сервер по протоколу STUN ChannelData. Оттуда по UDP отправляются на ваш сервер, где расшифровываются и передаются в WireGuard. Логин/пароль от TURN генерируются из ссылки на звонок.
+**Обновление: Многопользовательский прокси-сервер**
+Текущая реализация поддерживает одновременную работу нескольких пользователей через один прокси-сервер.
+- **Идентификация сессий:** Клиент генерирует уникальный 16-байтный UUID при старте.
+- **Агрегация потоков:** Сервер группирует все входящие DTLS-соединения от одного клиента по его UUID.
+- **Стабильный бэкенд:** Для каждой сессии создается ровно одно UDP-соединение с WireGuard-сервером. Это предотвращает проблему "прыгающих портов" (endpoint thrashing) и повышает стабильность.
+- **Балансировка:** Исходящий трафик от сервера к клиенту распределяется между всеми активными DTLS-потоками пользователя (Round-Robin).
+
Только для учебных целей!
## Настройка
Нам понадобится:
@@ -41,6 +50,9 @@ chmod 777 ./client-android
```
./client-android -peer :56000 -vk-link -listen 127.0.0.1:9000
```
+Дополнительные флаги:
+- `-session-id `: установить фиксированный ID сессии (32 символа hex).
+
Или
```
./client-android -udp -turn 5.255.211.241 -peer :56000 -yandex-link -listen 127.0.0.1:9000
diff --git a/client/main.go b/client/main.go
index e4de0f9..93e831c 100644
--- a/client/main.go
+++ b/client/main.go
@@ -453,7 +453,7 @@ func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.
return dtlsConn, nil
}
-func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error) {
+func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error, sessionID []byte) {
var err error = nil
defer func() { c <- err }()
dtlsctx, dtlscancel := context.WithCancel(ctx)
@@ -481,7 +481,15 @@ func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.Pa
}
log.Printf("Closed DTLS connection\n")
}()
- log.Printf("Established DTLS connection!\n")
+
+ // Phase 1: Send Session ID
+ dtlsConn.SetWriteDeadline(time.Now().Add(time.Second * 5))
+ if _, err1 = dtlsConn.Write(sessionID); err1 != nil {
+ err = fmt.Errorf("failed to send session ID: %s", err1)
+ return
+ }
+
+ log.Printf("Established DTLS connection and sent session ID!\n")
go func() {
for {
select {
@@ -758,14 +766,14 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
conn2.SetDeadline(time.Time{})
}
-func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConnChan <-chan net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}) {
+func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConnChan <-chan net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, sessionID []byte) {
for {
select {
case <-ctx.Done():
return
case listenConn := <-listenConnChan:
c := make(chan error)
- go oneDtlsConnection(ctx, peer, listenConn, connchan, okchan, c)
+ go oneDtlsConnection(ctx, peer, listenConn, connchan, okchan, c, sessionID)
if err := <-c; err != nil {
log.Printf("%s", err)
}
@@ -817,6 +825,7 @@ func main() { //nolint:cyclop
n := flag.Int("n", 0, "connections to TURN (default 16 for VK, 1 for Yandex)")
udp := flag.Bool("udp", false, "connect to TURN with UDP")
direct := flag.Bool("no-dtls", false, "connect without obfuscation. DO NOT USE")
+ sessionIDFlag := flag.String("session-id", "", "override session ID (hex, 32 chars)")
flag.Parse()
if *peerAddr == "" {
log.Panicf("Need peer address!")
@@ -856,6 +865,17 @@ func main() { //nolint:cyclop
getCreds,
}
+ var sessionID []byte
+ if *sessionIDFlag != "" {
+ sessionID = make([]byte, 16)
+ if _, err := fmt.Sscanf(*sessionIDFlag, "%x", &sessionID); err != nil {
+ log.Panicf("Invalid session ID: %v", err)
+ }
+ } else {
+ sessionID, _ = uuid.New().MarshalBinary()
+ }
+ log.Printf("Session ID: %x", sessionID)
+
listenConnChan := make(chan net.PacketConn)
listenConn, err := net.ListenPacket("udp", *listen) // nolint: noctx
if err != nil {
@@ -880,21 +900,27 @@ func main() { //nolint:cyclop
t := time.Tick(100 * time.Millisecond)
if *direct {
for i := 0; i < *n; i++ {
- wg1.Go(func() {
+ wg1.Add(1)
+ go func() {
+ defer wg1.Done()
oneTurnConnectionLoop(ctx, params, peer, listenConnChan, t)
- })
+ }()
}
} else {
okchan := make(chan struct{})
connchan := make(chan net.PacketConn)
- wg1.Go(func() {
- oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, okchan)
- })
+ wg1.Add(1)
+ go func() {
+ defer wg1.Done()
+ oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, okchan, sessionID)
+ }()
- wg1.Go(func() {
+ wg1.Add(1)
+ go func() {
+ defer wg1.Done()
oneTurnConnectionLoop(ctx, params, peer, connchan, t)
- })
+ }()
select {
case <-okchan:
@@ -902,12 +928,16 @@ func main() { //nolint:cyclop
}
for i := 0; i < *n-1; i++ {
connchan := make(chan net.PacketConn)
- wg1.Go(func() {
- oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil)
- })
- wg1.Go(func() {
+ wg1.Add(1)
+ go func() {
+ defer wg1.Done()
+ oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil, sessionID)
+ }()
+ wg1.Add(1)
+ go func() {
+ defer wg1.Done()
oneTurnConnectionLoop(ctx, params, peer, connchan, t)
- })
+ }()
}
}
diff --git a/server/main.go b/server/main.go
index 0136b39..5690462 100644
--- a/server/main.go
+++ b/server/main.go
@@ -5,11 +5,13 @@ import (
"crypto/tls"
"flag"
"fmt"
+ "io"
"log"
"net"
"os"
"os/signal"
"sync"
+ "sync/atomic"
"syscall"
"time"
@@ -17,6 +19,121 @@ import (
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
)
+type UserSession struct {
+ ID string
+ Conns []net.Conn
+ BackendConn net.Conn
+ LastUsed uint32
+ Lock sync.RWMutex
+ Ctx context.Context
+ Cancel context.CancelFunc
+ Manager *SessionManager
+}
+
+type SessionManager struct {
+ Sessions map[string]*UserSession
+ Lock sync.RWMutex
+}
+
+func (s *SessionManager) GetOrCreate(ctx context.Context, id string, connectAddr string) (*UserSession, error) {
+ s.Lock.Lock()
+ defer s.Lock.Unlock()
+
+ if session, ok := s.Sessions[id]; ok {
+ return session, nil
+ }
+
+ backendConn, err := net.Dial("udp", connectAddr)
+ if err != nil {
+ return nil, err
+ }
+
+ sessionCtx, cancel := context.WithCancel(ctx)
+ session := &UserSession{
+ ID: id,
+ BackendConn: backendConn,
+ Manager: s,
+ Ctx: sessionCtx,
+ Cancel: cancel,
+ }
+
+ s.Sessions[id] = session
+ go session.backendReaderLoop()
+
+ return session, nil
+}
+
+func (s *UserSession) backendReaderLoop() {
+ defer s.Cleanup()
+ buf := make([]byte, 1600)
+ for {
+ select {
+ case <-s.Ctx.Done():
+ return
+ default:
+ }
+
+ s.BackendConn.SetReadDeadline(time.Now().Add(time.Minute * 5))
+ n, err := s.BackendConn.Read(buf)
+ if err != nil {
+ log.Printf("Session %s backend read error: %v", s.ID, err)
+ return
+ }
+
+ s.Lock.RLock()
+ if len(s.Conns) == 0 {
+ s.Lock.RUnlock()
+ continue
+ }
+ // Round-robin selection of DTLS connection
+ idx := atomic.AddUint32(&s.LastUsed, 1) % uint32(len(s.Conns))
+ conn := s.Conns[idx]
+ s.Lock.RUnlock()
+
+ conn.SetWriteDeadline(time.Now().Add(time.Second * 10))
+ _, err = conn.Write(buf[:n])
+ if err != nil {
+ log.Printf("Session %s DTLS write error: %v", s.ID, err)
+ // Connection will be removed by its own reader loop
+ }
+ }
+}
+
+func (s *UserSession) AddConn(conn net.Conn) {
+ s.Lock.Lock()
+ defer s.Lock.Unlock()
+ s.Conns = append(s.Conns, conn)
+}
+
+func (s *UserSession) RemoveConn(conn net.Conn) {
+ s.Lock.Lock()
+ defer s.Lock.Unlock()
+ for i, c := range s.Conns {
+ if c == conn {
+ s.Conns = append(s.Conns[:i], s.Conns[i+1:]...)
+ break
+ }
+ }
+ // If all connections are gone, we might want to start a timer to cleanup the session
+ // but for now we'll keep it alive until backendReaderLoop fails or context is cancelled.
+}
+
+func (s *UserSession) Cleanup() {
+ s.Cancel()
+ s.BackendConn.Close()
+
+ s.Manager.Lock.Lock()
+ delete(s.Manager.Sessions, s.ID)
+ s.Manager.Lock.Unlock()
+
+ s.Lock.Lock()
+ for _, c := range s.Conns {
+ c.Close()
+ }
+ s.Conns = nil
+ s.Lock.Unlock()
+}
+
func main() {
listen := flag.String("listen", "0.0.0.0:56000", "listen on ip:port")
connect := flag.String("connect", "", "connect to ip:port")
@@ -41,17 +158,12 @@ func main() {
if len(*connect) == 0 {
log.Panicf("server address is required")
}
- // Generate a certificate and private key to secure the connection
+
certificate, genErr := selfsign.GenerateSelfSigned()
if genErr != nil {
- panic(err)
+ panic(genErr)
}
- //
- // Everything below is the pion-DTLS API! Thanks for using it ❤️.
- //
-
- // Prepare the configuration of the DTLS connection
config := &dtls.Config{
Certificates: []tls.Certificate{certificate},
ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
@@ -59,131 +171,86 @@ func main() {
ConnectionIDGenerator: dtls.RandomCIDGenerator(8),
}
- // Connect to a DTLS server
listener, err := dtls.Listen("udp", addr, config)
if err != nil {
panic(err)
}
context.AfterFunc(ctx, func() {
- if err = listener.Close(); err != nil {
- panic(err)
- }
+ listener.Close()
})
- fmt.Println("Listening")
+ manager := &SessionManager{
+ Sessions: make(map[string]*UserSession),
+ }
+
+ log.Printf("Listening on %s, forwarding to %s", *listen, *connect)
- wg1 := sync.WaitGroup{}
for {
- select {
- case <-ctx.Done():
- wg1.Wait()
- return
- default:
- }
- // Wait for a connection.
conn, err := listener.Accept()
if err != nil {
- log.Println(err)
- continue
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ log.Println("Accept error:", err)
+ continue
+ }
}
- wg1.Add(1)
+
go func(conn net.Conn) {
- defer wg1.Done()
- defer conn.Close() // graceful shutdown
- var err error = nil
- log.Printf("Connection from %s\n", conn.RemoteAddr())
- // `conn` is of type `net.Conn` but may be casted to `dtls.Conn`
- // using `dtlsConn := conn.(*dtls.Conn)` in order to to expose
- // functions like `ConnectionState` etc.
-
- // Perform the handshake with a 30-second timeout
- ctx1, cancel1 := context.WithTimeout(ctx, 30*time.Second)
+ defer conn.Close()
+
dtlsConn, ok := conn.(*dtls.Conn)
if !ok {
- log.Println("Type error")
- cancel1()
return
}
- log.Println("Start handshake")
- if err = dtlsConn.HandshakeContext(ctx1); err != nil {
- log.Println(err)
- cancel1()
+
+ handshakeCtx, hCancel := context.WithTimeout(ctx, 30*time.Second)
+ defer hCancel()
+
+ if err := dtlsConn.HandshakeContext(handshakeCtx); err != nil {
+ log.Println("Handshake failed:", err)
+ return
+ }
+
+ // Phase 1: Read Session ID (16 bytes)
+ idBuf := make([]byte, 16)
+ conn.SetReadDeadline(time.Now().Add(time.Second * 5))
+ _, err := io.ReadFull(conn, idBuf)
+ if err != nil {
+ log.Println("Failed to read session ID:", err)
return
}
- cancel1()
- log.Println("Handshake done")
+ sessionID := fmt.Sprintf("%x", idBuf)
- serverConn, err := net.Dial("udp", *connect)
+ session, err := manager.GetOrCreate(ctx, sessionID, *connect)
if err != nil {
- log.Println(err)
+ log.Println("Failed to get/create session:", err)
return
}
- defer func() {
- if err = serverConn.Close(); err != nil {
- log.Printf("failed to close outgoing connection: %s", err)
+
+ session.AddConn(conn)
+ defer session.RemoveConn(conn)
+
+ log.Printf("New stream for session %s from %s", sessionID, conn.RemoteAddr())
+
+ // Upstream Loop: DTLS -> Backend
+ buf := make([]byte, 1600)
+ for {
+ conn.SetReadDeadline(time.Now().Add(time.Minute * 10))
+ n, err := conn.Read(buf)
+ if err != nil {
+ log.Printf("Stream %s closed: %v", sessionID, err)
return
}
- }()
-
- var wg sync.WaitGroup
- wg.Add(2)
- ctx2, cancel2 := context.WithCancel(ctx)
- context.AfterFunc(ctx2, func() {
- conn.SetDeadline(time.Now())
- serverConn.SetDeadline(time.Now())
- })
- go func() {
- defer wg.Done()
- defer cancel2()
- buf := make([]byte, 1600)
- for {
- select {
- case <-ctx2.Done():
- return
- default:
- }
- conn.SetReadDeadline(time.Now().Add(time.Minute * 30))
- n, err1 := conn.Read(buf)
- if err1 != nil {
- log.Printf("Failed: %s", err1)
- return
- }
-
- serverConn.SetWriteDeadline(time.Now().Add(time.Minute * 30))
- _, err1 = serverConn.Write(buf[:n])
- if err1 != nil {
- log.Printf("Failed: %s", err1)
- return
- }
- }
- }()
- go func() {
- defer wg.Done()
- defer cancel2()
- buf := make([]byte, 1600)
- for {
- select {
- case <-ctx2.Done():
- return
- default:
- }
- serverConn.SetReadDeadline(time.Now().Add(time.Minute * 30))
- n, err1 := serverConn.Read(buf)
- if err1 != nil {
- log.Printf("Failed: %s", err1)
- return
- }
-
- conn.SetWriteDeadline(time.Now().Add(time.Minute * 30))
- _, err1 = conn.Write(buf[:n])
- if err1 != nil {
- log.Printf("Failed: %s", err1)
- return
- }
+
+ session.BackendConn.SetWriteDeadline(time.Now().Add(time.Second * 5))
+ _, err = session.BackendConn.Write(buf[:n])
+ if err != nil {
+ log.Printf("Session %s backend write error: %v", sessionID, err)
+ return
}
- }()
- wg.Wait()
- log.Printf("Connection closed: %s\n", conn.RemoteAddr())
+ }
}(conn)
}
}
From 86b357403cf5403d0a808915a4c58a35cc629f52 Mon Sep 17 00:00:00 2001
From: kiper292
Date: Wed, 18 Mar 2026 11:24:04 +0500
Subject: [PATCH 02/11] Use wireguard-turn-android as recommended app
Replace the recommended Android client in README.md and README.en.md: swap vk-turn-proxy-android for wireguard-turn-android and update the link and brief description (it's a modified WireGuard client with built-in TURN). Remove the previous explicit WireGuard config/exception steps from the recommended method while leaving the Termux alternative unchanged.
---
README.en.md | 4 +---
README.md | 4 +---
2 files changed, 2 insertions(+), 6 deletions(-)
diff --git a/README.en.md b/README.en.md
index 6037f91..c303beb 100644
--- a/README.en.md
+++ b/README.en.md
@@ -28,9 +28,7 @@ You will need:
#### Android
**Recommended method:**
-Use the native Android app [vk-turn-proxy-android](https://github.com/MYSOREZ/vk-turn-proxy-android).
-- In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
-- **Add the app to WireGuard exceptions (Excluded Applications). Click "Save".**
+Use the native Android app [wireguard-turn-android](https://github.com/kiper292/wireguard-turn-android). This is a modified WireGuard client with built-in TURN support.
**Alternative method (via Termux):**
- In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
diff --git a/README.md b/README.md
index e8dd5c2..cad2029 100644
--- a/README.md
+++ b/README.md
@@ -26,9 +26,7 @@
#### Android
**Рекомендуемый способ:**
-Использовать нативное Android-приложение [vk-turn-proxy-android](https://github.com/MYSOREZ/vk-turn-proxy-android).
-- В клиентском конфиге WireGuard меняем адрес сервера на `127.0.0.1:9000`, ставим MTU 1280
-- **Добавляем приложение в исключения WireGuard. Нажимаем "сохранить".**
+Использовать нативное Android-приложение [wireguard-turn-android](https://github.com/kiper292/wireguard-turn-android). Это модифицированный WireGuard клиент со встроенным TURN.
**Альтернативный способ (через Termux):**
- В клиентском конфиге WireGuard меняем адрес сервера на `127.0.0.1:9000`, ставим MTU 1280
From a00db4f4a400c11e83554e706cf1ab36984c2548 Mon Sep 17 00:00:00 2001
From: kiper292
Date: Tue, 24 Mar 2026 22:46:23 +0500
Subject: [PATCH 03/11] Add per-stream ID to DTLS sessions
Client and server now include a 1-byte stream ID alongside the 16-byte session ID (17 bytes total) so multiple logical streams can be multiplexed per session. Client: propagate streamID through connection helpers and send sessionID+streamID when establishing DTLS connections; default stream 0 for the first connection and subsequent goroutines pass incremental stream IDs. Server: read 17-byte header, split into sessionID and streamID, and track connections as streamEntry {id, conn} rather than a plain conn slice. AddConn/RemoveConn signatures updated to accept stream IDs; new logic evicts existing connection with the same stream ID. backendReaderLoop uses a local round-robin index (removed atomic usage) and closes connections on write errors. Also adjusted per-stream read deadlines and cleaned up connection closing in Cleanup().
---
client/main.go | 23 +++++++++-------
server/main.go | 71 ++++++++++++++++++++++++++++++--------------------
2 files changed, 56 insertions(+), 38 deletions(-)
diff --git a/client/main.go b/client/main.go
index 93e831c..9089931 100644
--- a/client/main.go
+++ b/client/main.go
@@ -453,7 +453,7 @@ func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.
return dtlsConn, nil
}
-func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error, sessionID []byte) {
+func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error, sessionID []byte, streamID byte) {
var err error = nil
defer func() { c <- err }()
dtlsctx, dtlscancel := context.WithCancel(ctx)
@@ -482,14 +482,17 @@ func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.Pa
log.Printf("Closed DTLS connection\n")
}()
- // Phase 1: Send Session ID
+ // Phase 1: Send Session ID + Stream ID (17 bytes)
dtlsConn.SetWriteDeadline(time.Now().Add(time.Second * 5))
- if _, err1 = dtlsConn.Write(sessionID); err1 != nil {
+ idBuf := make([]byte, 17)
+ copy(idBuf[:16], sessionID)
+ idBuf[16] = streamID
+ if _, err1 = dtlsConn.Write(idBuf); err1 != nil {
err = fmt.Errorf("failed to send session ID: %s", err1)
return
}
- log.Printf("Established DTLS connection and sent session ID!\n")
+ log.Printf("Established DTLS connection and sent session ID with stream %d!\n", streamID)
go func() {
for {
select {
@@ -766,14 +769,14 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
conn2.SetDeadline(time.Time{})
}
-func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConnChan <-chan net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, sessionID []byte) {
+func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConnChan <-chan net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, sessionID []byte, streamID byte) {
for {
select {
case <-ctx.Done():
return
case listenConn := <-listenConnChan:
c := make(chan error)
- go oneDtlsConnection(ctx, peer, listenConn, connchan, okchan, c, sessionID)
+ go oneDtlsConnection(ctx, peer, listenConn, connchan, okchan, c, sessionID, streamID)
if err := <-c; err != nil {
log.Printf("%s", err)
}
@@ -913,7 +916,7 @@ func main() { //nolint:cyclop
wg1.Add(1)
go func() {
defer wg1.Done()
- oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, okchan, sessionID)
+ oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, okchan, sessionID, 0)
}()
wg1.Add(1)
@@ -929,10 +932,10 @@ func main() { //nolint:cyclop
for i := 0; i < *n-1; i++ {
connchan := make(chan net.PacketConn)
wg1.Add(1)
- go func() {
+ go func(streamID byte) {
defer wg1.Done()
- oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil, sessionID)
- }()
+ oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil, sessionID, streamID)
+ }(byte(i + 1))
wg1.Add(1)
go func() {
defer wg1.Done()
diff --git a/server/main.go b/server/main.go
index 5690462..f8d7026 100644
--- a/server/main.go
+++ b/server/main.go
@@ -11,7 +11,6 @@ import (
"os"
"os/signal"
"sync"
- "sync/atomic"
"syscall"
"time"
@@ -19,11 +18,15 @@ import (
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
)
+type streamEntry struct {
+ id byte
+ conn net.Conn
+}
+
type UserSession struct {
ID string
- Conns []net.Conn
+ Conns []streamEntry
BackendConn net.Conn
- LastUsed uint32
Lock sync.RWMutex
Ctx context.Context
Cancel context.CancelFunc
@@ -51,12 +54,12 @@ func (s *SessionManager) GetOrCreate(ctx context.Context, id string, connectAddr
sessionCtx, cancel := context.WithCancel(ctx)
session := &UserSession{
ID: id,
+ Conns: make([]streamEntry, 0),
BackendConn: backendConn,
Manager: s,
Ctx: sessionCtx,
Cancel: cancel,
}
-
s.Sessions[id] = session
go session.backendReaderLoop()
@@ -66,6 +69,7 @@ func (s *SessionManager) GetOrCreate(ctx context.Context, id string, connectAddr
func (s *UserSession) backendReaderLoop() {
defer s.Cleanup()
buf := make([]byte, 1600)
+ var lastUsed uint32 = 0
for {
select {
case <-s.Ctx.Done():
@@ -81,43 +85,54 @@ func (s *UserSession) backendReaderLoop() {
}
s.Lock.RLock()
- if len(s.Conns) == 0 {
+ nConns := uint32(len(s.Conns))
+ if nConns == 0 {
s.Lock.RUnlock()
continue
}
- // Round-robin selection of DTLS connection
- idx := atomic.AddUint32(&s.LastUsed, 1) % uint32(len(s.Conns))
- conn := s.Conns[idx]
+
+ // Fast Round-robin selection using local variable
+ lastUsed = (lastUsed + 1) % nConns
+ conn := s.Conns[lastUsed].conn
s.Lock.RUnlock()
conn.SetWriteDeadline(time.Now().Add(time.Second * 10))
+
_, err = conn.Write(buf[:n])
if err != nil {
log.Printf("Session %s DTLS write error: %v", s.ID, err)
- // Connection will be removed by its own reader loop
+ conn.Close()
}
- }
+ }
}
-func (s *UserSession) AddConn(conn net.Conn) {
+func (s *UserSession) AddConn(id byte, conn net.Conn) {
s.Lock.Lock()
defer s.Lock.Unlock()
- s.Conns = append(s.Conns, conn)
+
+ // Evict existing connection with same ID
+ for i, entry := range s.Conns {
+ if entry.id == id {
+ //log.Printf("Session %s: Evicting old stream %d", s.ID, id)
+ entry.conn.Close()
+ s.Conns[i].conn = conn
+ return
+ }
+ }
+
+ s.Conns = append(s.Conns, streamEntry{id: id, conn: conn})
}
-func (s *UserSession) RemoveConn(conn net.Conn) {
+func (s *UserSession) RemoveConn(id byte, conn net.Conn) {
s.Lock.Lock()
defer s.Lock.Unlock()
- for i, c := range s.Conns {
- if c == conn {
+ for i, entry := range s.Conns {
+ if entry.id == id && entry.conn == conn {
s.Conns = append(s.Conns[:i], s.Conns[i+1:]...)
break
}
}
- // If all connections are gone, we might want to start a timer to cleanup the session
- // but for now we'll keep it alive until backendReaderLoop fails or context is cancelled.
}
-
func (s *UserSession) Cleanup() {
s.Cancel()
s.BackendConn.Close()
@@ -127,13 +142,12 @@ func (s *UserSession) Cleanup() {
s.Manager.Lock.Unlock()
s.Lock.Lock()
- for _, c := range s.Conns {
- c.Close()
+ for _, entry := range s.Conns {
+ entry.conn.Close()
}
s.Conns = nil
s.Lock.Unlock()
}
-
func main() {
listen := flag.String("listen", "0.0.0.0:56000", "listen on ip:port")
connect := flag.String("connect", "", "connect to ip:port")
@@ -213,15 +227,16 @@ func main() {
return
}
- // Phase 1: Read Session ID (16 bytes)
- idBuf := make([]byte, 16)
+ // Phase 1: Read Session ID + Stream ID (17 bytes)
+ idBuf := make([]byte, 17)
conn.SetReadDeadline(time.Now().Add(time.Second * 5))
_, err := io.ReadFull(conn, idBuf)
if err != nil {
log.Println("Failed to read session ID:", err)
return
}
- sessionID := fmt.Sprintf("%x", idBuf)
+ sessionID := fmt.Sprintf("%x", idBuf[:16])
+ streamID := idBuf[16]
session, err := manager.GetOrCreate(ctx, sessionID, *connect)
if err != nil {
@@ -229,15 +244,15 @@ func main() {
return
}
- session.AddConn(conn)
- defer session.RemoveConn(conn)
+ session.AddConn(streamID, conn)
+ defer session.RemoveConn(streamID, conn)
- log.Printf("New stream for session %s from %s", sessionID, conn.RemoteAddr())
+ log.Printf("New stream %d for session %s from %s", streamID, sessionID, conn.RemoteAddr())
// Upstream Loop: DTLS -> Backend
buf := make([]byte, 1600)
for {
- conn.SetReadDeadline(time.Now().Add(time.Minute * 10))
+ conn.SetReadDeadline(time.Now().Add(time.Minute * 5))
n, err := conn.Read(buf)
if err != nil {
log.Printf("Stream %s closed: %v", sessionID, err)
From ee1fd9ebf620cc70d0f8439d0544bee5970b199e Mon Sep 17 00:00:00 2001
From: kiper292
Date: Sat, 28 Mar 2026 13:11:43 +0500
Subject: [PATCH 04/11] fix client
---
client/main.go | 15 ++++++++-------
1 file changed, 8 insertions(+), 7 deletions(-)
diff --git a/client/main.go b/client/main.go
index 9089931..f381cae 100644
--- a/client/main.go
+++ b/client/main.go
@@ -77,7 +77,7 @@ func getVkCreds(link string) (string, string, string, error) {
log.Panicf("get TURN creds error: %v\n\n", resp)
}
}()
-
+/*
data := "client_secret=QbYic1K3lEV5kTGiqlq2&client_id=6287487&scopes=audio_anonymous%2Cvideo_anonymous%2Cphotos_anonymous%2Cprofile_anonymous&isApiOauthAnonymEnabled=false&version=1&app_id=6287487"
url := "https://login.vk.ru/?act=get_anonym_token"
@@ -97,11 +97,12 @@ func getVkCreds(link string) (string, string, string, error) {
}
token2 := resp["response"].(map[string]interface{})["payload"].(string)
+*/
+ //data = fmt.Sprintf("client_id=6287487&token_type=messages&payload=%s&client_secret=QbYic1K3lEV5kTGiqlq2&version=1&app_id=6287487", token2)
+ data := fmt.Sprintf("client_id=6287487&token_type=messages&client_secret=QbYic1K3lEV5kTGiqlq2&version=1&app_id=6287487")
+ url := "https://login.vk.ru/?act=get_anonym_token"
- data = fmt.Sprintf("client_id=6287487&token_type=messages&payload=%s&client_secret=QbYic1K3lEV5kTGiqlq2&version=1&app_id=6287487", token2)
- url = "https://login.vk.ru/?act=get_anonym_token"
-
- resp, err = doRequest(data, url)
+ resp, err := doRequest(data, url)
if err != nil {
return "", "", "", fmt.Errorf("request error:%s", err)
}
@@ -109,7 +110,7 @@ func getVkCreds(link string) (string, string, string, error) {
token3 := resp["data"].(map[string]interface{})["access_token"].(string)
data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=123&access_token=%s", link, token3)
- url = "https://api.vk.ru/method/calls.getAnonymousToken?v=5.264"
+ url = "https://api.vk.ru/method/calls.getAnonymousToken?v=5.274&client_id=6287487"
resp, err = doRequest(data, url)
if err != nil {
@@ -128,7 +129,7 @@ func getVkCreds(link string) (string, string, string, error) {
token5 := resp["session_key"].(string)
- data = fmt.Sprintf("joinLink=%s&isVideo=false&protocolVersion=5&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s", link, token4, token5)
+ data = fmt.Sprintf("joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s", link, token4, token5)
url = "https://calls.okcdn.ru/fb.do"
resp, err = doRequest(data, url)
From b656d10de8808b75c9239a3ec7ce7afa745a4ebe Mon Sep 17 00:00:00 2001
From: kiper292
Date: Sat, 4 Apr 2026 02:09:54 +0500
Subject: [PATCH 05/11] captcha fix
---
client/main.go | 458 ++++++++++++++++++++++++++++++++++---------
client/vk_captcha.go | 325 ++++++++++++++++++++++++++++++
2 files changed, 687 insertions(+), 96 deletions(-)
create mode 100644 client/vk_captcha.go
diff --git a/client/main.go b/client/main.go
index f381cae..011c396 100644
--- a/client/main.go
+++ b/client/main.go
@@ -12,8 +12,10 @@ import (
"fmt"
"io"
"log"
+ "math/rand"
"net"
"net/http"
+ "net/url"
"os"
"os/signal"
"strings"
@@ -31,123 +33,378 @@ import (
"github.com/pion/turn/v5"
)
-type getCredsFunc func(string) (string, string, string, error)
+type getCredsFunc func(context.Context, string, int) (string, string, string, error)
-func getVkCreds(link string) (string, string, string, error) {
- doRequest := func(data string, url string) (resp map[string]interface{}, err error) {
- client := &http.Client{
- Timeout: 20 * time.Second,
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: 90 * time.Second,
- },
- }
- defer client.CloseIdleConnections()
- req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
- if err != nil {
- return nil, err
- }
+const vkClientID = "6287487"
+const vkClientSecret = "QbYic1K3lEV5kTGiqlq2"
+const vkAPIVersion = "5.275"
- req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0")
- req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
+// TurnCredentials stores cached TURN credentials
+type TurnCredentials struct {
+ Username string
+ Password string
+ ServerAddr string
+ ExpiresAt time.Time
+ Link string
+}
- httpResp, err := client.Do(req)
- if err != nil {
- return nil, err
- }
- defer httpResp.Body.Close()
+// StreamCredentialsCache holds credentials cache for a single stream
+type StreamCredentialsCache struct {
+ creds TurnCredentials
+ mutex sync.RWMutex
+ errorCount atomic.Int32
+ lastErrorTime atomic.Int64
+}
- body, err := io.ReadAll(httpResp.Body)
- if err != nil {
- return nil, err
- }
+const (
+ credentialLifetime = 10 * time.Minute
+ cacheSafetyMargin = 60 * time.Second
+ maxCacheErrors = 3
+ errorWindow = 10 * time.Second
+ streamsPerCache = 4 // Number of streams sharing one credentials cache
+)
- err = json.Unmarshal(body, &resp)
- if err != nil {
- return nil, err
- }
+// getCacheID returns the shared cache ID for a given stream ID
+func getCacheID(streamID int) int {
+ return streamID / streamsPerCache
+}
+
+// credentialsStore manages per-stream credentials caches
+var credentialsStore = struct {
+ mu sync.RWMutex
+ caches map[int]*StreamCredentialsCache
+}{
+ caches: make(map[int]*StreamCredentialsCache),
+}
+
+// getStreamCache returns or creates a shared cache for the given stream ID
+func getStreamCache(streamID int) *StreamCredentialsCache {
+ cacheID := getCacheID(streamID)
+
+ // Try read lock first for fast path
+ credentialsStore.mu.RLock()
+ cache, exists := credentialsStore.caches[cacheID]
+ credentialsStore.mu.RUnlock()
- return resp, nil
+ if exists {
+ return cache
}
- var resp map[string]interface{}
- defer func() {
- if r := recover(); r != nil {
- log.Panicf("get TURN creds error: %v\n\n", resp)
- }
- }()
-/*
- data := "client_secret=QbYic1K3lEV5kTGiqlq2&client_id=6287487&scopes=audio_anonymous%2Cvideo_anonymous%2Cphotos_anonymous%2Cprofile_anonymous&isApiOauthAnonymEnabled=false&version=1&app_id=6287487"
- url := "https://login.vk.ru/?act=get_anonym_token"
+ // Need to create new cache
+ credentialsStore.mu.Lock()
+ defer credentialsStore.mu.Unlock()
- resp, err := doRequest(data, url)
- if err != nil {
- return "", "", "", fmt.Errorf("request error:%s", err)
+ // Double-check after acquiring write lock
+ if cache, exists = credentialsStore.caches[cacheID]; exists {
+ return cache
}
- token1 := resp["data"].(map[string]interface{})["access_token"].(string)
+ cache = &StreamCredentialsCache{}
+ credentialsStore.caches[cacheID] = cache
+ return cache
+}
- data = fmt.Sprintf("access_token=%s", token1)
- url = "https://api.vk.ru/method/calls.getAnonymousAccessTokenPayload?v=5.264&client_id=6287487"
+// invalidate invalidates the credentials cache for this stream
+func (c *StreamCredentialsCache) invalidate(streamID int) {
+ c.mutex.Lock()
+ c.creds = TurnCredentials{}
+ c.mutex.Unlock()
- resp, err = doRequest(data, url)
- if err != nil {
- return "", "", "", fmt.Errorf("request error:%s", err)
+ // Reset auth error counter
+ c.errorCount.Store(0)
+ c.lastErrorTime.Store(0)
+
+ log.Printf("[VK Auth] Credentials cache invalidated for stream %d", streamID)
+}
+
+func min(a, b int) int {
+ if a < b {
+ return a
}
+ return b
+}
+
+// vkDelay sleeps for a random duration between minMs and maxMs to avoid bot detection
+func vkDelay(minMs, maxMs int) {
+ ms := minMs + rand.Intn(maxMs-minMs+1)
+ time.Sleep(time.Duration(ms) * time.Millisecond)
+}
- token2 := resp["response"].(map[string]interface{})["payload"].(string)
-*/
- //data = fmt.Sprintf("client_id=6287487&token_type=messages&payload=%s&client_secret=QbYic1K3lEV5kTGiqlq2&version=1&app_id=6287487", token2)
- data := fmt.Sprintf("client_id=6287487&token_type=messages&client_secret=QbYic1K3lEV5kTGiqlq2&version=1&app_id=6287487")
- url := "https://login.vk.ru/?act=get_anonym_token"
+// vkCredsMu serializes VK credential fetching to avoid BOT detection from parallel requests
+var vkCredsMu sync.Mutex
- resp, err := doRequest(data, url)
- if err != nil {
- return "", "", "", fmt.Errorf("request error:%s", err)
+// getVkCredsCached checks cache before fetching credentials
+func getVkCredsCached(ctx context.Context, link string, streamID int) (string, string, string, error) {
+ cache := getStreamCache(streamID)
+ cacheID := getCacheID(streamID)
+
+ cache.mutex.Lock()
+ defer cache.mutex.Unlock()
+
+ // Check cache - another stream may have populated it while waiting
+ if cache.creds.Link == link && time.Now().Before(cache.creds.ExpiresAt) {
+ expires := time.Until(cache.creds.ExpiresAt)
+ log.Printf("[VK Auth] Using cached credentials (cache=%d, expires in %v)", cacheID, expires)
+ return cache.creds.Username, cache.creds.Password, cache.creds.ServerAddr, nil
}
- token3 := resp["data"].(map[string]interface{})["access_token"].(string)
+ log.Printf("[VK Auth] Cache miss (cache=%d), starting credential fetch...", cacheID)
- data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=123&access_token=%s", link, token3)
- url = "https://api.vk.ru/method/calls.getAnonymousToken?v=5.274&client_id=6287487"
+ // Check context before long fetch
+ select {
+ case <-ctx.Done():
+ return "", "", "", ctx.Err()
+ default:
+ }
- resp, err = doRequest(data, url)
+ // Fetch credentials with mutex to avoid VK flood control
+ user, pass, addr, err := getVkCredsSafe(ctx, link, streamID)
if err != nil {
- return "", "", "", fmt.Errorf("request error:%s", err)
+ return "", "", "", err
}
- token4 := resp["response"].(map[string]interface{})["token"].(string)
+ // Store in cache
+ cache.creds = TurnCredentials{
+ Username: user,
+ Password: pass,
+ ServerAddr: addr,
+ ExpiresAt: time.Now().Add(credentialLifetime - cacheSafetyMargin),
+ Link: link,
+ }
+
+ log.Printf("[VK Auth] Success! Credentials cached until %v (cache=%d)", cache.creds.ExpiresAt, cacheID)
+ return user, pass, addr, nil
+}
- data = fmt.Sprintf("%s%s%s", "session_data=%7B%22version%22%3A2%2C%22device_id%22%3A%22", uuid.New(), "%22%2C%22client_version%22%3A1.1%2C%22client_type%22%3A%22SDK_JS%22%7D&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA")
- url = "https://calls.okcdn.ru/fb.do"
+// getVkCredsSafe wraps getVkCreds with mutex to avoid VK flood control
+func getVkCredsSafe(ctx context.Context, link string, streamID int) (string, string, string, error) {
+ vkCredsMu.Lock()
+ defer vkCredsMu.Unlock()
+ return getVkCreds(ctx, link)
+}
- resp, err = doRequest(data, url)
+func vkHTTPPost(ctx context.Context, data string, url string) (map[string]interface{}, error) {
+ client := &http.Client{
+ Timeout: 20 * time.Second,
+ Transport: &http.Transport{
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 100,
+ IdleConnTimeout: 90 * time.Second,
+ },
+ }
+ defer client.CloseIdleConnections()
+ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer([]byte(data)))
+ if err != nil {
+ return nil, err
+ }
+ // Headers matching HAR capture exactly
+ req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "*/*")
+ req.Header.Set("Accept-Language", "en-US,en;q=0.9")
+ req.Header.Set("Origin", "https://vk.ru")
+ req.Header.Set("Referer", "https://vk.ru/")
+ req.Header.Set("sec-ch-ua-platform", `"Windows"`)
+ req.Header.Set("sec-ch-ua", `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`)
+ req.Header.Set("sec-ch-ua-mobile", "?0")
+ req.Header.Set("Sec-Fetch-Site", "same-site")
+ req.Header.Set("Sec-Fetch-Mode", "cors")
+ req.Header.Set("Sec-Fetch-Dest", "empty")
+ req.Header.Set("DNT", "1")
+ req.Header.Set("Priority", "u=1, i")
+
+ httpResp, err := client.Do(req)
if err != nil {
- return "", "", "", fmt.Errorf("request error:%s", err)
+ return nil, err
}
+ defer httpResp.Body.Close()
- token5 := resp["session_key"].(string)
+ // Handle HTTP errors (redirects, rate limits, etc.)
+ if httpResp.StatusCode >= 400 {
+ body, _ := io.ReadAll(httpResp.Body)
+ return nil, fmt.Errorf("HTTP %d from %s: %s", httpResp.StatusCode, req.URL, string(body[:min(len(body), 500)]))
+ }
- data = fmt.Sprintf("joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s", link, token4, token5)
- url = "https://calls.okcdn.ru/fb.do"
+ body, err := io.ReadAll(httpResp.Body)
+ if err != nil {
+ return nil, err
+ }
- resp, err = doRequest(data, url)
+ // Check content type - VK may return HTML instead of JSON (captcha page, redirect, etc.)
+ contentType := httpResp.Header.Get("Content-Type")
+ if contentType != "" && !strings.Contains(contentType, "application/json") && !strings.Contains(contentType, "text/javascript") {
+ // Log first 500 chars of non-JSON response for debugging
+ logPreview := string(body)
+ if len(logPreview) > 500 {
+ logPreview = logPreview[:500] + "...(truncated)"
+ }
+ return nil, fmt.Errorf("unexpected content-type %s, status %d, body: %s", contentType, httpResp.StatusCode, logPreview)
+ }
+
+ var resp map[string]interface{}
+ if err = json.Unmarshal(body, &resp); err != nil {
+ // Log the raw body for debugging
+ logPreview := string(body)
+ if len(logPreview) > 500 {
+ logPreview = logPreview[:500] + "...(truncated)"
+ }
+ return nil, fmt.Errorf("JSON parse error: %w, body: %s", err, logPreview)
+ }
+ return resp, nil
+}
+
+func getVkCreds(ctx context.Context, link string) (string, string, string, error) {
+ // Token 1 (messages)
+ log.Println("[VK Auth] Getting Token 1...")
+ data := fmt.Sprintf("client_id=%s&token_type=messages&client_secret=%s&version=1&app_id=%s",
+ vkClientID, vkClientSecret, vkClientID)
+ resp, err := vkHTTPPost(ctx, data, "https://login.vk.ru/?act=get_anonym_token")
+ if err != nil {
+ return "", "", "", fmt.Errorf("Token 1 request error: %w", err)
+ }
+ if errMsg, ok := resp["error"].(map[string]interface{}); ok {
+ return "", "", "", fmt.Errorf("Token 1 VK error: %v", errMsg)
+ }
+ dataObj, ok := resp["data"].(map[string]interface{})
+ if !ok {
+ return "", "", "", fmt.Errorf("invalid Token 1 response: %v", resp)
+ }
+ token1, ok := dataObj["access_token"].(string)
+ if !ok {
+ return "", "", "", fmt.Errorf("access_token not found in Token 1 response")
+ }
+ log.Println("[VK Auth] Token 1 received")
+ vkDelay(100, 200) // Token 1 → getCallPreview
+
+ // getCallPreview (optional, like browser)
+ log.Println("[VK Auth] Getting call preview...")
+ cpData := fmt.Sprintf("vk_join_link=https://vk.ru/call/join/%s&fields=photo_200&access_token=%s",
+ url.QueryEscape(link), token1)
+ cpURL := fmt.Sprintf("https://api.vk.ru/method/calls.getCallPreview?v=%s&client_id=%s", vkAPIVersion, vkClientID)
+ _, _ = vkHTTPPost(ctx, cpData, cpURL) // non-critical
+ vkDelay(500, 1000) // getCallPreview → Token 2
+
+ // Token 2 (may require captcha)
+ log.Println("[VK Auth] Getting Token 2...")
+ t2Data := fmt.Sprintf("vk_join_link=https://vk.ru/call/join/%s&name=123&access_token=%s",
+ url.QueryEscape(link), token1)
+ t2URL := fmt.Sprintf("https://api.vk.ru/method/calls.getAnonymousToken?v=%s&client_id=%s", vkAPIVersion, vkClientID)
+ resp, err = vkHTTPPost(ctx, t2Data, t2URL)
if err != nil {
- return "", "", "", fmt.Errorf("request error:%s", err)
+ return "", "", "", fmt.Errorf("Token 2 request error: %w", err)
}
- user := resp["turn_server"].(map[string]interface{})["username"].(string)
- pass := resp["turn_server"].(map[string]interface{})["credential"].(string)
- turn := resp["turn_server"].(map[string]interface{})["urls"].([]interface{})[0].(string)
+ // Check for captcha error
+ if errMsg, ok := resp["error"].(map[string]interface{}); ok {
+ captchaData, isCaptcha := ExtractCaptchaData(errMsg)
+ if !isCaptcha {
+ return "", "", "", fmt.Errorf("Token 2 VK error: %v", errMsg)
+ }
+
+ log.Printf("[VK Auth] Captcha detected, solving...")
+ successToken, solveErr := SolveVkCaptcha(ctx, captchaData)
+ if solveErr != nil {
+ return "", "", "", fmt.Errorf("captcha solving failed: %w", solveErr)
+ }
+
+ // Delay before retry (endSession → Token 2 retry)
+ vkDelay(100, 200)
+
+ // Retry Token 2 with captcha solution
+ log.Println("[VK Auth] Retrying Token 2 with captcha solution...")
+ t2Data = fmt.Sprintf(
+ "vk_join_link=https://vk.ru/call/join/%s&name=123"+
+ "&captcha_key=&captcha_sid=%s&is_sound_captcha=0"+
+ "&success_token=%s&captcha_ts=%s&captcha_attempt=%s"+
+ "&access_token=%s",
+ url.QueryEscape(link),
+ captchaData.CaptchaSid,
+ successToken,
+ captchaData.CaptchaTs,
+ captchaData.CaptchaAttempt,
+ token1,
+ )
+ resp, err = vkHTTPPost(ctx, t2Data, t2URL)
+ if err != nil {
+ return "", "", "", fmt.Errorf("Token 2 retry request error: %w", err)
+ }
+ if errMsg2, ok := resp["error"].(map[string]interface{}); ok {
+ return "", "", "", fmt.Errorf("Token 2 retry VK error: %v", errMsg2)
+ }
+ // Token 2 retry → Token 3
+ vkDelay(100, 200)
+ }
- clean := strings.Split(turn, "?")[0]
+ token2Obj, ok := resp["response"].(map[string]interface{})
+ if !ok {
+ return "", "", "", fmt.Errorf("invalid Token 2 response: %v", resp)
+ }
+ token2, ok := token2Obj["token"].(string)
+ if !ok {
+ return "", "", "", fmt.Errorf("token not found in Token 2 response")
+ }
+ log.Println("[VK Auth] Token 2 received")
+ // Token 2 → Token 3
+ vkDelay(100, 200)
+
+ // Token 3 (OK auth.anonymLogin)
+ log.Println("[VK Auth] Getting Token 3...")
+ sessionData := fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":1.1,"client_type":"SDK_JS"}`, uuid.New())
+ t3Data := fmt.Sprintf("session_data=%s&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA",
+ url.QueryEscape(sessionData))
+ resp, err = vkHTTPPost(ctx, t3Data, "https://calls.okcdn.ru/fb.do")
+ if err != nil {
+ return "", "", "", fmt.Errorf("Token 3 request error: %w", err)
+ }
+ if errMsg, ok := resp["error"].(string); ok && errMsg != "" {
+ return "", "", "", fmt.Errorf("Token 3 API error: %s", errMsg)
+ }
+ token3, ok := resp["session_key"].(string)
+ if !ok {
+ return "", "", "", fmt.Errorf("session_key not found in Token 3 response")
+ }
+ log.Println("[VK Auth] Token 3 received")
+ // Token 3 → Final (TURN)
+ vkDelay(100, 200)
+
+ // Final: vchat.joinConversationByLink (Token 4)
+ log.Println("[VK Auth] Getting TURN credentials (Token 4)...")
+ finalData := fmt.Sprintf(
+ "joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s",
+ url.QueryEscape(link), token2, token3)
+ resp, err = vkHTTPPost(ctx, finalData, "https://calls.okcdn.ru/fb.do")
+ if err != nil {
+ return "", "", "", fmt.Errorf("Final request error: %w", err)
+ }
+ if errMsg, ok := resp["error"].(string); ok && errMsg != "" {
+ return "", "", "", fmt.Errorf("Final API error: %s", errMsg)
+ }
+
+ ts, ok := resp["turn_server"].(map[string]interface{})
+ if !ok {
+ return "", "", "", fmt.Errorf("turn_server not found in response: %v", resp)
+ }
+ urls, _ := ts["urls"].([]interface{})
+ if len(urls) == 0 {
+ return "", "", "", fmt.Errorf("urls not found in turn_server")
+ }
+ urlStr, _ := urls[0].(string)
+ clean := strings.Split(urlStr, "?")[0]
address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
- return user, pass, address, nil
+ username, _ := ts["username"].(string)
+ credential, _ := ts["credential"].(string)
+
+ if username == "" || credential == "" {
+ return "", "", "", fmt.Errorf("username or credential not found in turn_server")
+ }
+
+ log.Println("[VK Auth] TURN credentials received")
+ vkDelay(1500, 2500) // Final delay before exit
+ return username, credential, address, nil
}
-func getYandexCreds(link string) (string, string, string, error) {
+func getYandexCreds(ctx context.Context, link string, streamID int) (string, string, string, error) {
const debug = false
const telemostConfHost = "cloud-api.yandex.ru"
telemostConfPath := fmt.Sprintf("%s%s%s", "/telemost_front/v2/telemost/conferences/https%3A%2F%2Ftelemost.yandex.ru%2Fj%2F", link, "/connection?next_gen_media_platform_allowed=false")
@@ -441,7 +698,8 @@ func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.
CipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
ConnectionIDGenerator: dtls.OnlySendCIDGenerator(),
}
- ctx1, cancel := context.WithTimeout(ctx, 30*time.Second)
+ // Extended timeout to accommodate serialized credential fetching via mutex
+ ctx1, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
dtlsConn, err := dtls.Client(conn, peer, config)
if err != nil {
@@ -586,13 +844,14 @@ type turnParams struct {
port string
link string
udp bool
+ streamID int
getCreds getCredsFunc
}
func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UDPAddr, conn2 net.PacketConn, c chan<- error) {
var err error = nil
defer func() { c <- err }()
- user, pass, url, err1 := turnParams.getCreds(turnParams.link)
+ user, pass, url, err1 := turnParams.getCreds(ctx, turnParams.link, turnParams.streamID)
if err1 != nil {
err = fmt.Errorf("failed to get TURN credentials: %s", err1)
return
@@ -785,7 +1044,11 @@ func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConnCha
}
}
-func oneTurnConnectionLoop(ctx context.Context, turnParams *turnParams, peer *net.UDPAddr, connchan <-chan net.PacketConn, t <-chan time.Time) {
+func oneTurnConnectionLoop(ctx context.Context, turnParams *turnParams, peer *net.UDPAddr, connchan <-chan net.PacketConn, t <-chan time.Time, streamID int) {
+ // Create a copy of turnParams with the streamID
+ tp := *turnParams
+ tp.streamID = streamID
+
for {
select {
case <-ctx.Done():
@@ -794,7 +1057,7 @@ func oneTurnConnectionLoop(ctx context.Context, turnParams *turnParams, peer *ne
select {
case <-t:
c := make(chan error)
- go oneTurnConnection(ctx, turnParams, peer, conn2, c)
+ go oneTurnConnection(ctx, &tp, peer, conn2, c)
if err := <-c; err != nil {
log.Printf("%s", err)
}
@@ -846,9 +1109,9 @@ func main() { //nolint:cyclop
if *vklink != "" {
parts := strings.Split(*vklink, "join/")
link = parts[len(parts)-1]
- getCreds = getVkCreds
+ getCreds = getVkCredsCached
if *n <= 0 {
- *n = 16
+ *n = 4
}
} else {
parts := strings.Split(*yalink, "j/")
@@ -862,11 +1125,12 @@ func main() { //nolint:cyclop
link = link[:idx]
}
params := &turnParams{
- *host,
- *port,
- link,
- *udp,
- getCreds,
+ host: *host,
+ port: *port,
+ link: link,
+ udp: *udp,
+ streamID: 0,
+ getCreds: getCreds,
}
var sessionID []byte
@@ -905,9 +1169,10 @@ func main() { //nolint:cyclop
if *direct {
for i := 0; i < *n; i++ {
wg1.Add(1)
+ streamID := i
go func() {
defer wg1.Done()
- oneTurnConnectionLoop(ctx, params, peer, listenConnChan, t)
+ oneTurnConnectionLoop(ctx, params, peer, listenConnChan, t, streamID)
}()
}
} else {
@@ -923,7 +1188,7 @@ func main() { //nolint:cyclop
wg1.Add(1)
go func() {
defer wg1.Done()
- oneTurnConnectionLoop(ctx, params, peer, connchan, t)
+ oneTurnConnectionLoop(ctx, params, peer, connchan, t, 0)
}()
select {
@@ -932,15 +1197,16 @@ func main() { //nolint:cyclop
}
for i := 0; i < *n-1; i++ {
connchan := make(chan net.PacketConn)
+ streamID := i + 1
wg1.Add(1)
- go func(streamID byte) {
+ go func(sID byte) {
defer wg1.Done()
- oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil, sessionID, streamID)
- }(byte(i + 1))
+ oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil, sessionID, sID)
+ }(byte(streamID))
wg1.Add(1)
go func() {
defer wg1.Done()
- oneTurnConnectionLoop(ctx, params, peer, connchan, t)
+ oneTurnConnectionLoop(ctx, params, peer, connchan, t, streamID)
}()
}
}
diff --git a/client/vk_captcha.go b/client/vk_captcha.go
new file mode 100644
index 0000000..8e3a348
--- /dev/null
+++ b/client/vk_captcha.go
@@ -0,0 +1,325 @@
+// SPDX-FileCopyrightText: 2023 The Pion community
+// SPDX-License-Identifier: MIT
+
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "crypto/tls"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "math/rand"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const (
+ vkCaptchaAPIVersion = "5.275"
+ vkCaptchaNotRobotVer = "5.131"
+ vkDebugInfo = "d44f534ce8deb56ba20be52e05c433309b49ee4d2a70602deeb17a1954257785"
+)
+
+// VkCaptchaData holds captcha challenge data from VK error response
+type VkCaptchaData struct {
+ CaptchaSid string
+ CaptchaTs string
+ CaptchaAttempt string
+ RedirectURI string
+ SessionToken string
+}
+
+// ExtractCaptchaData parses VK API error response for captcha info
+func ExtractCaptchaData(errResp map[string]interface{}) (*VkCaptchaData, bool) {
+ code, _ := errResp["error_code"].(float64)
+ if int(code) != 14 {
+ return nil, false
+ }
+
+ redirectURI, _ := errResp["redirect_uri"].(string)
+ if redirectURI == "" {
+ return nil, false
+ }
+
+ // Parse session_token from redirect_uri
+ parsed, err := url.Parse(redirectURI)
+ if err != nil {
+ return nil, false
+ }
+ sessionToken := parsed.Query().Get("session_token")
+ if sessionToken == "" {
+ return nil, false
+ }
+
+ // Extract captcha_sid
+ captchaSid, _ := errResp["captcha_sid"].(string)
+
+ // captcha_ts can be float64 or string
+ var captchaTs string
+ if tsFloat, ok := errResp["captcha_ts"].(float64); ok {
+ captchaTs = fmt.Sprintf("%.0f", tsFloat)
+ } else if tsStr, ok := errResp["captcha_ts"].(string); ok {
+ captchaTs = tsStr
+ }
+
+ // captcha_attempt
+ var captchaAttempt string
+ if attFloat, ok := errResp["captcha_attempt"].(float64); ok {
+ captchaAttempt = fmt.Sprintf("%.0f", attFloat)
+ } else if attStr, ok := errResp["captcha_attempt"].(string); ok {
+ captchaAttempt = attStr
+ }
+
+ return &VkCaptchaData{
+ CaptchaSid: captchaSid,
+ CaptchaTs: captchaTs,
+ CaptchaAttempt: captchaAttempt,
+ RedirectURI: redirectURI,
+ SessionToken: sessionToken,
+ }, true
+}
+
+// SolveVkCaptcha fetches captcha page, solves PoW, and calls captchaNotRobot API
+func SolveVkCaptcha(ctx context.Context, captchaData *VkCaptchaData) (string, error) {
+ log.Printf("[Captcha] Solving Not Robot Captcha...")
+
+ // HAR: Token 2 error → Captcha HTML = 2.72s (browser page load + user perception)
+ time.Sleep(1500*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond)
+
+ // Fetch captcha HTML (browser redirect)
+ powInput, difficulty, cookies, err := fetchCaptchaPowInput(ctx, captchaData.RedirectURI)
+ if err != nil {
+ return "", fmt.Errorf("failed to fetch powInput: %w", err)
+ }
+ log.Printf("[Captcha] PoW input: %s, difficulty: %d", powInput, difficulty)
+
+ // Solve PoW
+ hash := solveCaptchaPoW(powInput, difficulty)
+ log.Printf("[Captcha] PoW solved: hash=%s", hash)
+
+ // Call captchaNotRobot API with cookies from captcha page
+ successToken, err := callCaptchaNotRobotAPI(ctx, captchaData.SessionToken, hash, cookies)
+ if err != nil {
+ return "", fmt.Errorf("captchaNotRobot API failed: %w", err)
+ }
+
+ log.Printf("[Captcha] Success! Got success_token")
+ return successToken, nil
+}
+
+func fetchCaptchaPowInput(ctx context.Context, redirectURI string) (string, int, string, error) {
+ req, err := http.NewRequestWithContext(ctx, "GET", redirectURI, nil)
+ if err != nil {
+ return "", 0, "", err
+ }
+ req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
+ req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
+ req.Header.Set("Accept-Language", "en-US,en;q=0.9")
+
+ client := &http.Client{
+ Timeout: 20 * time.Second,
+ Transport: &http.Transport{
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ },
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", 0, "", err
+ }
+ defer resp.Body.Close()
+
+ // Capture Set-Cookie headers
+ var cookieValues []string
+ for _, setCookie := range resp.Header.Values("Set-Cookie") {
+ // Extract just the cookie name=value part (before ; expires= or ; path=)
+ cookieParts := strings.Split(setCookie, ";")
+ cookieValues = append(cookieValues, strings.TrimSpace(cookieParts[0]))
+ }
+ cookies := strings.Join(cookieValues, "; ")
+ if cookies != "" {
+ log.Printf("[Captcha] Captcha page set %d cookie(s)", len(cookieValues))
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", 0, "", err
+ }
+
+ html := string(body)
+
+ // Extract powInput: const powInput = "..."
+ powInputRe := regexp.MustCompile(`const\s+powInput\s*=\s*"([^"]+)"`)
+ powInputMatch := powInputRe.FindStringSubmatch(html)
+ if len(powInputMatch) < 2 {
+ return "", 0, "", fmt.Errorf("powInput not found in captcha HTML")
+ }
+ powInput := powInputMatch[1]
+
+ // Extract difficulty: '0'.repeat(N)
+ diffRe := regexp.MustCompile(`startsWith\('0'\.repeat\((\d+)\)\)`)
+ diffMatch := diffRe.FindStringSubmatch(html)
+ difficulty := 2 // default
+ if len(diffMatch) >= 2 {
+ if d, err := strconv.Atoi(diffMatch[1]); err == nil {
+ difficulty = d
+ }
+ }
+
+ return powInput, difficulty, cookies, nil
+}
+
+func solveCaptchaPoW(powInput string, difficulty int) string {
+ target := strings.Repeat("0", difficulty)
+ for nonce := 1; nonce <= 10000000; nonce++ {
+ data := powInput + strconv.Itoa(nonce)
+ hash := sha256.Sum256([]byte(data))
+ hexHash := hex.EncodeToString(hash[:])
+ if strings.HasPrefix(hexHash, target) {
+ return hexHash
+ }
+ }
+ return ""
+}
+
+func callCaptchaNotRobotAPI(ctx context.Context, sessionToken, hash, cookies string) (string, error) {
+ vkReq := func(method string, postData string) (map[string]interface{}, error) {
+ requestURL := fmt.Sprintf("https://api.vk.ru/method/%s?v=%s", method, vkCaptchaNotRobotVer)
+
+ req, err := http.NewRequestWithContext(ctx, "POST", requestURL, strings.NewReader(postData))
+ if err != nil {
+ return nil, err
+ }
+ // Headers matching HAR capture exactly
+ req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "*/*")
+ req.Header.Set("Accept-Language", "en-US,en;q=0.9")
+ req.Header.Set("Origin", "https://id.vk.ru")
+ req.Header.Set("Referer", "https://id.vk.ru/")
+ req.Header.Set("sec-ch-ua-platform", `"Windows"`)
+ req.Header.Set("sec-ch-ua", `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`)
+ req.Header.Set("sec-ch-ua-mobile", "?0")
+ req.Header.Set("Sec-Fetch-Site", "same-site")
+ req.Header.Set("Sec-Fetch-Mode", "cors")
+ req.Header.Set("Sec-Fetch-Dest", "empty")
+ req.Header.Set("DNT", "1")
+ req.Header.Set("Priority", "u=1, i")
+ // Add cookies captured from captcha page
+ if cookies != "" {
+ req.Header.Set("Cookie", cookies)
+ }
+
+ client := &http.Client{
+ Timeout: 20 * time.Second,
+ Transport: &http.Transport{
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ },
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var result map[string]interface{}
+ if err := json.Unmarshal(body, &result); err != nil {
+ return nil, err
+ }
+ return result, nil
+ }
+
+ domain := "vk.com"
+ baseParams := fmt.Sprintf("session_token=%s&domain=%s&adFp=&access_token=",
+ url.QueryEscape(sessionToken), url.QueryEscape(domain))
+
+ // Step 1: settings
+ log.Printf("[Captcha] Step 1/4: settings")
+ _, err := vkReq("captchaNotRobot.settings", baseParams)
+ if err != nil {
+ return "", fmt.Errorf("settings failed: %w", err)
+ }
+ // HAR: settings → componentDone = 0.19s
+ time.Sleep(100*time.Millisecond + time.Duration(rand.Intn(100))*time.Millisecond)
+
+ // Step 2: componentDone
+ log.Printf("[Captcha] Step 2/4: componentDone")
+ browserFp := fmt.Sprintf("%032x", uint64(time.Now().UnixNano()))
+ deviceJSON := `{"screenWidth":1920,"screenHeight":1080,"screenAvailWidth":1920,"screenAvailHeight":1032,"innerWidth":1920,"innerHeight":945,"devicePixelRatio":1,"language":"en-US","languages":["en-US"],"webdriver":false,"hardwareConcurrency":16,"deviceMemory":8,"connectionEffectiveType":"4g","notificationsPermission":"denied"}`
+ componentData := baseParams + fmt.Sprintf("&browser_fp=%s&device=%s", browserFp, url.QueryEscape(deviceJSON))
+ _, err = vkReq("captchaNotRobot.componentDone", componentData)
+ if err != nil {
+ return "", fmt.Errorf("componentDone failed: %w", err)
+ }
+ // HAR: componentDone → check ≈ 1.95s + statEvents delay ≈ 3.2s total
+ time.Sleep(1500*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond)
+
+ // Step 3: check
+ log.Printf("[Captcha] Step 3/4: check")
+ cursorJSON := `[{"x":950,"y":500},{"x":945,"y":510},{"x":940,"y":520},{"x":938,"y":525},{"x":938,"y":525}]`
+ answer := base64.StdEncoding.EncodeToString([]byte("{}")) // e30=
+
+ // Generate random connectionDownlink values (simulating Network Information API)
+ // HAR shows browser repeats the same value 7 times: [9.8,9.8,9.8,9.8,9.8,9.8,9.8]
+ baseDownlink := 8.0 + rand.Float64()*4.0 // Random in [8.0, 12.0) for typical WiFi
+ downlinkStr := fmt.Sprintf("%.1f", baseDownlink)
+ connectionDownlink := "[" + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "]"
+
+ checkData := baseParams + fmt.Sprintf(
+ "&accelerometer=%s&gyroscope=%s&motion=%s&cursor=%s&taps=%s&connectionRtt=%s&connectionDownlink=%s"+
+ "&browser_fp=%s&hash=%s&answer=%s&debug_info=%s",
+ url.QueryEscape("[]"), // accelerometer
+ url.QueryEscape("[]"), // gyroscope
+ url.QueryEscape("[]"), // motion
+ url.QueryEscape(cursorJSON), // cursor
+ url.QueryEscape("[]"), // taps
+ url.QueryEscape("[]"), // connectionRtt
+ url.QueryEscape(connectionDownlink),
+ browserFp, // browser_fp
+ hash, // hash (PoW result)
+ answer, // answer
+ vkDebugInfo, // debug_info (static)
+ )
+
+ checkResp, err := vkReq("captchaNotRobot.check", checkData)
+ if err != nil {
+ return "", fmt.Errorf("check request failed: %w", err)
+ }
+
+ respObj, ok := checkResp["response"].(map[string]interface{})
+ if !ok {
+ return "", fmt.Errorf("invalid check response: %v", checkResp)
+ }
+
+ status, _ := respObj["status"].(string)
+ if status != "OK" {
+ return "", fmt.Errorf("check response status: %s, full response: %v", status, checkResp)
+ }
+
+ successToken, ok := respObj["success_token"].(string)
+ if !ok || successToken == "" {
+ return "", fmt.Errorf("success_token not found in check response: %v", checkResp)
+ }
+ // HAR: check → endSession = 0.48s
+ time.Sleep(200*time.Millisecond + time.Duration(rand.Intn(300))*time.Millisecond)
+
+ // Step 4: endSession
+ log.Printf("[Captcha] Step 4/4: endSession")
+ vkReq("captchaNotRobot.endSession", baseParams)
+
+ return successToken, nil
+}
From fc5edf434a78da90271a65e84752cb27212040ac Mon Sep 17 00:00:00 2001
From: kiper292
Date: Sat, 4 Apr 2026 02:16:02 +0500
Subject: [PATCH 06/11] add mipsle arch
---
.github/workflows/ci.yml | 4 ++++
.github/workflows/release.yml | 29 +++++++++++++++++++++++++++--
2 files changed, 31 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3e4d7de..ecd517f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -69,6 +69,10 @@ jobs:
goarch: arm64
cgo: 1
api: 21
+ - goos: android
+ goarch: arm
+ cgo: 1
+ api: 21
# you can add more (android/arm, windows, etc.) later
steps:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index f4247cd..306a2c9 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -27,6 +27,21 @@ jobs:
goarch: arm
goarm: '7'
cgo: 0
+ - goos: linux
+ goarch: mipsle
+ gomips: softfloat
+ cgo: 0
+ - goos: linux
+ goarch: mips
+ gomips: softfloat
+ cgo: 0
+ - goos: linux
+ goarch: mips64le
+ gomips: softfloat
+ cgo: 0
+ - goos: linux
+ goarch: riscv64
+ cgo: 0
- goos: darwin
goarch: amd64
cgo: 0
@@ -36,6 +51,9 @@ jobs:
- goos: windows
goarch: amd64
cgo: 0
+ - goos: windows
+ goarch: arm64
+ cgo: 0
- goos: windows
goarch: 386
cgo: 0
@@ -43,6 +61,10 @@ jobs:
goarch: arm64
cgo: 1
api: 21
+ - goos: android
+ goarch: arm
+ cgo: 1
+ api: 21
- goos: freebsd
goarch: amd64
cgo: 0
@@ -69,6 +91,7 @@ jobs:
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
+ GOMIPS: ${{ matrix.gomips }}
GOARM: ${{ matrix.goarm }}
CGO_ENABLED: ${{ matrix.cgo }}
ANDROID_API: ${{ matrix.api }}
@@ -87,6 +110,8 @@ jobs:
if [ "$GOARCH" = "arm64" ]; then
export CC="$TOOLCHAIN_BIN/aarch64-linux-android${ANDROID_API}-clang"
+ elif [ "$GOARCH" = "arm" ]; then
+ export CC="$TOOLCHAIN_BIN/armv7a-linux-androideabi${ANDROID_API}-clang"
else
echo "Unsupported ANDROID GOARCH=$GOARCH"
exit 1
@@ -104,12 +129,12 @@ jobs:
EXT=
fi
- GOOS=$GOOS GOARCH=$GOARCH GOARM=$GOARM \
+ GOOS=$GOOS GOARCH=$GOARCH GOARM=$GOARM GOMIPS=$GOMIPS \
go build -ldflags "-s -w -checklinkname=0" -trimpath \
-o "dist/client-${GOOS}-${GOARCH}${EXT}" \
./client
- GOOS=$GOOS GOARCH=$GOARCH GOARM=$GOARM \
+ GOOS=$GOOS GOARCH=$GOARCH GOARM=$GOARM GOMIPS=$GOMIPS \
go build -ldflags "-s -w -checklinkname=0" -trimpath \
-o "dist/server-${GOOS}-${GOARCH}${EXT}" \
./server
From b01249e8be0a7bf7ad12bd490c5110752ee00162 Mon Sep 17 00:00:00 2001
From: kiper292
Date: Sat, 4 Apr 2026 03:06:08 +0500
Subject: [PATCH 07/11] wb mode
---
README.en.md | 210 ++++++++++++-
README.md | 113 ++++---
client/credentials.go | 151 +++++++++
client/main.go | 691 ++----------------------------------------
client/vk.go | 258 ++++++++++++++++
client/wb.go | 358 ++++++++++++++++++++++
6 files changed, 1056 insertions(+), 725 deletions(-)
create mode 100644 client/credentials.go
create mode 100644 client/vk.go
create mode 100644 client/wb.go
diff --git a/README.en.md b/README.en.md
index c303beb..fc6fa03 100644
--- a/README.en.md
+++ b/README.en.md
@@ -1,7 +1,15 @@
-# Good TURN
+# VK/WB TURN Proxy
[Russian version](README.md)
-Tunnels WireGuard/Hysteria traffic through VK Calls or Yandex Telemost TURN servers. Packets are encrypted with DTLS 1.2 and then sent in parallel streams via TCP or UDP to the TURN server using the STUN ChannelData protocol. From there, they are forwarded via UDP to your server, decrypted, and passed to WireGuard. TURN credentials are generated from the meeting link.
+Tunnels WireGuard/Hysteria traffic through VK Calls or WB Stream TURN servers. Packets are encrypted with DTLS 1.2 and then sent in parallel streams via TCP or UDP to the TURN server using the STUN ChannelData protocol. From there, they are forwarded via UDP to your server, decrypted, and passed to WireGuard. TURN credentials are generated from the meeting link.
+
+## Features
+
+- **VK Calls** — TURN credentials from VK API with automatic captcha solving (Not Robot)
+- **WB Stream** — TURN credentials from WB Stream API (LiveKit ICE)
+- **Caching** — 10 minute TTL with shared cache across 4 streams
+- **DTLS obfuscation** — DPI bypass via DTLS tunnel
+- **Multiple connections** — up to N parallel connections to TURN
**Update: Multi-user Proxy Server**
The current implementation supports multiple simultaneous users through a single proxy server.
@@ -12,19 +20,32 @@ The current implementation supports multiple simultaneous users through a single
For educational purposes only!
+## Client Structure
+
+```
+client/
+├── credentials.go # Shared credentials cache, request serialization
+├── vk.go # VK API: Token 1→4 chain, HTTP requests
+├── vk_captcha.go # VK Captcha: PoW solving, Not Robot flow
+├── wb.go # WB Stream: guest register → room → LiveKit ICE
+└── main.go # DTLS/TURN connections, CLI, main loop
+```
+
## Setup
+
You will need:
1. A link to an active VK call: create your own (requires a VK account) or search for `"https://vk.com/call/join/"`. Links are valid forever unless "end call for all" is clicked.
-2. Or a link to a Yandex Telemost call: `"https://telemost.yandex.ru/j/"`. Better not to search for these as conference participants are visible.
-3. A VPS with WireGuard installed.
-4. For Android: Download Termux from F-Droid.
+2. A VPS with WireGuard installed.
+3. For Android: Download Termux from F-Droid.
### Server
+
```bash
./server -listen 0.0.0.0:56000 -connect 127.0.0.1:
```
### Client
+
#### Android
**Recommended method:**
@@ -47,42 +68,201 @@ Copy the binary to a local folder and grant execution rights:
cp /sdcard/Download/client-android ./
chmod 777 ./client-android
```
-Run:
+
+**VK mode:**
```bash
./client-android -peer :56000 -vk-link -listen 127.0.0.1:9000
```
-Additional flags:
-- `-session-id `: set a fixed session ID (32 hex characters).
-Or:
+**WB mode:**
```bash
-./client-android -udp -turn 5.255.211.241 -peer :56000 -yandex-link -listen 127.0.0.1:9000
+./client-android -wb -peer :56000 -listen 127.0.0.1:9000
```
+Additional flags:
+- `-session-id `: set a fixed session ID (32 hex characters).
+- `-n `: number of connections to TURN (default 4).
+- `-udp`: use UDP for TURN (default TCP).
+- `-turn `: override TURN server address.
+- `-port `: override TURN server port.
+- `-no-dtls`: without DTLS obfuscation (may result in a ban).
+
#### Linux
+
In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
The script will add routes to the necessary IPs:
+
```bash
./client-linux -peer :56000 -vk-link -listen 127.0.0.1:9000 | sudo routes.sh
```
+```bash
+./client-linux -wb -peer :56000 -listen 127.0.0.1:9000 | sudo routes.sh
+```
+
+⚠️ Do not enable the VPN until the program has established a connection! Unlike Android, some requests will go through the VPN here (DNS and TURN connection requests).
+
#### Windows
+
In the WireGuard client config, change the server address to `127.0.0.1:9000` and set MTU to 1280.
In PowerShell as Administrator (so the script can add routes):
+
```powershell
./client.exe -peer :56000 -vk-link -listen 127.0.0.1:9000 | routes.ps1
```
+```powershell
+./client.exe -wb -peer :56000 -listen 127.0.0.1:9000 | routes.ps1
+```
+
+⚠️ Do not enable the VPN until the program has established a connection! Unlike Android, some requests will go through the VPN here (DNS and TURN connection requests).
+
### If it doesn't work
-Use the `-turn` option to manually specify a TURN server address.
+
+Use the `-turn` option to manually specify a TURN server address. This should be a VK, Max, or Odnoklassniki server (VK link) or WB Stream (WB mode).
+
If TCP doesn't work, try adding the `-udp` flag.
+
Add `-n 1` for a more stable single-stream connection (limited to 5 Mbps for VK).
-## Yandex Telemost
-**UPD. TELEMOST IS CLOSED**
-Unlike VK, Yandex servers do not limit speed, so the default is `-n 1`.
+## VK Auth Flow
+
+1. **Token 1** — anonymous token (`login.vk.ru`)
+2. **getCallPreview** — call preview (optional)
+3. **Token 2** — anonymous token for the call (`api.vk.ru`)
+ - On captcha → PoW solving → retry
+4. **Token 3** — OK session key (`calls.okcdn.ru`)
+5. **Token 4** — TURN credentials (`calls.okcdn.ru`)
+
+## WB Auth Flow
+
+1. **Guest register** — guest registration (`stream.wb.ru`)
+2. **Create room** — create a room
+3. **Join room** — join the room
+4. **Get token** — get roomToken
+5. **LiveKit ICE** — WebSocket to LiveKit, protobuf TURN parsing
+
+## Caching
+
+- TTL: **10 minutes** (safety margin 60 seconds)
+- One cache per **4 streams** (`streamID / 4`)
+- Fast path via `RLock`
+- Fetch serialization via global `fetchMu`
+
+## v2ray
+
+Instead of WireGuard, you can use any V2Ray core that supports it (e.g., xray or sing-box) and any V2Ray client that uses this core (e.g., v2rayN or v2rayNG). This allows you to add more inbound interfaces (e.g., SOCKS) and implement fine-grained routing.
+
+Example configs:
+
+
+
+
+Client
+
+
+```json
+{
+ "inbounds": [
+ {
+ "protocol": "socks",
+ "listen": "127.0.0.1",
+ "port": 1080,
+ "settings": {
+ "udp": true
+ },
+ "sniffing": {
+ "enabled": true,
+ "destOverride": [
+ "http",
+ "tls"
+ ]
+ }
+ },
+ {
+ "protocol": "http",
+ "listen": "127.0.0.1",
+ "port": 8080,
+ "sniffing": {
+ "enabled": true,
+ "destOverride": [
+ "http",
+ "tls"
+ ]
+ }
+ }
+ ],
+ "outbounds": [
+ {
+ "protocol": "wireguard",
+ "settings": {
+ "secretKey": "",
+ "peers": [
+ {
+ "endpoint": "127.0.0.1:9000",
+ "publicKey": ""
+ }
+ ],
+ "domainStrategy": "ForceIPv4",
+ "mtu": 1280
+ }
+ }
+ ]
+}
+```
+
+
+
+
+
+
+Server
+
+
+```json
+{
+ "inbounds": [
+ {
+ "protocol": "wireguard",
+ "listen": "0.0.0.0",
+ "port": 51820,
+ "settings": {
+ "secretKey": "",
+ "peers": [
+ {
+ "publicKey": ""
+ }
+ ],
+ "mtu": 1280
+ },
+ "sniffing": {
+ "enabled": true,
+ "destOverride": [
+ "http",
+ "tls"
+ ]
+ }
+ }
+ ],
+ "outbounds": [
+ {
+ "protocol": "freedom",
+ "settings": {
+ "domainStrategy": "UseIPv4"
+ }
+ }
+ ]
+}
+```
+
+
## Direct mode
-With the `-no-dtls` flag, you can send packets without DTLS obfuscation and connect to regular WireGuard servers. This may result in a ban from VK/Yandex.
+
+With the `-no-dtls` flag, you can send packets without DTLS obfuscation and connect to regular WireGuard servers. This may result in a ban from VK/WB.
+
+Thanks to https://github.com/KillTheCensorship/Turnel for part of the code :)
+
+WB Stream functionality is based on https://github.com/jaykaiperson/lionheart
diff --git a/README.md b/README.md
index cad2029..f1aeca5 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,15 @@
-# Good TURN
+# VK/WB TURN Proxy
[English version](README.en.md)
-Проброс трафика WireGuard/Hysteria через TURN сервера VK звонков или Яндекс телемоста. Пакеты шифруются DTLS 1.2, затем параллельными потоками через TCP или UDP отправляются на TURN сервер по протоколу STUN ChannelData. Оттуда по UDP отправляются на ваш сервер, где расшифровываются и передаются в WireGuard. Логин/пароль от TURN генерируются из ссылки на звонок.
+Проброс трафика WireGuard/Hysteria через TURN сервера VK звонков или WB Stream. Пакеты шифруются DTLS 1.2, затем параллельными потоками через TCP или UDP отправляются на TURN сервер по протоколу STUN ChannelData. Оттуда по UDP отправляются на ваш сервер, где расшифровываются и передаются в WireGuard. Логин/пароль от TURN генерируются из ссылки на звонок.
+
+## Возможности
+
+- **VK Calls** — TURN credentials от VK API с автоматическим решением капчи (Not Robot)
+- **WB Stream** — TURN credentials от WB Stream API (LiveKit ICE)
+- **Кеширование** — 10 минут с общим кешем на 4 потока
+- **DTLS-обфускация** — обход DPI через DTLS-туннель
+- **Множественные соединения** — до N параллельных подключений к TURN
**Обновление: Многопользовательский прокси-сервер**
Текущая реализация поддерживает одновременную работу нескольких пользователей через один прокси-сервер.
@@ -11,18 +19,34 @@
- **Балансировка:** Исходящий трафик от сервера к клиенту распределяется между всеми активными DTLS-потоками пользователя (Round-Robin).
Только для учебных целей!
+
+## Структура клиента
+
+```
+client/
+├── credentials.go # Общий кеш credentials, сериализация запросов
+├── vk.go # VK API: Token 1→4 chain, HTTP-запросы
+├── vk_captcha.go # VK Captcha: PoW solving, Not Robot flow
+├── wb.go # WB Stream: guest register → room → LiveKit ICE
+└── main.go # DTLS/TURN соединения, CLI, основной цикл
+```
+
## Настройка
+
Нам понадобится:
1. Ссылка на действующий ВК звонок: создаём свой (нужен аккаунт вк), или гуглим `"https://vk.com/call/join/"`.
-Ссылка действительна вечно, если не нажимать "завершить звонок для всех"
-2. Или ссыска на звонок Яндекс телемоста: `"https://telemost.yandex.ru/j/"`. Её лучше не гуглить, так как видно подключение к конференции
-3. VPS с установленным WireGuard
-4. Для андроида: скачать Termux из F-Droid
+ Ссылка действительна вечно, если не нажимать "завершить звонок для всех"
+2. VPS с установленным WireGuard
+3. Для андроида: скачать Termux из F-Droid
+
### Сервер
+
```
./server -listen 0.0.0.0:56000 -connect 127.0.0.1:<порт wg>
```
+
### Клиент
+
#### Android
**Рекомендуемый способ:**
@@ -30,7 +54,8 @@
**Альтернативный способ (через Termux):**
- В клиентском конфиге WireGuard меняем адрес сервера на `127.0.0.1:9000`, ставим MTU 1280
-- **Добавляем Termux в исключения WireGuard. Нажимаем "сохранить".**
+- **Добавляем Termux в исключения WireGuard. Нажимаем "сохранить".**
+
В Termux:
```
termux-wake-lock
@@ -44,20 +69,27 @@ termux-wake-unlock
cp /sdcard/Download/client-android ./
chmod 777 ./client-android
```
-Запускаем:
+
+**VK режим:**
```
./client-android -peer :56000 -vk-link -listen 127.0.0.1:9000
```
-Дополнительные флаги:
-- `-session-id `: установить фиксированный ID сессии (32 символа hex).
-Или
+**WB режим:**
```
-./client-android -udp -turn 5.255.211.241 -peer :56000 -yandex-link -listen 127.0.0.1:9000
+./client-android -wb -peer :56000 -listen 127.0.0.1:9000
```
-**Если после включения VPN в терминале вылезают ошибки DNS, попробуйте в Wireguard включить VPN только для нужных приложений.**
+Дополнительные флаги:
+- `-session-id `: установить фиксированный ID сессии (32 символа hex).
+- `-n <число>`: количество подключений к TURN (по умолчанию 4).
+- `-udp`: использовать UDP для TURN (по умолчанию TCP).
+- `-turn `: переопределить адрес TURN сервера.
+- `-port `: переопределить порт TURN сервера.
+- `-no-dtls`: без DTLS-обфускации (может привести к бану).
+
#### Linux
+
В клиентском конфиге WireGuard меняем адрес сервера на `127.0.0.1:9000`, ставим MTU 1280
Скрипт будет добавлять маршруты к нужным ip:
@@ -67,11 +99,13 @@ chmod 777 ./client-android
```
```
-./client-linux -udp -turn 5.255.211.241 -peer :56000 -yandex-link -listen 127.0.0.1:9000 | sudo routes.sh
+./client-linux -wb -peer :56000 -listen 127.0.0.1:9000 | sudo routes.sh
```
Не включайте впн, пока программа не установит соединение! В отличие от андроида, здесь часть запросов будет идти через впн (dns и запрос подключения к turn)
+
#### Windows
+
В клиентском конфиге WireGuard меняем адрес сервера на `127.0.0.1:9000`, ставим MTU 1280
В PowerShell от Администратора (чтобы скрипт прописывал маршруты):
@@ -81,40 +115,42 @@ chmod 777 ./client-android
```
```
-./client.exe -udp -turn 5.255.211.241 -peer :56000 -yandex-link -listen 127.0.0.1:9000 | routes.ps1
+./client.exe -wb -peer :56000 -listen 127.0.0.1:9000 | routes.ps1
```
-Не включайте впн, пока программа не установит соединение! В отличие от андроида, здесь часть запросов будет идти через впн (dns и запрос подключения к turn)
+Не включайте впн, пока программа не установит соединение! В отличие от андродида, здесь часть запросов будет идти через впн (dns и запрос подключения к turn)
+
### Если не работает
-С помощью опции `-turn` можно указать адрес TURN сервера вручную. Это должен быть сервер ВК, Макса или Одноклассников (ссылка вк) или Яндекса (ссылка яндекса). Возможно потом составлю список.
+
+С помощью опции `-turn` можно указать адрес TURN сервера вручную. Это должен быть сервер ВК, Макса или Одноклассников (ссылка вк) или WB Stream (режим -wb).
Если не работает TCP, попробуйте добавить флаг `-udp`.
Добавьте флаг `-n 1` для более стабильного подключения в 1 поток (ограничение 5 Мбит/с для ВК)
-## Яндекс телемост
-**UPD. ТЕЛЕМОСТ ЗАКРЫЛИ**
+## VK Auth Flow
-В отличие от ВК, сервера яндекса не ограничивают скорость, так что по умолчанию стоит `-n 1`. Увеличение этого числа может привести к временной блокировке по IP из-за переполнения конференции фейковыми участниками.
+1. **Token 1** — анонимный токен (`login.vk.ru`)
+2. **getCallPreview** — превью звонка (опционально)
+3. **Token 2** — анонимный токен для звонка (`api.vk.ru`)
+ - При капче → PoW solving → retry
+4. **Token 3** — OK session key (`calls.okcdn.ru`)
+5. **Token 4** — TURN credentials (`calls.okcdn.ru`)
-В режиме `-udp` скорость обычно больше
+## WB Auth Flow
-Большинство диапазонов IP TURN серверов Яндекса не работают, указывайте вручную через `-turn`
-
-
- Рабочие IP
-
+1. **Guest register** — регистрация гостя (`stream.wb.ru`)
+2. **Create room** — создание комнаты
+3. **Join room** — подключение к комнате
+4. **Get token** — получение roomToken
+5. **LiveKit ICE** — WebSocket к LiveKit, protobuf парсинг TURN
+## Кеширование
- 5.255.211.241
- 5.255.211.242
- 5.255.211.243
- 5.255.211.245
- 5.255.211.246
-
-
-
-Спасибо https://github.com/KillTheCensorship/Turnel за часть кода :)
+- TTL: **10 минут** (safety margin 60 секунд)
+- Один кеш на **4 потока** (`streamID / 4`)
+- Fast path через `RLock`
+- Сериализация fetch через глобальный `fetchMu`
## v2ray
@@ -225,4 +261,9 @@ chmod 777 ./client-android
## Direct mode
-С флагом `-no-dtls` можно отправлять пакеты без обфускации DTLS и подключаться к обычным серверам Wireguard. Может привести к бану от вк/яндекса.
+
+С флагом `-no-dtls` можно отправлять пакеты без обфускации DTLS и подключаться к обычным серверам Wireguard. Может привести к бану от ВК/WB.
+
+Спасибо https://github.com/KillTheCensorship/Turnel за часть кода :)
+
+Функционал WB Stream основан на проекте https://github.com/jaykaiperson/lionheart
diff --git a/client/credentials.go b/client/credentials.go
new file mode 100644
index 0000000..9b0a2e2
--- /dev/null
+++ b/client/credentials.go
@@ -0,0 +1,151 @@
+// SPDX-FileCopyrightText: 2023 The Pion community
+// SPDX-License-Identifier: MIT
+
+package main
+
+import (
+ "context"
+ "log"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// getCredsFunc is the signature for credential retrieval functions
+type getCredsFunc func(context.Context, string, int) (string, string, string, error)
+
+// TurnCredentials stores cached TURN credentials
+type TurnCredentials struct {
+ Username string
+ Password string
+ ServerAddr string
+ ExpiresAt time.Time
+ Link string
+}
+
+// StreamCredentialsCache holds credentials cache for a single stream
+type StreamCredentialsCache struct {
+ creds TurnCredentials
+ mutex sync.RWMutex
+ errorCount atomic.Int32
+ lastErrorTime atomic.Int64
+}
+
+const (
+ credentialLifetime = 10 * time.Minute
+ cacheSafetyMargin = 60 * time.Second
+ maxCacheErrors = 3
+ errorWindow = 10 * time.Second
+ streamsPerCache = 4 // Number of streams sharing one credentials cache
+)
+
+// getCacheID returns the shared cache ID for a given stream ID
+func getCacheID(streamID int) int {
+ return streamID / streamsPerCache
+}
+
+// credentialsStore manages per-stream credentials caches
+var credentialsStore = struct {
+ mu sync.RWMutex
+ caches map[int]*StreamCredentialsCache
+}{
+ caches: make(map[int]*StreamCredentialsCache),
+}
+
+// getStreamCache returns or creates a shared cache for the given stream ID
+func getStreamCache(streamID int) *StreamCredentialsCache {
+ cacheID := getCacheID(streamID)
+
+ // Try read lock first for fast path
+ credentialsStore.mu.RLock()
+ cache, exists := credentialsStore.caches[cacheID]
+ credentialsStore.mu.RUnlock()
+
+ if exists {
+ return cache
+ }
+
+ // Need to create new cache
+ credentialsStore.mu.Lock()
+ defer credentialsStore.mu.Unlock()
+
+ // Double-check after acquiring write lock
+ if cache, exists = credentialsStore.caches[cacheID]; exists {
+ return cache
+ }
+
+ cache = &StreamCredentialsCache{}
+ credentialsStore.caches[cacheID] = cache
+ return cache
+}
+
+// invalidate invalidates the credentials cache for this stream
+func (c *StreamCredentialsCache) invalidate(streamID int) {
+ c.mutex.Lock()
+ c.creds = TurnCredentials{}
+ c.mutex.Unlock()
+
+ // Reset auth error counter
+ c.errorCount.Store(0)
+ c.lastErrorTime.Store(0)
+
+ log.Printf("[Auth] Credentials cache invalidated for stream %d", streamID)
+}
+
+// fetchMu serializes credential fetching to avoid API rate limiting
+var fetchMu sync.Mutex
+
+// fetchFunc is the signature for credential retrieval functions (without cache logic)
+type fetchFunc func(ctx context.Context, link string) (string, string, string, error)
+
+// serializeFetch wraps a fetch call with the global fetchMu to avoid API rate limiting
+func serializeFetch(ctx context.Context, link string, storeFn fetchFunc) (string, string, string, error) {
+ fetchMu.Lock()
+ defer fetchMu.Unlock()
+ return storeFn(ctx, link)
+}
+
+// getCredsCached checks cache before fetching credentials.
+// This is the general entry point for credential retrieval with caching.
+func getCredsCached(ctx context.Context, link string, streamID int, storeFn fetchFunc) (string, string, string, error) {
+ cache := getStreamCache(streamID)
+ cacheID := getCacheID(streamID)
+
+ cache.mutex.Lock()
+ defer cache.mutex.Unlock()
+
+ // Check cache - another stream may have populated it while waiting
+ if cache.creds.Link == link && time.Now().Before(cache.creds.ExpiresAt) {
+ expires := time.Until(cache.creds.ExpiresAt)
+ log.Printf("[Auth] Using cached credentials (cache=%d, expires in %v)", cacheID, expires)
+ return cache.creds.Username, cache.creds.Password, cache.creds.ServerAddr, nil
+ }
+
+ log.Printf("[Auth] Cache miss (cache=%d), starting credential fetch...", cacheID)
+
+ // Check context before long fetch
+ select {
+ case <-ctx.Done():
+ return "", "", "", ctx.Err()
+ default:
+ }
+
+ // Fetch credentials with global mutex to avoid API rate limiting
+ user, pass, addr, err := serializeFetch(ctx, link, storeFn)
+
+ if err != nil {
+ return "", "", "", err
+ }
+
+ // Store in cache
+ cache.creds = TurnCredentials{
+ Username: user,
+ Password: pass,
+ ServerAddr: addr,
+ ExpiresAt: time.Now().Add(credentialLifetime - cacheSafetyMargin),
+ Link: link,
+ }
+
+ log.Printf("[Auth] Success! Credentials cached until %v (cache=%d)", cache.creds.ExpiresAt, cacheID)
+ return user, pass, addr, nil
+}
diff --git a/client/main.go b/client/main.go
index 011c396..3e19922 100644
--- a/client/main.go
+++ b/client/main.go
@@ -4,18 +4,12 @@
package main
import (
- "bytes"
"context"
"crypto/tls"
- "encoding/json"
"flag"
"fmt"
- "io"
"log"
- "math/rand"
"net"
- "net/http"
- "net/url"
"os"
"os/signal"
"strings"
@@ -26,666 +20,12 @@ import (
"github.com/cbeuw/connutil"
"github.com/google/uuid"
- "github.com/gorilla/websocket"
"github.com/pion/dtls/v3"
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
"github.com/pion/logging"
"github.com/pion/turn/v5"
)
-type getCredsFunc func(context.Context, string, int) (string, string, string, error)
-
-const vkClientID = "6287487"
-const vkClientSecret = "QbYic1K3lEV5kTGiqlq2"
-const vkAPIVersion = "5.275"
-
-// TurnCredentials stores cached TURN credentials
-type TurnCredentials struct {
- Username string
- Password string
- ServerAddr string
- ExpiresAt time.Time
- Link string
-}
-
-// StreamCredentialsCache holds credentials cache for a single stream
-type StreamCredentialsCache struct {
- creds TurnCredentials
- mutex sync.RWMutex
- errorCount atomic.Int32
- lastErrorTime atomic.Int64
-}
-
-const (
- credentialLifetime = 10 * time.Minute
- cacheSafetyMargin = 60 * time.Second
- maxCacheErrors = 3
- errorWindow = 10 * time.Second
- streamsPerCache = 4 // Number of streams sharing one credentials cache
-)
-
-// getCacheID returns the shared cache ID for a given stream ID
-func getCacheID(streamID int) int {
- return streamID / streamsPerCache
-}
-
-// credentialsStore manages per-stream credentials caches
-var credentialsStore = struct {
- mu sync.RWMutex
- caches map[int]*StreamCredentialsCache
-}{
- caches: make(map[int]*StreamCredentialsCache),
-}
-
-// getStreamCache returns or creates a shared cache for the given stream ID
-func getStreamCache(streamID int) *StreamCredentialsCache {
- cacheID := getCacheID(streamID)
-
- // Try read lock first for fast path
- credentialsStore.mu.RLock()
- cache, exists := credentialsStore.caches[cacheID]
- credentialsStore.mu.RUnlock()
-
- if exists {
- return cache
- }
-
- // Need to create new cache
- credentialsStore.mu.Lock()
- defer credentialsStore.mu.Unlock()
-
- // Double-check after acquiring write lock
- if cache, exists = credentialsStore.caches[cacheID]; exists {
- return cache
- }
-
- cache = &StreamCredentialsCache{}
- credentialsStore.caches[cacheID] = cache
- return cache
-}
-
-// invalidate invalidates the credentials cache for this stream
-func (c *StreamCredentialsCache) invalidate(streamID int) {
- c.mutex.Lock()
- c.creds = TurnCredentials{}
- c.mutex.Unlock()
-
- // Reset auth error counter
- c.errorCount.Store(0)
- c.lastErrorTime.Store(0)
-
- log.Printf("[VK Auth] Credentials cache invalidated for stream %d", streamID)
-}
-
-func min(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
-
-// vkDelay sleeps for a random duration between minMs and maxMs to avoid bot detection
-func vkDelay(minMs, maxMs int) {
- ms := minMs + rand.Intn(maxMs-minMs+1)
- time.Sleep(time.Duration(ms) * time.Millisecond)
-}
-
-// vkCredsMu serializes VK credential fetching to avoid BOT detection from parallel requests
-var vkCredsMu sync.Mutex
-
-// getVkCredsCached checks cache before fetching credentials
-func getVkCredsCached(ctx context.Context, link string, streamID int) (string, string, string, error) {
- cache := getStreamCache(streamID)
- cacheID := getCacheID(streamID)
-
- cache.mutex.Lock()
- defer cache.mutex.Unlock()
-
- // Check cache - another stream may have populated it while waiting
- if cache.creds.Link == link && time.Now().Before(cache.creds.ExpiresAt) {
- expires := time.Until(cache.creds.ExpiresAt)
- log.Printf("[VK Auth] Using cached credentials (cache=%d, expires in %v)", cacheID, expires)
- return cache.creds.Username, cache.creds.Password, cache.creds.ServerAddr, nil
- }
-
- log.Printf("[VK Auth] Cache miss (cache=%d), starting credential fetch...", cacheID)
-
- // Check context before long fetch
- select {
- case <-ctx.Done():
- return "", "", "", ctx.Err()
- default:
- }
-
- // Fetch credentials with mutex to avoid VK flood control
- user, pass, addr, err := getVkCredsSafe(ctx, link, streamID)
- if err != nil {
- return "", "", "", err
- }
-
- // Store in cache
- cache.creds = TurnCredentials{
- Username: user,
- Password: pass,
- ServerAddr: addr,
- ExpiresAt: time.Now().Add(credentialLifetime - cacheSafetyMargin),
- Link: link,
- }
-
- log.Printf("[VK Auth] Success! Credentials cached until %v (cache=%d)", cache.creds.ExpiresAt, cacheID)
- return user, pass, addr, nil
-}
-
-// getVkCredsSafe wraps getVkCreds with mutex to avoid VK flood control
-func getVkCredsSafe(ctx context.Context, link string, streamID int) (string, string, string, error) {
- vkCredsMu.Lock()
- defer vkCredsMu.Unlock()
- return getVkCreds(ctx, link)
-}
-
-func vkHTTPPost(ctx context.Context, data string, url string) (map[string]interface{}, error) {
- client := &http.Client{
- Timeout: 20 * time.Second,
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: 90 * time.Second,
- },
- }
- defer client.CloseIdleConnections()
- req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer([]byte(data)))
- if err != nil {
- return nil, err
- }
- // Headers matching HAR capture exactly
- req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Set("Accept", "*/*")
- req.Header.Set("Accept-Language", "en-US,en;q=0.9")
- req.Header.Set("Origin", "https://vk.ru")
- req.Header.Set("Referer", "https://vk.ru/")
- req.Header.Set("sec-ch-ua-platform", `"Windows"`)
- req.Header.Set("sec-ch-ua", `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`)
- req.Header.Set("sec-ch-ua-mobile", "?0")
- req.Header.Set("Sec-Fetch-Site", "same-site")
- req.Header.Set("Sec-Fetch-Mode", "cors")
- req.Header.Set("Sec-Fetch-Dest", "empty")
- req.Header.Set("DNT", "1")
- req.Header.Set("Priority", "u=1, i")
-
- httpResp, err := client.Do(req)
- if err != nil {
- return nil, err
- }
- defer httpResp.Body.Close()
-
- // Handle HTTP errors (redirects, rate limits, etc.)
- if httpResp.StatusCode >= 400 {
- body, _ := io.ReadAll(httpResp.Body)
- return nil, fmt.Errorf("HTTP %d from %s: %s", httpResp.StatusCode, req.URL, string(body[:min(len(body), 500)]))
- }
-
- body, err := io.ReadAll(httpResp.Body)
- if err != nil {
- return nil, err
- }
-
- // Check content type - VK may return HTML instead of JSON (captcha page, redirect, etc.)
- contentType := httpResp.Header.Get("Content-Type")
- if contentType != "" && !strings.Contains(contentType, "application/json") && !strings.Contains(contentType, "text/javascript") {
- // Log first 500 chars of non-JSON response for debugging
- logPreview := string(body)
- if len(logPreview) > 500 {
- logPreview = logPreview[:500] + "...(truncated)"
- }
- return nil, fmt.Errorf("unexpected content-type %s, status %d, body: %s", contentType, httpResp.StatusCode, logPreview)
- }
-
- var resp map[string]interface{}
- if err = json.Unmarshal(body, &resp); err != nil {
- // Log the raw body for debugging
- logPreview := string(body)
- if len(logPreview) > 500 {
- logPreview = logPreview[:500] + "...(truncated)"
- }
- return nil, fmt.Errorf("JSON parse error: %w, body: %s", err, logPreview)
- }
- return resp, nil
-}
-
-func getVkCreds(ctx context.Context, link string) (string, string, string, error) {
- // Token 1 (messages)
- log.Println("[VK Auth] Getting Token 1...")
- data := fmt.Sprintf("client_id=%s&token_type=messages&client_secret=%s&version=1&app_id=%s",
- vkClientID, vkClientSecret, vkClientID)
- resp, err := vkHTTPPost(ctx, data, "https://login.vk.ru/?act=get_anonym_token")
- if err != nil {
- return "", "", "", fmt.Errorf("Token 1 request error: %w", err)
- }
- if errMsg, ok := resp["error"].(map[string]interface{}); ok {
- return "", "", "", fmt.Errorf("Token 1 VK error: %v", errMsg)
- }
- dataObj, ok := resp["data"].(map[string]interface{})
- if !ok {
- return "", "", "", fmt.Errorf("invalid Token 1 response: %v", resp)
- }
- token1, ok := dataObj["access_token"].(string)
- if !ok {
- return "", "", "", fmt.Errorf("access_token not found in Token 1 response")
- }
- log.Println("[VK Auth] Token 1 received")
- vkDelay(100, 200) // Token 1 → getCallPreview
-
- // getCallPreview (optional, like browser)
- log.Println("[VK Auth] Getting call preview...")
- cpData := fmt.Sprintf("vk_join_link=https://vk.ru/call/join/%s&fields=photo_200&access_token=%s",
- url.QueryEscape(link), token1)
- cpURL := fmt.Sprintf("https://api.vk.ru/method/calls.getCallPreview?v=%s&client_id=%s", vkAPIVersion, vkClientID)
- _, _ = vkHTTPPost(ctx, cpData, cpURL) // non-critical
- vkDelay(500, 1000) // getCallPreview → Token 2
-
- // Token 2 (may require captcha)
- log.Println("[VK Auth] Getting Token 2...")
- t2Data := fmt.Sprintf("vk_join_link=https://vk.ru/call/join/%s&name=123&access_token=%s",
- url.QueryEscape(link), token1)
- t2URL := fmt.Sprintf("https://api.vk.ru/method/calls.getAnonymousToken?v=%s&client_id=%s", vkAPIVersion, vkClientID)
- resp, err = vkHTTPPost(ctx, t2Data, t2URL)
- if err != nil {
- return "", "", "", fmt.Errorf("Token 2 request error: %w", err)
- }
-
- // Check for captcha error
- if errMsg, ok := resp["error"].(map[string]interface{}); ok {
- captchaData, isCaptcha := ExtractCaptchaData(errMsg)
- if !isCaptcha {
- return "", "", "", fmt.Errorf("Token 2 VK error: %v", errMsg)
- }
-
- log.Printf("[VK Auth] Captcha detected, solving...")
- successToken, solveErr := SolveVkCaptcha(ctx, captchaData)
- if solveErr != nil {
- return "", "", "", fmt.Errorf("captcha solving failed: %w", solveErr)
- }
-
- // Delay before retry (endSession → Token 2 retry)
- vkDelay(100, 200)
-
- // Retry Token 2 with captcha solution
- log.Println("[VK Auth] Retrying Token 2 with captcha solution...")
- t2Data = fmt.Sprintf(
- "vk_join_link=https://vk.ru/call/join/%s&name=123"+
- "&captcha_key=&captcha_sid=%s&is_sound_captcha=0"+
- "&success_token=%s&captcha_ts=%s&captcha_attempt=%s"+
- "&access_token=%s",
- url.QueryEscape(link),
- captchaData.CaptchaSid,
- successToken,
- captchaData.CaptchaTs,
- captchaData.CaptchaAttempt,
- token1,
- )
- resp, err = vkHTTPPost(ctx, t2Data, t2URL)
- if err != nil {
- return "", "", "", fmt.Errorf("Token 2 retry request error: %w", err)
- }
- if errMsg2, ok := resp["error"].(map[string]interface{}); ok {
- return "", "", "", fmt.Errorf("Token 2 retry VK error: %v", errMsg2)
- }
- // Token 2 retry → Token 3
- vkDelay(100, 200)
- }
-
- token2Obj, ok := resp["response"].(map[string]interface{})
- if !ok {
- return "", "", "", fmt.Errorf("invalid Token 2 response: %v", resp)
- }
- token2, ok := token2Obj["token"].(string)
- if !ok {
- return "", "", "", fmt.Errorf("token not found in Token 2 response")
- }
- log.Println("[VK Auth] Token 2 received")
- // Token 2 → Token 3
- vkDelay(100, 200)
-
- // Token 3 (OK auth.anonymLogin)
- log.Println("[VK Auth] Getting Token 3...")
- sessionData := fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":1.1,"client_type":"SDK_JS"}`, uuid.New())
- t3Data := fmt.Sprintf("session_data=%s&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA",
- url.QueryEscape(sessionData))
- resp, err = vkHTTPPost(ctx, t3Data, "https://calls.okcdn.ru/fb.do")
- if err != nil {
- return "", "", "", fmt.Errorf("Token 3 request error: %w", err)
- }
- if errMsg, ok := resp["error"].(string); ok && errMsg != "" {
- return "", "", "", fmt.Errorf("Token 3 API error: %s", errMsg)
- }
- token3, ok := resp["session_key"].(string)
- if !ok {
- return "", "", "", fmt.Errorf("session_key not found in Token 3 response")
- }
- log.Println("[VK Auth] Token 3 received")
- // Token 3 → Final (TURN)
- vkDelay(100, 200)
-
- // Final: vchat.joinConversationByLink (Token 4)
- log.Println("[VK Auth] Getting TURN credentials (Token 4)...")
- finalData := fmt.Sprintf(
- "joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s",
- url.QueryEscape(link), token2, token3)
- resp, err = vkHTTPPost(ctx, finalData, "https://calls.okcdn.ru/fb.do")
- if err != nil {
- return "", "", "", fmt.Errorf("Final request error: %w", err)
- }
- if errMsg, ok := resp["error"].(string); ok && errMsg != "" {
- return "", "", "", fmt.Errorf("Final API error: %s", errMsg)
- }
-
- ts, ok := resp["turn_server"].(map[string]interface{})
- if !ok {
- return "", "", "", fmt.Errorf("turn_server not found in response: %v", resp)
- }
- urls, _ := ts["urls"].([]interface{})
- if len(urls) == 0 {
- return "", "", "", fmt.Errorf("urls not found in turn_server")
- }
- urlStr, _ := urls[0].(string)
- clean := strings.Split(urlStr, "?")[0]
- address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
-
- username, _ := ts["username"].(string)
- credential, _ := ts["credential"].(string)
-
- if username == "" || credential == "" {
- return "", "", "", fmt.Errorf("username or credential not found in turn_server")
- }
-
- log.Println("[VK Auth] TURN credentials received")
- vkDelay(1500, 2500) // Final delay before exit
- return username, credential, address, nil
-}
-
-func getYandexCreds(ctx context.Context, link string, streamID int) (string, string, string, error) {
- const debug = false
- const telemostConfHost = "cloud-api.yandex.ru"
- telemostConfPath := fmt.Sprintf("%s%s%s", "/telemost_front/v2/telemost/conferences/https%3A%2F%2Ftelemost.yandex.ru%2Fj%2F", link, "/connection?next_gen_media_platform_allowed=false")
- const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"
-
- type ConferenceResponse struct {
- URI string `json:"uri"`
- RoomID string `json:"room_id"`
- PeerID string `json:"peer_id"`
- ClientConfiguration struct {
- MediaServerURL string `json:"media_server_url"`
- } `json:"client_configuration"`
- Credentials string `json:"credentials"`
- }
-
- type PartMeta struct {
- Name string `json:"name"`
- Role string `json:"role"`
- Description string `json:"description"`
- SendAudio bool `json:"sendAudio"`
- SendVideo bool `json:"sendVideo"`
- }
-
- type PartAttrs struct {
- Name string `json:"name"`
- Role string `json:"role"`
- Description string `json:"description"`
- }
-
- type SdkInfo struct {
- Implementation string `json:"implementation"`
- Version string `json:"version"`
- UserAgent string `json:"userAgent"`
- HwConcurrency int `json:"hwConcurrency"`
- }
-
- type Capabilities struct {
- OfferAnswerMode []string `json:"offerAnswerMode"`
- InitialSubscriberOffer []string `json:"initialSubscriberOffer"`
- SlotsMode []string `json:"slotsMode"`
- SimulcastMode []string `json:"simulcastMode"`
- SelfVadStatus []string `json:"selfVadStatus"`
- DataChannelSharing []string `json:"dataChannelSharing"`
- VideoEncoderConfig []string `json:"videoEncoderConfig"`
- DataChannelVideoCodec []string `json:"dataChannelVideoCodec"`
- BandwidthLimitationReason []string `json:"bandwidthLimitationReason"`
- SdkDefaultDeviceManagement []string `json:"sdkDefaultDeviceManagement"`
- JoinOrderLayout []string `json:"joinOrderLayout"`
- PinLayout []string `json:"pinLayout"`
- SendSelfViewVideoSlot []string `json:"sendSelfViewVideoSlot"`
- ServerLayoutTransition []string `json:"serverLayoutTransition"`
- SdkPublisherOptimizeBitrate []string `json:"sdkPublisherOptimizeBitrate"`
- SdkNetworkLostDetection []string `json:"sdkNetworkLostDetection"`
- SdkNetworkPathMonitor []string `json:"sdkNetworkPathMonitor"`
- PublisherVp9 []string `json:"publisherVp9"`
- SvcMode []string `json:"svcMode"`
- SubscriberOfferAsyncAck []string `json:"subscriberOfferAsyncAck"`
- SvcModes []string `json:"svcModes"`
- ReportTelemetryModes []string `json:"reportTelemetryModes"`
- KeepDefaultDevicesModes []string `json:"keepDefaultDevicesModes"`
- }
-
- type HelloPayload struct {
- ParticipantMeta PartMeta `json:"participantMeta"`
- ParticipantAttributes PartAttrs `json:"participantAttributes"`
- SendAudio bool `json:"sendAudio"`
- SendVideo bool `json:"sendVideo"`
- SendSharing bool `json:"sendSharing"`
- ParticipantID string `json:"participantId"`
- RoomID string `json:"roomId"`
- ServiceName string `json:"serviceName"`
- Credentials string `json:"credentials"`
- CapabilitiesOffer Capabilities `json:"capabilitiesOffer"`
- SdkInfo SdkInfo `json:"sdkInfo"`
- SdkInitializationID string `json:"sdkInitializationId"`
- DisablePublisher bool `json:"disablePublisher"`
- DisableSubscriber bool `json:"disableSubscriber"`
- DisableSubscriberAudio bool `json:"disableSubscriberAudio"`
- }
-
- type HelloRequest struct {
- UID string `json:"uid"`
- Hello HelloPayload `json:"hello"`
- }
-
- type FlexUrls []string
-
- type WSSResponse struct {
- UID string `json:"uid"`
- ServerHello struct {
- RtcConfiguration struct {
- IceServers []struct {
- Urls FlexUrls `json:"urls"`
- Username string `json:"username,omitempty"`
- Credential string `json:"credential,omitempty"`
- } `json:"iceServers"`
- } `json:"rtcConfiguration"`
- } `json:"serverHello"`
- }
-
- type WSSAck struct {
- Uid string `json:"uid"`
- Ack struct {
- Status struct {
- Code string `json:"code"`
- } `json:"status"`
- } `json:"ack"`
- }
-
- type WSSData struct {
- ParticipantId string
- RoomId string
- Credentials string
- Wss string
- }
-
- endpoint := "https://" + telemostConfHost + telemostConfPath
- client := &http.Client{
- Timeout: 20 * time.Second,
- Transport: &http.Transport{
- MaxIdleConns: 100,
- MaxIdleConnsPerHost: 100,
- IdleConnTimeout: 90 * time.Second,
- },
- }
- defer client.CloseIdleConnections()
- req, err := http.NewRequest("GET", endpoint, nil)
- if err != nil {
- return "", "", "", err
- }
- req.Header.Set("User-Agent", userAgent)
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Referer", "https://telemost.yandex.ru/")
- req.Header.Set("Origin", "https://telemost.yandex.ru")
- req.Header.Set("Client-Instance-Id", uuid.New().String())
-
- resp, err := client.Do(req)
- if err != nil {
- return "", "", "", err
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- body, _ := io.ReadAll(resp.Body)
- return "", "", "", fmt.Errorf("GetConference: status=%s body=%s", resp.Status, string(body))
- }
-
- var result ConferenceResponse
- if err = json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return "", "", "", fmt.Errorf("decode conf: %v", err)
- }
- data := WSSData{
- ParticipantId: result.PeerID,
- RoomId: result.RoomID,
- Credentials: result.Credentials,
- Wss: result.ClientConfiguration.MediaServerURL,
- }
- h := http.Header{}
- h.Set("Origin", "https://telemost.yandex.ru")
- h.Set("User-Agent", userAgent)
-
- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
- defer cancel()
-
- dialer := websocket.Dialer{}
- conn, _, err := dialer.DialContext(ctx, data.Wss, h)
- if err != nil {
- return "", "", "", fmt.Errorf("ws dial: %w", err)
- }
- defer conn.Close()
-
- req1 := HelloRequest{
- UID: uuid.New().String(),
- Hello: HelloPayload{
- ParticipantMeta: PartMeta{
- Name: "Гость",
- Role: "SPEAKER",
- Description: "",
- SendAudio: false,
- SendVideo: false,
- },
- ParticipantAttributes: PartAttrs{
- Name: "Гость",
- Role: "SPEAKER",
- Description: "",
- },
- SendAudio: false,
- SendVideo: false,
- SendSharing: false,
-
- ParticipantID: data.ParticipantId,
- RoomID: data.RoomId,
- ServiceName: "telemost",
- Credentials: data.Credentials,
- SdkInfo: SdkInfo{
- Implementation: "browser",
- Version: "5.15.0",
- UserAgent: userAgent,
- HwConcurrency: 4,
- },
- SdkInitializationID: uuid.New().String(),
- DisablePublisher: false,
- DisableSubscriber: false,
- DisableSubscriberAudio: false,
- CapabilitiesOffer: Capabilities{
- OfferAnswerMode: []string{"SEPARATE"},
- InitialSubscriberOffer: []string{"ON_HELLO"},
- SlotsMode: []string{"FROM_CONTROLLER"},
- SimulcastMode: []string{"DISABLED"},
- SelfVadStatus: []string{"FROM_SERVER"},
- DataChannelSharing: []string{"TO_RTP"},
- VideoEncoderConfig: []string{"NO_CONFIG"},
- DataChannelVideoCodec: []string{"VP8"},
- BandwidthLimitationReason: []string{"BANDWIDTH_REASON_DISABLED"},
- SdkDefaultDeviceManagement: []string{"SDK_DEFAULT_DEVICE_MANAGEMENT_DISABLED"},
- JoinOrderLayout: []string{"JOIN_ORDER_LAYOUT_DISABLED"},
- PinLayout: []string{"PIN_LAYOUT_DISABLED"},
- SendSelfViewVideoSlot: []string{"SEND_SELF_VIEW_VIDEO_SLOT_DISABLED"},
- ServerLayoutTransition: []string{"SERVER_LAYOUT_TRANSITION_DISABLED"},
- SdkPublisherOptimizeBitrate: []string{"SDK_PUBLISHER_OPTIMIZE_BITRATE_DISABLED"},
- SdkNetworkLostDetection: []string{"SDK_NETWORK_LOST_DETECTION_DISABLED"},
- SdkNetworkPathMonitor: []string{"SDK_NETWORK_PATH_MONITOR_DISABLED"},
- PublisherVp9: []string{"PUBLISH_VP9_DISABLED"},
- SvcMode: []string{"SVC_MODE_DISABLED"},
- SubscriberOfferAsyncAck: []string{"SUBSCRIBER_OFFER_ASYNC_ACK_DISABLED"},
- SvcModes: []string{"FALSE"},
- ReportTelemetryModes: []string{"TRUE"},
- KeepDefaultDevicesModes: []string{"TRUE"},
- },
- },
- }
-
- if debug {
- b, _ := json.MarshalIndent(req1, "", " ")
- log.Printf("Sending HELLO:\n%s", string(b))
- }
-
- if err := conn.WriteJSON(req1); err != nil {
- return "", "", "", fmt.Errorf("ws write: %w", err)
- }
-
- conn.SetReadDeadline(time.Now().Add(15 * time.Second))
-
- for {
- _, msg, err := conn.ReadMessage()
- if err != nil {
- return "", "", "", fmt.Errorf("ws read: %w", err)
- }
- if debug {
- s := string(msg)
- if len(s) > 800 {
- s = s[:800] + "...(truncated)"
- }
- log.Printf("WSS recv: %s", s)
- }
-
- var ack WSSAck
- if err := json.Unmarshal(msg, &ack); err == nil && ack.Ack.Status.Code != "" {
- continue
- }
-
- var resp WSSResponse
- if err := json.Unmarshal(msg, &resp); err == nil {
- ice := resp.ServerHello.RtcConfiguration.IceServers
- for _, s := range ice {
- for _, u := range s.Urls {
- if !strings.HasPrefix(u, "turn:") && !strings.HasPrefix(u, "turns:") {
- continue
- }
- if strings.Contains(u, "transport=tcp") {
- continue
- }
- clean := strings.Split(u, "?")[0]
- address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
-
- return s.Username, s.Credential, address, nil
- }
- }
- }
- }
-}
-
func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.Conn, error) {
certificate, err := selfsign.GenerateSelfSigned()
if err != nil {
@@ -1087,9 +427,9 @@ func main() { //nolint:cyclop
port := flag.String("port", "", "override TURN port")
listen := flag.String("listen", "127.0.0.1:9000", "listen on ip:port")
vklink := flag.String("vk-link", "", "VK calls invite link \"https://vk.com/call/join/...\"")
- yalink := flag.String("yandex-link", "", "Yandex telemost invite link \"https://telemost.yandex.ru/j/...\"")
+ wb := flag.Bool("wb", false, "use WB Stream instead of VK")
peerAddr := flag.String("peer", "", "peer server address (host:port)")
- n := flag.Int("n", 0, "connections to TURN (default 16 for VK, 1 for Yandex)")
+ n := flag.Int("n", 0, "connections to TURN (default 4)")
udp := flag.Bool("udp", false, "connect to TURN with UDP")
direct := flag.Bool("no-dtls", false, "connect without obfuscation. DO NOT USE")
sessionIDFlag := flag.String("session-id", "", "override session ID (hex, 32 chars)")
@@ -1101,26 +441,29 @@ func main() { //nolint:cyclop
if err != nil {
panic(err)
}
- if (*vklink == "") == (*yalink == "") {
- log.Panicf("Need either vk-link or yandex-link!")
+ if !*wb && *vklink == "" {
+ log.Panicf("Need either -wb or -vk-link!")
}
+
var link string
var getCreds getCredsFunc
- if *vklink != "" {
- parts := strings.Split(*vklink, "join/")
- link = parts[len(parts)-1]
- getCreds = getVkCredsCached
- if *n <= 0 {
- *n = 4
+
+ if *wb {
+ link = "wb"
+ getCreds = func(ctx context.Context, lk string, streamID int) (string, string, string, error) {
+ return getCredsCached(ctx, lk, streamID, wbFetch)
}
} else {
- parts := strings.Split(*yalink, "j/")
+ parts := strings.Split(*vklink, "join/")
link = parts[len(parts)-1]
- getCreds = getYandexCreds
- if *n <= 0 {
- *n = 1
+ getCreds = func(ctx context.Context, lk string, streamID int) (string, string, string, error) {
+ return getCredsCached(ctx, lk, streamID, getVkCreds)
}
}
+
+ if *n <= 0 {
+ *n = 4
+ }
if idx := strings.IndexAny(link, "/?#"); idx != -1 {
link = link[:idx]
}
diff --git a/client/vk.go b/client/vk.go
new file mode 100644
index 0000000..a75c55b
--- /dev/null
+++ b/client/vk.go
@@ -0,0 +1,258 @@
+// SPDX-FileCopyrightText: 2023 The Pion community
+// SPDX-License-Identifier: MIT
+
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "math/rand"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const vkClientID = "6287487"
+const vkClientSecret = "QbYic1K3lEV5kTGiqlq2"
+const vkAPIVersion = "5.275"
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
+
+// vkDelay sleeps for a random duration between minMs and maxMs to avoid bot detection
+func vkDelay(minMs, maxMs int) {
+ ms := minMs + rand.Intn(maxMs-minMs+1)
+ time.Sleep(time.Duration(ms) * time.Millisecond)
+}
+
+func vkHTTPPost(ctx context.Context, data string, url string) (map[string]interface{}, error) {
+ client := &http.Client{
+ Timeout: 20 * time.Second,
+ Transport: &http.Transport{
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 100,
+ IdleConnTimeout: 90 * time.Second,
+ },
+ }
+ defer client.CloseIdleConnections()
+ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer([]byte(data)))
+ if err != nil {
+ return nil, err
+ }
+ // Headers matching HAR capture exactly
+ req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "*/*")
+ req.Header.Set("Accept-Language", "en-US,en;q=0.9")
+ req.Header.Set("Origin", "https://vk.ru")
+ req.Header.Set("Referer", "https://vk.ru/")
+ req.Header.Set("sec-ch-ua-platform", `"Windows"`)
+ req.Header.Set("sec-ch-ua", `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`)
+ req.Header.Set("sec-ch-ua-mobile", "?0")
+ req.Header.Set("Sec-Fetch-Site", "same-site")
+ req.Header.Set("Sec-Fetch-Mode", "cors")
+ req.Header.Set("Sec-Fetch-Dest", "empty")
+ req.Header.Set("DNT", "1")
+ req.Header.Set("Priority", "u=1, i")
+
+ httpResp, err := client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer httpResp.Body.Close()
+
+ // Handle HTTP errors (redirects, rate limits, etc.)
+ if httpResp.StatusCode >= 400 {
+ body, _ := io.ReadAll(httpResp.Body)
+ return nil, fmt.Errorf("HTTP %d from %s: %s", httpResp.StatusCode, req.URL, string(body[:min(len(body), 500)]))
+ }
+
+ body, err := io.ReadAll(httpResp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ // Check content type - VK may return HTML instead of JSON (captcha page, redirect, etc.)
+ contentType := httpResp.Header.Get("Content-Type")
+ if contentType != "" && !strings.Contains(contentType, "application/json") && !strings.Contains(contentType, "text/javascript") {
+ // Log first 500 chars of non-JSON response for debugging
+ logPreview := string(body)
+ if len(logPreview) > 500 {
+ logPreview = logPreview[:500] + "...(truncated)"
+ }
+ return nil, fmt.Errorf("unexpected content-type %s, status %d, body: %s", contentType, httpResp.StatusCode, logPreview)
+ }
+
+ var resp map[string]interface{}
+ if err = json.Unmarshal(body, &resp); err != nil {
+ // Log the raw body for debugging
+ logPreview := string(body)
+ if len(logPreview) > 500 {
+ logPreview = logPreview[:500] + "...(truncated)"
+ }
+ return nil, fmt.Errorf("JSON parse error: %w, body: %s", err, logPreview)
+ }
+ return resp, nil
+}
+
+func getVkCreds(ctx context.Context, link string) (string, string, string, error) {
+ // Token 1 (messages)
+ log.Println("[VK Auth] Getting Token 1...")
+ data := fmt.Sprintf("client_id=%s&token_type=messages&client_secret=%s&version=1&app_id=%s",
+ vkClientID, vkClientSecret, vkClientID)
+ resp, err := vkHTTPPost(ctx, data, "https://login.vk.ru/?act=get_anonym_token")
+ if err != nil {
+ return "", "", "", fmt.Errorf("Token 1 request error: %w", err)
+ }
+ if errMsg, ok := resp["error"].(map[string]interface{}); ok {
+ return "", "", "", fmt.Errorf("Token 1 VK error: %v", errMsg)
+ }
+ dataObj, ok := resp["data"].(map[string]interface{})
+ if !ok {
+ return "", "", "", fmt.Errorf("invalid Token 1 response: %v", resp)
+ }
+ token1, ok := dataObj["access_token"].(string)
+ if !ok {
+ return "", "", "", fmt.Errorf("access_token not found in Token 1 response")
+ }
+ log.Println("[VK Auth] Token 1 received")
+ vkDelay(100, 200) // Token 1 → getCallPreview
+
+ // getCallPreview (optional, like browser)
+ log.Println("[VK Auth] Getting call preview...")
+ cpData := fmt.Sprintf("vk_join_link=https://vk.ru/call/join/%s&fields=photo_200&access_token=%s",
+ url.QueryEscape(link), token1)
+ cpURL := fmt.Sprintf("https://api.vk.ru/method/calls.getCallPreview?v=%s&client_id=%s", vkAPIVersion, vkClientID)
+ _, _ = vkHTTPPost(ctx, cpData, cpURL) // non-critical
+ vkDelay(500, 1000) // getCallPreview → Token 2
+
+ // Token 2 (may require captcha)
+ log.Println("[VK Auth] Getting Token 2...")
+ t2Data := fmt.Sprintf("vk_join_link=https://vk.ru/call/join/%s&name=123&access_token=%s",
+ url.QueryEscape(link), token1)
+ t2URL := fmt.Sprintf("https://api.vk.ru/method/calls.getAnonymousToken?v=%s&client_id=%s", vkAPIVersion, vkClientID)
+ resp, err = vkHTTPPost(ctx, t2Data, t2URL)
+ if err != nil {
+ return "", "", "", fmt.Errorf("Token 2 request error: %w", err)
+ }
+
+ // Check for captcha error
+ if errMsg, ok := resp["error"].(map[string]interface{}); ok {
+ captchaData, isCaptcha := ExtractCaptchaData(errMsg)
+ if !isCaptcha {
+ return "", "", "", fmt.Errorf("Token 2 VK error: %v", errMsg)
+ }
+
+ log.Printf("[VK Auth] Captcha detected, solving...")
+ successToken, solveErr := SolveVkCaptcha(ctx, captchaData)
+ if solveErr != nil {
+ return "", "", "", fmt.Errorf("captcha solving failed: %w", solveErr)
+ }
+
+ // Delay before retry (endSession → Token 2 retry)
+ vkDelay(100, 200)
+
+ // Retry Token 2 with captcha solution
+ log.Println("[VK Auth] Retrying Token 2 with captcha solution...")
+ t2Data = fmt.Sprintf(
+ "vk_join_link=https://vk.ru/call/join/%s&name=123"+
+ "&captcha_key=&captcha_sid=%s&is_sound_captcha=0"+
+ "&success_token=%s&captcha_ts=%s&captcha_attempt=%s"+
+ "&access_token=%s",
+ url.QueryEscape(link),
+ captchaData.CaptchaSid,
+ successToken,
+ captchaData.CaptchaTs,
+ captchaData.CaptchaAttempt,
+ token1,
+ )
+ resp, err = vkHTTPPost(ctx, t2Data, t2URL)
+ if err != nil {
+ return "", "", "", fmt.Errorf("Token 2 retry request error: %w", err)
+ }
+ if errMsg2, ok := resp["error"].(map[string]interface{}); ok {
+ return "", "", "", fmt.Errorf("Token 2 retry VK error: %v", errMsg2)
+ }
+ // Token 2 retry → Token 3
+ vkDelay(100, 200)
+ }
+
+ token2Obj, ok := resp["response"].(map[string]interface{})
+ if !ok {
+ return "", "", "", fmt.Errorf("invalid Token 2 response: %v", resp)
+ }
+ token2, ok := token2Obj["token"].(string)
+ if !ok {
+ return "", "", "", fmt.Errorf("token not found in Token 2 response")
+ }
+ log.Println("[VK Auth] Token 2 received")
+ // Token 2 → Token 3
+ vkDelay(100, 200)
+
+ // Token 3 (OK auth.anonymLogin)
+ log.Println("[VK Auth] Getting Token 3...")
+ sessionData := fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":1.1,"client_type":"SDK_JS"}`, uuid.New())
+ t3Data := fmt.Sprintf("session_data=%s&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA",
+ url.QueryEscape(sessionData))
+ resp, err = vkHTTPPost(ctx, t3Data, "https://calls.okcdn.ru/fb.do")
+ if err != nil {
+ return "", "", "", fmt.Errorf("Token 3 request error: %w", err)
+ }
+ if errMsg, ok := resp["error"].(string); ok && errMsg != "" {
+ return "", "", "", fmt.Errorf("Token 3 API error: %s", errMsg)
+ }
+ token3, ok := resp["session_key"].(string)
+ if !ok {
+ return "", "", "", fmt.Errorf("session_key not found in Token 3 response")
+ }
+ log.Println("[VK Auth] Token 3 received")
+ // Token 3 → Final (TURN)
+ vkDelay(100, 200)
+
+ // Final: vchat.joinConversationByLink (Token 4)
+ log.Println("[VK Auth] Getting TURN credentials (Token 4)...")
+ finalData := fmt.Sprintf(
+ "joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s",
+ url.QueryEscape(link), token2, token3)
+ resp, err = vkHTTPPost(ctx, finalData, "https://calls.okcdn.ru/fb.do")
+ if err != nil {
+ return "", "", "", fmt.Errorf("Final request error: %w", err)
+ }
+ if errMsg, ok := resp["error"].(string); ok && errMsg != "" {
+ return "", "", "", fmt.Errorf("Final API error: %s", errMsg)
+ }
+
+ ts, ok := resp["turn_server"].(map[string]interface{})
+ if !ok {
+ return "", "", "", fmt.Errorf("turn_server not found in response: %v", resp)
+ }
+ urls, _ := ts["urls"].([]interface{})
+ if len(urls) == 0 {
+ return "", "", "", fmt.Errorf("urls not found in turn_server")
+ }
+ urlStr, _ := urls[0].(string)
+ clean := strings.Split(urlStr, "?")[0]
+ address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
+
+ username, _ := ts["username"].(string)
+ credential, _ := ts["credential"].(string)
+
+ if username == "" || credential == "" {
+ return "", "", "", fmt.Errorf("username or credential not found in turn_server")
+ }
+
+ log.Println("[VK Auth] TURN credentials received")
+ vkDelay(1500, 2500) // Final delay before exit
+ return username, credential, address, nil
+}
diff --git a/client/wb.go b/client/wb.go
new file mode 100644
index 0000000..6beffd5
--- /dev/null
+++ b/client/wb.go
@@ -0,0 +1,358 @@
+// SPDX-FileCopyrightText: 2023 The Pion community
+// SPDX-License-Identifier: MIT
+
+package main
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+const (
+ wbBase = "https://stream.wb.ru"
+ wbUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
+)
+
+// WbTurnCred stores a single TURN credential
+type WbTurnCred struct {
+ URL string
+ Username string
+ Password string
+}
+
+// wbFetch adapts fetchWbCreds to the fetchFunc signature
+func wbFetch(ctx context.Context, link string) (string, string, string, error) {
+ _ = link // WB doesn't use link parameter
+ creds, err := fetchWbCreds(ctx)
+ if err != nil {
+ return "", "", "", err
+ }
+ if len(creds) > 0 {
+ // Clean URL: "turn:host:port?transport=udp" -> "host:port"
+ clean := strings.Split(creds[0].URL, "?")[0]
+ address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
+ return creds[0].Username, creds[0].Password, address, nil
+ }
+ return "", "", "", fmt.Errorf("no TURN credentials received from WB")
+}
+
+// wbHTTPClient creates a WB HTTP client
+func wbHTTPClient() *http.Client {
+ return &http.Client{
+ Timeout: 15 * time.Second,
+ Transport: &http.Transport{
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 100,
+ IdleConnTimeout: 90 * time.Second,
+ TLSClientConfig: &tls.Config{},
+ },
+ }
+}
+
+// wbReq makes an HTTP request to WB API
+func wbReq(ctx context.Context, client *http.Client, method, ep string, body []byte, tok string) ([]byte, error) {
+ var rd io.Reader
+ if body != nil {
+ rd = bytes.NewReader(body)
+ }
+
+ rq, err := http.NewRequestWithContext(ctx, method, wbBase+ep, rd)
+ if err != nil {
+ return nil, err
+ }
+
+ rq.Header.Set("User-Agent", wbUA)
+ rq.Header.Set("Accept", "application/json")
+ rq.Header.Set("Accept-Language", "en-US,en;q=0.9")
+ rq.Header.Set("Origin", wbBase)
+ rq.Header.Set("Referer", wbBase+"/")
+ if body != nil {
+ rq.Header.Set("Content-Type", "application/json")
+ }
+ if tok != "" {
+ rq.Header.Set("Authorization", "Bearer "+tok)
+ }
+
+ rs, err := client.Do(rq)
+ if err != nil {
+ return nil, err
+ }
+ defer rs.Body.Close()
+
+ var r io.Reader = rs.Body
+ if rs.Header.Get("Content-Encoding") == "gzip" {
+ if g, e := gzip.NewReader(rs.Body); e == nil {
+ defer g.Close()
+ r = g
+ }
+ }
+
+ b, err := io.ReadAll(r)
+ if err != nil {
+ return nil, err
+ }
+
+ if rs.StatusCode >= 300 {
+ return nil, fmt.Errorf("HTTP %d: %s", rs.StatusCode, string(b))
+ }
+
+ return b, nil
+}
+
+// fetchWbCreds performs the full WB credential acquisition flow
+func fetchWbCreds(ctx context.Context) ([]WbTurnCred, error) {
+ client := wbHTTPClient()
+ defer client.CloseIdleConnections()
+
+ nm := fmt.Sprintf("lh_%d", time.Now().UnixMilli()%100000)
+
+ log.Println("[WB Auth] Step 1: Guest registration...")
+ rr, err := wbReq(ctx, client, "POST", "/auth/api/v1/auth/user/guest-register",
+ []byte(`{"displayName":"`+nm+`"}`), "")
+ if err != nil {
+ return nil, fmt.Errorf("guest register: %w", err)
+ }
+
+ var reg struct {
+ AccessToken string `json:"accessToken"`
+ }
+ if err = json.Unmarshal(rr, ®); err != nil {
+ return nil, fmt.Errorf("parse register response: %w", err)
+ }
+ if reg.AccessToken == "" {
+ return nil, fmt.Errorf("no access token in response")
+ }
+ log.Println("[WB Auth] Guest registered")
+
+ log.Println("[WB Auth] Step 2: Create room...")
+ rr, err = wbReq(ctx, client, "POST", "/api-room/api/v2/room",
+ []byte(`{"roomType":"ROOM_TYPE_ALL_ON_SCREEN","roomPrivacy":"ROOM_PRIVACY_FREE"}`),
+ reg.AccessToken)
+ if err != nil {
+ return nil, fmt.Errorf("create room: %w", err)
+ }
+
+ var room struct {
+ RoomID string `json:"roomId"`
+ }
+ if err = json.Unmarshal(rr, &room); err != nil {
+ return nil, fmt.Errorf("parse room response: %w", err)
+ }
+ if room.RoomID == "" {
+ return nil, fmt.Errorf("no room ID in response")
+ }
+ roomPreview := room.RoomID
+ if len(roomPreview) > 8 {
+ roomPreview = roomPreview[:8]
+ }
+ log.Printf("[WB Auth] Room created: %s", roomPreview)
+
+ log.Println("[WB Auth] Step 3: Join room...")
+ _, err = wbReq(ctx, client, "POST", fmt.Sprintf("/api-room/api/v1/room/%s/join", room.RoomID),
+ []byte("{}"), reg.AccessToken)
+ if err != nil {
+ return nil, fmt.Errorf("join room: %w", err)
+ }
+
+ log.Println("[WB Auth] Step 4: Get room token...")
+ rr, err = wbReq(ctx, client, "GET", fmt.Sprintf(
+ "/api-room-manager/api/v1/room/%s/token?deviceType=PARTICIPANT_DEVICE_TYPE_WEB_DESKTOP&displayName=%s",
+ room.RoomID, url.QueryEscape(nm)), nil, reg.AccessToken)
+ if err != nil {
+ return nil, fmt.Errorf("get token: %w", err)
+ }
+
+ var tok struct {
+ RoomToken string `json:"roomToken"`
+ }
+ if err = json.Unmarshal(rr, &tok); err != nil {
+ return nil, fmt.Errorf("parse token response: %w", err)
+ }
+ if tok.RoomToken == "" {
+ return nil, fmt.Errorf("no room token in response")
+ }
+
+ log.Println("[WB Auth] Step 5: Negotiating ICE (LiveKit)...")
+ creds, err := wbLkICE(ctx, tok.RoomToken)
+ if err != nil {
+ return nil, fmt.Errorf("livekit ICE: %w", err)
+ }
+
+ for _, c := range creds {
+ log.Printf("[WB Auth] → %s", c.URL)
+ }
+
+ return creds, nil
+}
+
+// wbLkICE connects to LiveKit WebSocket and extracts TURN credentials
+func wbLkICE(ctx context.Context, token string) ([]WbTurnCred, error) {
+ u := "wss://wbstream01-el.wb.ru:7880/rtc?access_token=" + url.QueryEscape(token) +
+ "&auto_subscribe=1&sdk=js&version=2.15.3&protocol=16&adaptive_stream=1"
+
+ conn, _, err := (&websocket.Dialer{
+ TLSClientConfig: &tls.Config{},
+ HandshakeTimeout: 10 * time.Second,
+ }).DialContext(ctx, u, http.Header{
+ "User-Agent": {wbUA},
+ "Origin": {wbBase},
+ })
+ if err != nil {
+ return nil, err
+ }
+ defer conn.Close()
+
+ for i := 0; i < 15; i++ {
+ conn.SetReadDeadline(time.Now().Add(5 * time.Second))
+ _, msg, err := conn.ReadMessage()
+ if err != nil {
+ break
+ }
+ if creds := wbPbICE(msg); len(creds) > 0 {
+ return wbDedup(creds), nil
+ }
+ }
+
+ return nil, fmt.Errorf("TURN credentials not found in LiveKit response")
+}
+
+// PbVar reads protobuf varint
+func wbPbVar(d []byte, o int) (uint64, int) {
+ var v uint64
+ for s := 0; o < len(d) && s < 64; s += 7 {
+ b := d[o]
+ o++
+ v |= uint64(b&0x7f) << s
+ if b < 0x80 {
+ return v, o
+ }
+ }
+ return 0, o
+}
+
+// PbAll finds all fields with given tag number in protobuf data
+func wbPbAll(d []byte, f uint64) (r [][]byte) {
+ for o := 0; o < len(d); {
+ t, n := wbPbVar(d, o)
+ if n == o {
+ break
+ }
+ o = n
+ switch t & 7 {
+ case 0:
+ _, o = wbPbVar(d, o)
+ case 2:
+ l, n := wbPbVar(d, o)
+ o = n
+ e := o + int(l)
+ if e > len(d) || e < o {
+ return
+ }
+ if t>>3 == f {
+ r = append(r, d[o:e])
+ }
+ o = e
+ case 1:
+ o += 8
+ case 5:
+ o += 4
+ default:
+ return
+ }
+ }
+ return
+}
+
+// PbStr extracts string field with given tag number
+func wbPbStr(d []byte, f uint64) string {
+ if a := wbPbAll(d, f); len(a) > 0 {
+ return string(a[0])
+ }
+ return ""
+}
+
+// PbICE extracts TURN/STUN credentials from protobuf message
+func wbPbICE(d []byte) (res []WbTurnCred) {
+ for o := 0; o < len(d); {
+ t, n := wbPbVar(d, o)
+ if n == o {
+ break
+ }
+ o = n
+ switch t & 7 {
+ case 0:
+ _, o = wbPbVar(d, o)
+ case 2:
+ l, n := wbPbVar(d, o)
+ o = n
+ e := o + int(l)
+ if e > len(d) || e < o {
+ return
+ }
+ inner := d[o:e]
+ for _, f := range []uint64{5, 9} {
+ for _, blk := range wbPbAll(inner, f) {
+ urls := wbPbAll(blk, 1)
+ hit := false
+ for _, u := range urls {
+ s := string(u)
+ if strings.HasPrefix(s, "turn") || strings.HasPrefix(s, "stun") {
+ hit = true
+ break
+ }
+ }
+ if !hit {
+ continue
+ }
+ un, pw := wbPbStr(blk, 2), wbPbStr(blk, 3)
+ for _, u := range urls {
+ res = append(res, WbTurnCred{string(u), un, pw})
+ }
+ for _, blk2 := range wbPbAll(inner, f) {
+ if len(blk2) > 0 && len(blk) > 0 && &blk2[0] == &blk[0] {
+ continue
+ }
+ u2, p2 := wbPbStr(blk2, 2), wbPbStr(blk2, 3)
+ for _, u := range wbPbAll(blk2, 1) {
+ res = append(res, WbTurnCred{string(u), u2, p2})
+ }
+ }
+ return
+ }
+ }
+ o = e
+ case 1:
+ o += 8
+ case 5:
+ o += 4
+ default:
+ return
+ }
+ }
+ return
+}
+
+// wbDedup removes duplicate credentials
+func wbDedup(cc []WbTurnCred) (r []WbTurnCred) {
+ seen := map[string]bool{}
+ for _, c := range cc {
+ k := c.URL + "|" + c.Username
+ if !seen[k] {
+ seen[k] = true
+ r = append(r, c)
+ }
+ }
+ return
+}
From f41f75d10b27c78058ec809f42397c1c4760b0cb Mon Sep 17 00:00:00 2001
From: kiper292
Date: Sun, 5 Apr 2026 00:12:02 +0500
Subject: [PATCH 08/11] Update vk_captcha.go
---
client/vk_captcha.go | 92 +++++++++++++++-----------------------------
1 file changed, 32 insertions(+), 60 deletions(-)
diff --git a/client/vk_captcha.go b/client/vk_captcha.go
index 8e3a348..92abf49 100644
--- a/client/vk_captcha.go
+++ b/client/vk_captcha.go
@@ -91,11 +91,8 @@ func ExtractCaptchaData(errResp map[string]interface{}) (*VkCaptchaData, bool) {
func SolveVkCaptcha(ctx context.Context, captchaData *VkCaptchaData) (string, error) {
log.Printf("[Captcha] Solving Not Robot Captcha...")
- // HAR: Token 2 error → Captcha HTML = 2.72s (browser page load + user perception)
- time.Sleep(1500*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond)
-
// Fetch captcha HTML (browser redirect)
- powInput, difficulty, cookies, err := fetchCaptchaPowInput(ctx, captchaData.RedirectURI)
+ powInput, difficulty, err := fetchCaptchaPowInput(ctx, captchaData.RedirectURI)
if err != nil {
return "", fmt.Errorf("failed to fetch powInput: %w", err)
}
@@ -105,8 +102,8 @@ func SolveVkCaptcha(ctx context.Context, captchaData *VkCaptchaData) (string, er
hash := solveCaptchaPoW(powInput, difficulty)
log.Printf("[Captcha] PoW solved: hash=%s", hash)
- // Call captchaNotRobot API with cookies from captcha page
- successToken, err := callCaptchaNotRobotAPI(ctx, captchaData.SessionToken, hash, cookies)
+ // Call captchaNotRobot API
+ successToken, err := callCaptchaNotRobotAPI(ctx, captchaData.SessionToken, hash)
if err != nil {
return "", fmt.Errorf("captchaNotRobot API failed: %w", err)
}
@@ -115,10 +112,10 @@ func SolveVkCaptcha(ctx context.Context, captchaData *VkCaptchaData) (string, er
return successToken, nil
}
-func fetchCaptchaPowInput(ctx context.Context, redirectURI string) (string, int, string, error) {
+func fetchCaptchaPowInput(ctx context.Context, redirectURI string) (string, int, error) {
req, err := http.NewRequestWithContext(ctx, "GET", redirectURI, nil)
if err != nil {
- return "", 0, "", err
+ return "", 0, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
@@ -133,25 +130,13 @@ func fetchCaptchaPowInput(ctx context.Context, redirectURI string) (string, int,
resp, err := client.Do(req)
if err != nil {
- return "", 0, "", err
+ return "", 0, err
}
defer resp.Body.Close()
- // Capture Set-Cookie headers
- var cookieValues []string
- for _, setCookie := range resp.Header.Values("Set-Cookie") {
- // Extract just the cookie name=value part (before ; expires= or ; path=)
- cookieParts := strings.Split(setCookie, ";")
- cookieValues = append(cookieValues, strings.TrimSpace(cookieParts[0]))
- }
- cookies := strings.Join(cookieValues, "; ")
- if cookies != "" {
- log.Printf("[Captcha] Captcha page set %d cookie(s)", len(cookieValues))
- }
-
body, err := io.ReadAll(resp.Body)
if err != nil {
- return "", 0, "", err
+ return "", 0, err
}
html := string(body)
@@ -160,7 +145,7 @@ func fetchCaptchaPowInput(ctx context.Context, redirectURI string) (string, int,
powInputRe := regexp.MustCompile(`const\s+powInput\s*=\s*"([^"]+)"`)
powInputMatch := powInputRe.FindStringSubmatch(html)
if len(powInputMatch) < 2 {
- return "", 0, "", fmt.Errorf("powInput not found in captcha HTML")
+ return "", 0, fmt.Errorf("powInput not found in captcha HTML")
}
powInput := powInputMatch[1]
@@ -174,7 +159,7 @@ func fetchCaptchaPowInput(ctx context.Context, redirectURI string) (string, int,
}
}
- return powInput, difficulty, cookies, nil
+ return powInput, difficulty, nil
}
func solveCaptchaPoW(powInput string, difficulty int) string {
@@ -190,7 +175,7 @@ func solveCaptchaPoW(powInput string, difficulty int) string {
return ""
}
-func callCaptchaNotRobotAPI(ctx context.Context, sessionToken, hash, cookies string) (string, error) {
+func callCaptchaNotRobotAPI(ctx context.Context, sessionToken, hash string) (string, error) {
vkReq := func(method string, postData string) (map[string]interface{}, error) {
requestURL := fmt.Sprintf("https://api.vk.ru/method/%s?v=%s", method, vkCaptchaNotRobotVer)
@@ -199,24 +184,20 @@ func callCaptchaNotRobotAPI(ctx context.Context, sessionToken, hash, cookies str
return nil, err
}
// Headers matching HAR capture exactly
- req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
+ req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "*/*")
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
- req.Header.Set("Origin", "https://id.vk.ru")
- req.Header.Set("Referer", "https://id.vk.ru/")
- req.Header.Set("sec-ch-ua-platform", `"Windows"`)
- req.Header.Set("sec-ch-ua", `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`)
+ req.Header.Set("Origin", "https://vk.ru")
+ req.Header.Set("Referer", "https://vk.ru/")
+ req.Header.Set("sec-ch-ua-platform", "\"Linux\"")
+ req.Header.Set("sec-ch-ua", "\"Chromium\";v=\"146\", \"Not-A.Brand\";v=\"24\", \"Google Chrome\";v=\"146\"")
req.Header.Set("sec-ch-ua-mobile", "?0")
+ req.Header.Set("DNT", "1")
req.Header.Set("Sec-Fetch-Site", "same-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
- req.Header.Set("DNT", "1")
- req.Header.Set("Priority", "u=1, i")
- // Add cookies captured from captcha page
- if cookies != "" {
- req.Header.Set("Cookie", cookies)
- }
+ req.Header.Set("Sec-GPC", "1")
client := &http.Client{
Timeout: 20 * time.Second,
@@ -253,46 +234,38 @@ func callCaptchaNotRobotAPI(ctx context.Context, sessionToken, hash, cookies str
if err != nil {
return "", fmt.Errorf("settings failed: %w", err)
}
- // HAR: settings → componentDone = 0.19s
- time.Sleep(100*time.Millisecond + time.Duration(rand.Intn(100))*time.Millisecond)
+ time.Sleep(200 * time.Millisecond)
// Step 2: componentDone
log.Printf("[Captcha] Step 2/4: componentDone")
- browserFp := fmt.Sprintf("%032x", uint64(time.Now().UnixNano()))
+ browserFp := fmt.Sprintf("%032x", rand.Int63())
deviceJSON := `{"screenWidth":1920,"screenHeight":1080,"screenAvailWidth":1920,"screenAvailHeight":1032,"innerWidth":1920,"innerHeight":945,"devicePixelRatio":1,"language":"en-US","languages":["en-US"],"webdriver":false,"hardwareConcurrency":16,"deviceMemory":8,"connectionEffectiveType":"4g","notificationsPermission":"denied"}`
componentData := baseParams + fmt.Sprintf("&browser_fp=%s&device=%s", browserFp, url.QueryEscape(deviceJSON))
_, err = vkReq("captchaNotRobot.componentDone", componentData)
if err != nil {
return "", fmt.Errorf("componentDone failed: %w", err)
}
- // HAR: componentDone → check ≈ 1.95s + statEvents delay ≈ 3.2s total
- time.Sleep(1500*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond)
+ time.Sleep(200 * time.Millisecond)
// Step 3: check
log.Printf("[Captcha] Step 3/4: check")
cursorJSON := `[{"x":950,"y":500},{"x":945,"y":510},{"x":940,"y":520},{"x":938,"y":525},{"x":938,"y":525}]`
answer := base64.StdEncoding.EncodeToString([]byte("{}")) // e30=
- // Generate random connectionDownlink values (simulating Network Information API)
- // HAR shows browser repeats the same value 7 times: [9.8,9.8,9.8,9.8,9.8,9.8,9.8]
- baseDownlink := 8.0 + rand.Float64()*4.0 // Random in [8.0, 12.0) for typical WiFi
- downlinkStr := fmt.Sprintf("%.1f", baseDownlink)
- connectionDownlink := "[" + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "," + downlinkStr + "]"
-
checkData := baseParams + fmt.Sprintf(
"&accelerometer=%s&gyroscope=%s&motion=%s&cursor=%s&taps=%s&connectionRtt=%s&connectionDownlink=%s"+
"&browser_fp=%s&hash=%s&answer=%s&debug_info=%s",
- url.QueryEscape("[]"), // accelerometer
- url.QueryEscape("[]"), // gyroscope
- url.QueryEscape("[]"), // motion
- url.QueryEscape(cursorJSON), // cursor
- url.QueryEscape("[]"), // taps
- url.QueryEscape("[]"), // connectionRtt
- url.QueryEscape(connectionDownlink),
- browserFp, // browser_fp
- hash, // hash (PoW result)
- answer, // answer
- vkDebugInfo, // debug_info (static)
+ url.QueryEscape("[]"), // accelerometer
+ url.QueryEscape("[]"), // gyroscope
+ url.QueryEscape("[]"), // motion
+ url.QueryEscape(cursorJSON), // cursor
+ url.QueryEscape("[]"), // taps
+ url.QueryEscape("[]"), // connectionRtt
+ url.QueryEscape("[9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5,9.5]"), // connectionDownlink (16 values as in HAR)
+ browserFp, // browser_fp
+ hash, // hash (PoW result)
+ answer, // answer
+ vkDebugInfo, // debug_info (static)
)
checkResp, err := vkReq("captchaNotRobot.check", checkData)
@@ -314,8 +287,7 @@ func callCaptchaNotRobotAPI(ctx context.Context, sessionToken, hash, cookies str
if !ok || successToken == "" {
return "", fmt.Errorf("success_token not found in check response: %v", checkResp)
}
- // HAR: check → endSession = 0.48s
- time.Sleep(200*time.Millisecond + time.Duration(rand.Intn(300))*time.Millisecond)
+ time.Sleep(200 * time.Millisecond)
// Step 4: endSession
log.Printf("[Captcha] Step 4/4: endSession")
From ac181c352a5052f188f19feda578a9e65168c820 Mon Sep 17 00:00:00 2001
From: kiper292
Date: Sun, 5 Apr 2026 01:08:12 +0500
Subject: [PATCH 09/11] support for old v1 server
---
README.en.md | 1 +
README.md | 1 +
client/main.go | 34 +++++++++++++++++++---------------
3 files changed, 21 insertions(+), 15 deletions(-)
diff --git a/README.en.md b/README.en.md
index fc6fa03..f665b81 100644
--- a/README.en.md
+++ b/README.en.md
@@ -86,6 +86,7 @@ Additional flags:
- `-turn `: override TURN server address.
- `-port `: override TURN server port.
- `-no-dtls`: without DTLS obfuscation (may result in a ban).
+- `-v1`: use v1 protocol (no session_id and stream_id sent). For legacy servers.
#### Linux
diff --git a/README.md b/README.md
index f1aeca5..54155fd 100644
--- a/README.md
+++ b/README.md
@@ -87,6 +87,7 @@ chmod 777 ./client-android
- `-turn `: переопределить адрес TURN сервера.
- `-port `: переопределить порт TURN сервера.
- `-no-dtls`: без DTLS-обфускации (может привести к бану).
+- `-v1`: использовать протокол v1 (без отправки session_id и stream_id). Для серверов старой версии.
#### Linux
diff --git a/client/main.go b/client/main.go
index 3e19922..001e127 100644
--- a/client/main.go
+++ b/client/main.go
@@ -52,7 +52,7 @@ func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.
return dtlsConn, nil
}
-func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error, sessionID []byte, streamID byte) {
+func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error, sessionID []byte, streamID byte, v1 bool) {
var err error = nil
defer func() { c <- err }()
dtlsctx, dtlscancel := context.WithCancel(ctx)
@@ -81,17 +81,20 @@ func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.Pa
log.Printf("Closed DTLS connection\n")
}()
- // Phase 1: Send Session ID + Stream ID (17 bytes)
- dtlsConn.SetWriteDeadline(time.Now().Add(time.Second * 5))
- idBuf := make([]byte, 17)
- copy(idBuf[:16], sessionID)
- idBuf[16] = streamID
- if _, err1 = dtlsConn.Write(idBuf); err1 != nil {
- err = fmt.Errorf("failed to send session ID: %s", err1)
- return
+ // Phase 1: Send Session ID + Stream ID (17 bytes) - only for v2 protocol
+ if !v1 {
+ dtlsConn.SetWriteDeadline(time.Now().Add(time.Second * 5))
+ idBuf := make([]byte, 17)
+ copy(idBuf[:16], sessionID)
+ idBuf[16] = streamID
+ if _, err1 = dtlsConn.Write(idBuf); err1 != nil {
+ err = fmt.Errorf("failed to send session ID: %s", err1)
+ return
+ }
+ log.Printf("Established DTLS connection and sent session ID with stream %d!\n", streamID)
+ } else {
+ log.Printf("Established DTLS connection (v1 protocol, no session ID)!\n")
}
-
- log.Printf("Established DTLS connection and sent session ID with stream %d!\n", streamID)
go func() {
for {
select {
@@ -369,14 +372,14 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
conn2.SetDeadline(time.Time{})
}
-func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConnChan <-chan net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, sessionID []byte, streamID byte) {
+func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConnChan <-chan net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, sessionID []byte, streamID byte, v1 bool) {
for {
select {
case <-ctx.Done():
return
case listenConn := <-listenConnChan:
c := make(chan error)
- go oneDtlsConnection(ctx, peer, listenConn, connchan, okchan, c, sessionID, streamID)
+ go oneDtlsConnection(ctx, peer, listenConn, connchan, okchan, c, sessionID, streamID, v1)
if err := <-c; err != nil {
log.Printf("%s", err)
}
@@ -432,6 +435,7 @@ func main() { //nolint:cyclop
n := flag.Int("n", 0, "connections to TURN (default 4)")
udp := flag.Bool("udp", false, "connect to TURN with UDP")
direct := flag.Bool("no-dtls", false, "connect without obfuscation. DO NOT USE")
+ v1 := flag.Bool("v1", false, "use v1 server protocol (no session_id and stream_id)")
sessionIDFlag := flag.String("session-id", "", "override session ID (hex, 32 chars)")
flag.Parse()
if *peerAddr == "" {
@@ -525,7 +529,7 @@ func main() { //nolint:cyclop
wg1.Add(1)
go func() {
defer wg1.Done()
- oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, okchan, sessionID, 0)
+ oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, okchan, sessionID, 0, *v1)
}()
wg1.Add(1)
@@ -544,7 +548,7 @@ func main() { //nolint:cyclop
wg1.Add(1)
go func(sID byte) {
defer wg1.Done()
- oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil, sessionID, sID)
+ oneDtlsConnectionLoop(ctx, peer, listenConnChan, connchan, nil, sessionID, sID, *v1)
}(byte(streamID))
wg1.Add(1)
go func() {
From ae3d1b4895ff8b724c9eafdb2d8c37498ee5b97a Mon Sep 17 00:00:00 2001
From: kiper292
Date: Thu, 16 Apr 2026 16:03:28 +0500
Subject: [PATCH 10/11] captcha fix
---
client/manual_captcha.go | 579 +++++++++++++++++
client/vk.go | 12 +-
client/vk_captcha.go | 1304 +++++++++++++++++++++++++++++++++-----
3 files changed, 1721 insertions(+), 174 deletions(-)
create mode 100644 client/manual_captcha.go
diff --git a/client/manual_captcha.go b/client/manual_captcha.go
new file mode 100644
index 0000000..bb11d1b
--- /dev/null
+++ b/client/manual_captcha.go
@@ -0,0 +1,579 @@
+package main
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ neturl "net/url"
+ "os/exec"
+ "runtime"
+ "strings"
+ "time"
+)
+
+const captchaListenPort = "8765"
+
+type browserCommand struct {
+ name string
+ args []string
+}
+
+func localCaptchaOrigin() string {
+ return "http://localhost:" + captchaListenPort
+}
+
+func localCaptchaListenAddrs() []string {
+ return []string{
+ "127.0.0.1:" + captchaListenPort,
+ "[::1]:" + captchaListenPort,
+ }
+}
+
+func localCaptchaHosts() []string {
+ return []string{
+ "localhost:" + captchaListenPort,
+ "127.0.0.1:" + captchaListenPort,
+ "[::1]:" + captchaListenPort,
+ }
+}
+
+func isLocalCaptchaHost(host string) bool {
+ for _, localHost := range localCaptchaHosts() {
+ if strings.EqualFold(host, localHost) {
+ return true
+ }
+ }
+ return false
+}
+
+func localCaptchaURLForTarget(targetURL *neturl.URL) string {
+ localURL := &neturl.URL{
+ Scheme: "http",
+ Host: "localhost:" + captchaListenPort,
+ Path: targetURL.Path,
+ RawPath: targetURL.RawPath,
+ RawQuery: targetURL.RawQuery,
+ }
+ if localURL.Path == "" {
+ localURL.Path = "/"
+ }
+ return localURL.String()
+}
+
+func targetOrigin(targetURL *neturl.URL) string {
+ return targetURL.Scheme + "://" + targetURL.Host
+}
+
+func isSafeLocalRedirectPath(raw string) bool {
+ if raw == "" || raw[0] != '/' {
+ return false
+ }
+ if len(raw) > 1 && (raw[1] == '/' || raw[1] == '\\') {
+ return false
+ }
+ return true
+}
+
+func rewriteProxyRedirectLocation(raw string, targetURL *neturl.URL) (string, bool) {
+ if isSafeLocalRedirectPath(raw) {
+ return raw, true
+ }
+
+ parsed, err := neturl.Parse(raw)
+ if err != nil {
+ return "", false
+ }
+ if !strings.EqualFold(parsed.Scheme, targetURL.Scheme) || !strings.EqualFold(parsed.Host, targetURL.Host) {
+ return "", false
+ }
+
+ return localCaptchaURLForTarget(parsed), true
+}
+
+func rewriteProxyHeaderURL(raw string, targetURL *neturl.URL) string {
+ if raw == "" {
+ return raw
+ }
+ parsed, err := neturl.Parse(raw)
+ if err != nil {
+ return raw
+ }
+ if parsed.Scheme != "http" || !isLocalCaptchaHost(parsed.Host) {
+ return raw
+ }
+ parsed.Scheme = targetURL.Scheme
+ parsed.Host = targetURL.Host
+ return parsed.String()
+}
+
+func rewriteProxyRequest(req *http.Request, targetURL *neturl.URL) {
+ req.URL.Scheme = targetURL.Scheme
+ req.URL.Host = targetURL.Host
+ if req.URL.Path == "" {
+ req.URL.Path = targetURL.Path
+ }
+ req.Host = targetURL.Host
+
+ req.Header.Del("Accept-Encoding")
+ for _, headerName := range []string{"Origin", "Referer"} {
+ if rewritten := rewriteProxyHeaderURL(req.Header.Get(headerName), targetURL); rewritten != "" {
+ req.Header.Set(headerName, rewritten)
+ } else {
+ req.Header.Del(headerName)
+ }
+ }
+}
+
+func extractSuccessToken(body []byte) string {
+ var payload struct {
+ Response struct {
+ SuccessToken string `json:"success_token"`
+ } `json:"response"`
+ }
+ if err := json.Unmarshal(body, &payload); err != nil {
+ return ""
+ }
+ return payload.Response.SuccessToken
+}
+
+func rewriteProxyCookies(header http.Header) {
+ cookies := (&http.Response{Header: header}).Cookies()
+ if len(cookies) == 0 {
+ return
+ }
+ header.Del("Set-Cookie")
+ for _, cookie := range cookies {
+ cookie.Domain = ""
+ cookie.Secure = false
+ cookie.Partitioned = false
+ if cookie.SameSite == http.SameSiteNoneMode || cookie.SameSite == http.SameSiteStrictMode {
+ cookie.SameSite = http.SameSiteLaxMode
+ }
+ header.Add("Set-Cookie", cookie.String())
+ }
+}
+
+func rewriteCaptchaHTML(html string, targetURL *neturl.URL) string {
+ localOrigin := localCaptchaOrigin()
+ upstreamOrigin := targetOrigin(targetURL)
+ html = strings.ReplaceAll(html, upstreamOrigin, localOrigin)
+
+ script := fmt.Sprintf(`
+
+`, localOrigin, upstreamOrigin)
+
+ switch {
+ case strings.Contains(html, ""):
+ return strings.Replace(html, "", script+"", 1)
+ case strings.Contains(html, "
+Solve the Captcha
+
+"):
+ return strings.Replace(html, "", script+"", 1)
+ default:
+ return html + script
+ }
+}
+
+func startCaptchaServer(srv *http.Server, logPrefix string) error {
+ var listenErrs []string
+ var listening bool
+
+ for _, addr := range localCaptchaListenAddrs() {
+ listener, err := net.Listen("tcp", addr)
+ if err != nil {
+ listenErrs = append(listenErrs, fmt.Sprintf("%s (%v)", addr, err))
+ continue
+ }
+ listening = true
+ go func(listener net.Listener) {
+ if err := srv.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ log.Printf("%s: %s", logPrefix, err)
+ }
+ }(listener)
+ }
+
+ if listening {
+ return nil
+ }
+
+ return fmt.Errorf("captcha listeners failed: %s", strings.Join(listenErrs, "; "))
+}
+
+func runCaptchaServerAndWait(handler http.Handler, captchaURL string, keyCh <-chan string, logPrefix string) (string, error) {
+ srv := &http.Server{Handler: handler}
+
+ if err := startCaptchaServer(srv, logPrefix); err != nil {
+ return "", err
+ }
+
+ fmt.Println("\n==============================================")
+ fmt.Println("ACTION REQUIRED: MANUAL CAPTCHA SOLVING NEEDED")
+ fmt.Println("Open this URL in your browser: " + localCaptchaOrigin())
+ fmt.Println("==============================================")
+ fmt.Println()
+
+ openBrowser(captchaURL)
+
+ key := <-keyCh
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ if err := srv.Shutdown(ctx); err != nil {
+ return "", err
+ }
+
+ return key, nil
+}
+
+func notifyKey(keyCh chan<- string, key string) {
+ if key != "" {
+ select {
+ case keyCh <- key:
+ default:
+ }
+ }
+}
+
+func solveCaptchaViaHTTP(captchaImg string) (string, error) {
+ keyCh := make(chan string, 1)
+ mux := http.NewServeMux()
+
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = fmt.Fprintf(w, `
+