feat(proxy): tcp-режим для xray/sing-box поверх turn

This commit is contained in:
samosvalishe committed 2026-08-25 15:44:16 +03:00
1 parent e63279db18
commit f7129099f7
60 files changed
+2953 -135

No files matched your search

@@ -409,13 +409,20 @@ func (s *captchaSession) fetchCaptchaHTML(redirectURI string) (string, error) {
}
func parseCaptchaPage(html string) (*captchaPage, error) {
// Заглушка VK (429/5xx) - временно; поломка парсера на настоящей странице - нет,
// её надо эскалировать на следующий режим решения, а не ретраить вечно. Отличаем
// по серверным глобалам: PoW-скрипт обфусцирован, переименование его конверта -
// это поломка парсера, а не отсутствие страницы.
if !reCaptchaVKGlobal.MatchString(html) && !reCaptchaInitGlobal.MatchString(html) {
return nil, fmt.Errorf("%w: not a captcha page (bytes=%d)", ErrUnavailable, len(html))
}
pow, err := parsePowParams(html)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrUnavailable, err)
return nil, err
}
debugInfo := parseCaptchaDebugInfo(html)
if debugInfo == "" {
return nil, fmt.Errorf("%w: captcha debug_info not found on page", ErrUnavailable)
return nil, errors.New("captcha debug_info not found on page")
}
return &captchaPage{Pow: pow, DebugInfo: debugInfo, Init: parseCaptchaInitGlobal(html)}, nil
}
@@ -278,3 +278,18 @@ func TestParseCaptchaPageRejectsNonCaptchaHTML(t *testing.T) {
t.Fatalf("err = %v, want ErrUnavailable", err)
}
}
// Смена обфускации - не аутаж: ошибка обязана дойти до эскалации на другой решатель.
// Переименованный конверт PoW - именно этот случай, страница настоящая.
func TestParseCaptchaPageBrokenParserIsNotUnavailable(t *testing.T) {
t.Parallel()
for name, html := range map[string]string{
"pow renamed": `<script>window.vk = {}; window.zzz = "v2." + solve();</script>`,
"debug absent": `<script>window.init = {};</script>`,
} {
_, err := parseCaptchaPage(html)
if err == nil || errors.Is(err, ErrUnavailable) {
t.Fatalf("%s: err = %v, want plain parse error", name, err)
}
}
}
+3 -1
View File
@@ -17,12 +17,14 @@ import (
"github.com/samosvalishe/free-turn-proxy/internal/provider/vk/internal/browserprofile"
)
const powResultGlobal = "captchaPowResult"
// PoW-скрипт страницы обфусцирован, имена переменных генерируются заново на каждый
// релиз. Стабильны только аргументы IIFE (input, difficulty, метка ошибки) и
// префикс версии конверта.
var (
rePowArgs = regexp.MustCompile(`\}\(\s*["']([A-Za-z0-9_-]{8,})["']\s*,\s*(\d+)\s*,\s*["'][^"']*["']\s*\)\s*\)`)
rePowPrefix = regexp.MustCompile(`captchaPowResult["'\]]{0,3}\s*=\s*["']([A-Za-z0-9._-]{0,8})["']\s*\+`)
rePowPrefix = regexp.MustCompile(powResultGlobal + `["'\]]{0,3}\s*=\s*["']([A-Za-z0-9._-]{0,8})["']\s*\+`)
)
type powParams struct {
+16 -2
View File
@@ -1,9 +1,12 @@
package vkauth
import (
"errors"
"strings"
"sync"
"sync/atomic"
"github.com/pion/stun/v3"
)
type StreamCredentialsCache struct {
@@ -75,11 +78,22 @@ func IsAuthError(err error) bool {
if err == nil {
return false
}
// Ответ TURN-сервера приходит типизированным - код берём из него, а не из текста.
if turnErr, ok := errors.AsType[*stun.TurnError](err); ok {
switch turnErr.ErrorCodeAttr.Code {
// 486 - квота аллокаций: креды живы, но новую сессию по ним не поднять.
case stun.CodeUnauthorized, stun.CodeWrongCredentials,
stun.CodeStaleNonce, stun.CodeAllocQuotaReached:
return true
default:
return false
}
}
// Ошибки не от TURN-сервера (получение кредов у провайдера) типа не несут.
s := err.Error()
return strings.Contains(s, "401") ||
strings.Contains(s, "Unauthorized") ||
strings.Contains(s, "authentication") ||
strings.Contains(s, "invalid credential") ||
strings.Contains(s, "stale nonce") ||
strings.Contains(s, "Allocation Quota")
strings.Contains(s, "stale nonce")
}
@@ -9,6 +9,7 @@ import (
"time"
tlsclient "github.com/bogdanfinn/tls-client"
"github.com/pion/stun/v3"
)
// newTestClient builds a Client with a zero-interval throttle and the supplied
@@ -36,7 +37,6 @@ func TestIsAuthError(t *testing.T) {
"stale nonce": true,
"invalid credential": true,
"authentication required": true,
"486: Allocation Quota Reached": true,
"connection refused": false,
"dial tcp 10.0.0.1:48612: i/o timeout": false,
"": false,
@@ -52,6 +52,28 @@ func TestIsAuthError(t *testing.T) {
}
}
func TestIsAuthErrorTurnCode(t *testing.T) {
t.Parallel()
codes := map[stun.ErrorCode]bool{
stun.CodeAllocQuotaReached: true,
stun.CodeUnauthorized: true,
stun.CodeStaleNonce: true,
stun.CodeWrongCredentials: true,
stun.CodeInsufficientCapacity: false,
stun.CodeForbidden: false,
}
for code, want := range codes {
err := fmt.Errorf("TURN allocate: %w", &stun.TurnError{
StunMessageType: stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse),
ErrorCodeAttr: stun.ErrorCodeAttribute{Code: code, Reason: []byte("reason")},
})
if got := IsAuthError(err); got != want {
t.Errorf("IsAuthError(code %d) = %v, want %v", code, got, want)
}
}
}
func TestStoreCacheGrouping(t *testing.T) {
t.Parallel()