refactor: вынести солвер captcha в internal/captcha

Вытаскивает auto-captcha пайплайн из client/main и даёт ему узкий публичный
интерфейс, чтобы main.go больше не держал ~1.2k строк обработки VK-челленджей.

Новые пакеты под client/internal/:

- browserprofile: типы Profile / Saved плюс Load / Save / Random и инжекторы
  заголовков ApplyHTTP / ApplyFhttp (перенесены из profiles.go + main.go).
  manual_captcha.go тоже переключён на него.
- captcha: package-level entrypoint Solve(ctx, *Error, ...), плюс
  Error / ParseError / IsCaptcha (переименованы из VkCaptchaError /
  ParseVkCaptchaError / IsCaptchaError). Сессия, scoring слайдера, синтез
  курсора и PoW теперь неэкспортируемая деталь реализации.

solveVkCaptcha в main.go сжимается до обёртки над captcha.Solve с загрузкой
SavedProfile.
This commit is contained in:
samosvalishe committed 2026-05-18 16:15:59 +03:00
1 parent 130d5e9298
commit ac3a6031d0
6 files changed
+172 -169

No files matched your search

@@ -1,9 +1,12 @@
package main
package browserprofile
import (
"encoding/json"
"math/rand"
"net/http"
"os"
fhttp "github.com/bogdanfinn/fhttp"
)
type Profile struct {
@@ -13,7 +16,7 @@ type Profile struct {
SecChUaPlatform string
}
type SavedProfile struct {
type Saved struct {
Profile
DeviceJSON string
BrowserFp string
@@ -21,19 +24,19 @@ type SavedProfile struct {
const profileFile = "vk_profile.json"
func LoadProfileFromDisk() (*SavedProfile, error) {
func Load() (*Saved, error) {
data, err := os.ReadFile(profileFile)
if err != nil {
return nil, err
}
var sp SavedProfile
var sp Saved
if err := json.Unmarshal(data, &sp); err != nil {
return nil, err
}
return &sp, nil
}
func SaveProfileToDisk(sp SavedProfile) error {
func Save(sp Saved) error {
data, err := json.MarshalIndent(sp, "", " ")
if err != nil {
return err
@@ -41,10 +44,27 @@ func SaveProfileToDisk(sp SavedProfile) error {
return os.WriteFile(profileFile, data, 0644)
}
func ApplyHTTP(req *http.Request, profile Profile) {
req.Header.Set("User-Agent", profile.UserAgent)
req.Header.Set("sec-ch-ua", profile.SecChUa)
req.Header.Set("sec-ch-ua-mobile", profile.SecChUaMobile)
req.Header.Set("sec-ch-ua-platform", profile.SecChUaPlatform)
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
req.Header.Set("DNT", "1")
}
func ApplyFhttp(req *fhttp.Request, profile Profile) {
req.Header.Set("User-Agent", profile.UserAgent)
req.Header.Set("sec-ch-ua", profile.SecChUa)
req.Header.Set("sec-ch-ua-mobile", profile.SecChUaMobile)
req.Header.Set("sec-ch-ua-platform", profile.SecChUaPlatform)
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
req.Header.Set("DNT", "1")
}
// profiles contain paired User-Agent and Client Hints strings to harden bot detection.
// Used only as a fallback if no saved profile exists (which we shouldn't really use for check anymore).
// Used only as a fallback if no saved profile exists.
var profileList = []Profile{
// Windows Chrome
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
@@ -63,8 +83,6 @@ var profileList = []Profile{
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
// Windows Edge
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Microsoft Edge";v="146"`,
@@ -77,8 +95,6 @@ var profileList = []Profile{
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
// macOS Chrome
{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
@@ -91,8 +107,6 @@ var profileList = []Profile{
SecChUaMobile: "?0",
SecChUaPlatform: `"macOS"`,
},
// Linux Chrome
{
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
@@ -107,7 +121,6 @@ var profileList = []Profile{
},
}
// getRandomProfile returns a paired User-Agent and Client Hints profile.
func getRandomProfile() Profile {
func Random() Profile {
return profileList[rand.Intn(len(profileList))]
}
@@ -1,4 +1,4 @@
package main
package captcha
import (
"bytes"
@@ -21,6 +21,8 @@ import (
fhttp "github.com/bogdanfinn/fhttp"
tlsclient "github.com/bogdanfinn/tls-client"
"github.com/cacggghp/vk-turn-proxy/client/internal/browserprofile"
)
const (
@@ -102,22 +104,24 @@ func (e *captchaShowTypeError) Error() string {
type captchaSession struct {
ctx context.Context
client tlsclient.HttpClient
profile Profile
savedProfile *SavedProfile
profile browserprofile.Profile
savedProfile *browserprofile.Saved
}
func solveCaptchaAuto(
// Solve runs the automatic captcha challenge against VK's captchaNotRobot API
// and returns a success token on success.
func Solve(
ctx context.Context,
captchaErr *VkCaptchaError,
captchaErr *Error,
streamID int,
client tlsclient.HttpClient,
profile Profile,
savedProfile *SavedProfile,
profile browserprofile.Profile,
savedProfile *browserprofile.Saved,
) (string, error) {
if captchaErr == nil || captchaErr.SessionToken == "" {
return "", fmt.Errorf("no session_token in redirect_uri")
}
log.Printf("[STREAM %d] [Captcha] Solving VK Smart Captcha automatically (v2)...", streamID)
log.Printf("[STREAM %d] [Captcha] Solving VK Smart Captcha automatically...", streamID)
s := &captchaSession{ctx: ctx, client: client, profile: profile, savedProfile: savedProfile}
@@ -146,7 +150,7 @@ func solveCaptchaAuto(
return "", fmt.Errorf("captcha attempts exhausted")
}
func (s *captchaSession) solveOnce(captchaErr *VkCaptchaError) (string, error) {
func (s *captchaSession) solveOnce(captchaErr *Error) (string, error) {
html, err := s.fetchCaptchaHTML(captchaErr.RedirectURI)
if err != nil {
return "", err
@@ -490,7 +494,7 @@ func (s *captchaSession) doRaw(
if err != nil {
return nil, err
}
applyBrowserProfileFhttp(req, s.profile)
browserprofile.ApplyFhttp(req, s.profile)
req.Header.Set("Accept", "*/*")
req.Header.Set("Sec-Fetch-Site", "same-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
+112
View File
@@ -0,0 +1,112 @@
package captcha
import (
"fmt"
"log"
neturl "net/url"
)
// Error describes a VK API "captcha required" error (error_code 14) and the
// fields the solver needs to drive the challenge.
type Error struct {
ErrorCode int
ErrorMsg string
CaptchaSid string
CaptchaImg string
RedirectURI string
IsSoundCaptchaAvailable bool
SessionToken string
CaptchaTs string
CaptchaAttempt string
}
// ParseError extracts a captcha challenge from a VK API error payload. Returns
// nil if required fields are missing.
func ParseError(errData map[string]any) *Error {
codeFloat, ok := errData["error_code"].(float64)
if !ok {
log.Printf("missing error_code in captcha error data")
return nil
}
code := int(codeFloat)
redirectURI, ok := errData["redirect_uri"].(string)
if !ok {
log.Printf("missing redirect_uri in captcha error data")
return nil
}
captchaSid, ok := errData["captcha_sid"].(string)
if !ok {
if sidNum, ok2 := errData["captcha_sid"].(float64); ok2 {
captchaSid = fmt.Sprintf("%.0f", sidNum)
} else {
log.Printf("missing captcha_sid in captcha error data")
return nil
}
}
captchaImg, ok := errData["captcha_img"].(string)
if !ok {
log.Printf("missing captcha_img in captcha error data")
return nil
}
errorMsg, ok := errData["error_msg"].(string)
if !ok {
log.Printf("missing error_msg in captcha error data")
return nil
}
var sessionToken string
if redirectURI != "" {
if parsed, err := neturl.Parse(redirectURI); err == nil {
sessionToken = parsed.Query().Get("session_token")
} else {
log.Printf("failed to parse redirect_uri: %v", err)
return nil
}
}
if sessionToken == "" {
if st, stOk := errData["session_token"].(string); stOk {
sessionToken = st
}
}
isSound, ok := errData["is_sound_captcha_available"].(bool)
if !ok {
isSound = false
}
var captchaTs string
if tsFloat, ok := errData["captcha_ts"].(float64); ok {
captchaTs = fmt.Sprintf("%.0f", tsFloat)
} else if tsStr, ok := errData["captcha_ts"].(string); ok {
captchaTs = tsStr
}
var captchaAttempt string
if attFloat, ok := errData["captcha_attempt"].(float64); ok {
captchaAttempt = fmt.Sprintf("%.0f", attFloat)
} else if attStr, ok := errData["captcha_attempt"].(string); ok {
captchaAttempt = attStr
}
return &Error{
ErrorCode: code,
ErrorMsg: errorMsg,
CaptchaSid: captchaSid,
CaptchaImg: captchaImg,
RedirectURI: redirectURI,
IsSoundCaptchaAvailable: isSound,
SessionToken: sessionToken,
CaptchaTs: captchaTs,
CaptchaAttempt: captchaAttempt,
}
}
// IsCaptcha reports whether this error represents an actionable captcha
// challenge (error_code 14 with both redirect_uri and session_token present).
func (e *Error) IsCaptcha() bool {
return e.ErrorCode == 14 && e.RedirectURI != "" && e.SessionToken != ""
}
@@ -1,4 +1,4 @@
package main
package captcha
import (
"bytes"
+12 -140
View File
@@ -29,6 +29,8 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
"github.com/bogdanfinn/tls-client/profiles"
"github.com/cacggghp/vk-turn-proxy/client/internal/browserprofile"
"github.com/cacggghp/vk-turn-proxy/client/internal/captcha"
"github.com/cacggghp/vk-turn-proxy/client/internal/dnsdial"
"github.com/cacggghp/vk-turn-proxy/tcputil"
"github.com/cbeuw/connutil"
@@ -305,25 +307,6 @@ func (l directTCPListener) AcceptTCP() (transport.TCPConn, error) {
// region Helper: HTTP Headers Injection
// applyBrowserProfile applies consistent User-Agent and Client Hints to bypass WAFs
func applyBrowserProfile(req *http.Request, profile Profile) {
req.Header.Set("User-Agent", profile.UserAgent)
req.Header.Set("sec-ch-ua", profile.SecChUa)
req.Header.Set("sec-ch-ua-mobile", profile.SecChUaMobile)
req.Header.Set("sec-ch-ua-platform", profile.SecChUaPlatform)
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
req.Header.Set("DNT", "1")
}
func applyBrowserProfileFhttp(req *fhttp.Request, profile Profile) {
req.Header.Set("User-Agent", profile.UserAgent)
req.Header.Set("sec-ch-ua", profile.SecChUa)
req.Header.Set("sec-ch-ua-mobile", profile.SecChUaMobile)
req.Header.Set("sec-ch-ua-platform", profile.SecChUaPlatform)
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
req.Header.Set("DNT", "1")
}
func getCustomNetDialer() net.Dialer {
return appDialer
}
@@ -332,118 +315,7 @@ func getCustomNetDialer() net.Dialer {
// region Automatic Captcha Solver & Authentication
type VkCaptchaError struct {
ErrorCode int
ErrorMsg string
CaptchaSid string
CaptchaImg string
RedirectURI string
IsSoundCaptchaAvailable bool
SessionToken string
CaptchaTs string
CaptchaAttempt string
}
func ParseVkCaptchaError(errData map[string]any) *VkCaptchaError {
// Extract error_code
codeFloat, ok := errData["error_code"].(float64)
if !ok {
log.Printf("missing error_code in captcha error data")
return nil
}
code := int(codeFloat)
// Extract redirect_uri
RedirectURI, ok := errData["redirect_uri"].(string)
if !ok {
log.Printf("missing redirect_uri in captcha error data")
return nil
}
// Extract captcha_sid
captchaSid, ok := errData["captcha_sid"].(string)
if !ok {
// try numeric
if sidNum, ok2 := errData["captcha_sid"].(float64); ok2 {
captchaSid = fmt.Sprintf("%.0f", sidNum)
} else {
log.Printf("missing captcha_sid in captcha error data")
return nil
}
}
// Extract captcha_img
captchaImg, ok := errData["captcha_img"].(string)
if !ok {
log.Printf("missing captcha_img in captcha error data")
return nil
}
// Extract error_msg
errorMsg, ok := errData["error_msg"].(string)
if !ok {
log.Printf("missing error_msg in captcha error data")
return nil
}
// Extract session token
var sessionToken string
if RedirectURI != "" {
if parsed, err := neturl.Parse(RedirectURI); err == nil {
sessionToken = parsed.Query().Get("session_token")
} else {
log.Printf("failed to parse redirect_uri: %v", err)
return nil
}
}
// Fallback to top-level session_token field if not in redirect_uri
if sessionToken == "" {
if st, stOk := errData["session_token"].(string); stOk {
sessionToken = st
}
}
// Extract is_sound_captcha_available
isSound, ok := errData["is_sound_captcha_available"].(bool)
if !ok {
isSound = false
}
// Extract captcha_ts
var captchaTs string
if tsFloat, ok := errData["captcha_ts"].(float64); ok {
captchaTs = fmt.Sprintf("%.0f", tsFloat)
} else if tsStr, ok := errData["captcha_ts"].(string); ok {
captchaTs = tsStr
}
// Extract captcha_attempt
var captchaAttempt string
if attFloat, ok := errData["captcha_attempt"].(float64); ok {
captchaAttempt = fmt.Sprintf("%.0f", attFloat)
} else if attStr, ok := errData["captcha_attempt"].(string); ok {
captchaAttempt = attStr
}
// Build VkCaptchaError
return &VkCaptchaError{
ErrorCode: code,
ErrorMsg: errorMsg,
CaptchaSid: captchaSid,
CaptchaImg: captchaImg,
RedirectURI: RedirectURI,
IsSoundCaptchaAvailable: isSound,
SessionToken: sessionToken,
CaptchaTs: captchaTs,
CaptchaAttempt: captchaAttempt,
}
}
func (e *VkCaptchaError) IsCaptchaError() bool {
return e.ErrorCode == 14 && e.RedirectURI != "" && e.SessionToken != ""
}
func solveVkCaptcha(ctx context.Context, captchaErr *VkCaptchaError, streamID int, client tlsclient.HttpClient, profile Profile) (string, error) {
func solveVkCaptcha(ctx context.Context, captchaErr *captcha.Error, streamID int, client tlsclient.HttpClient, profile browserprofile.Profile) (string, error) {
log.Printf("[STREAM %d] [Captcha] Solving captcha...", streamID)
if captchaErr.SessionToken == "" {
@@ -453,14 +325,14 @@ func solveVkCaptcha(ctx context.Context, captchaErr *VkCaptchaError, streamID in
return "", fmt.Errorf("no redirect_uri for auto-solve")
}
var savedProfile *SavedProfile
if sp, err := LoadProfileFromDisk(); err == nil {
var savedProfile *browserprofile.Saved
if sp, err := browserprofile.Load(); err == nil {
log.Printf("[STREAM %d] [Captcha] Using saved real browser profile", streamID)
savedProfile = sp
profile = sp.Profile
}
successToken, err := solveCaptchaAuto(ctx, captchaErr, streamID, client, profile, savedProfile)
successToken, err := captcha.Solve(ctx, captchaErr, streamID, client, profile, savedProfile)
if err != nil {
return "", err
}
@@ -697,7 +569,7 @@ func fetchVkCreds(ctx context.Context, link string, streamID int, dialer net.Dia
}
func getTokenChain(ctx context.Context, link string, streamID int, creds VKCredentials, dialer net.Dialer, jar tlsclient.CookieJar) (string, string, []string, error) {
profile := Profile{
profile := browserprofile.Profile{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Not(A:Brand";v="99", "Google Chrome";v="146", "Chromium";v="146"`,
SecChUaMobile: "?0",
@@ -732,7 +604,7 @@ func getTokenChain(ctx context.Context, link string, streamID int, creds VKCrede
}
req.Host = domain
applyBrowserProfileFhttp(req, profile)
browserprofile.ApplyFhttp(req, profile)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "*/*")
req.Header.Set("Origin", "https://vk.ru")
@@ -802,8 +674,8 @@ func getTokenChain(ctx context.Context, link string, streamID int, creds VKCrede
}
if errObj, hasErr := resp["error"].(map[string]any); hasErr {
captchaErr := ParseVkCaptchaError(errObj)
if captchaErr != nil && captchaErr.IsCaptchaError() {
captchaErr := captcha.ParseError(errObj)
if captchaErr != nil && captchaErr.IsCaptcha() {
solveMode, hasSolveMode := captchaSolveModeForAttempt(attempt, manualCaptcha)
if !hasSolveMode {
log.Printf("[STREAM %d] [Captcha] No more solve modes available (attempt %d)", streamID, attempt+1)
@@ -1004,7 +876,7 @@ func getYandexCreds(link string) (string, string, string, error) {
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")
profile := getRandomProfile()
profile := browserprofile.Random()
name := generateName()
type ConferenceResponse struct {
@@ -1134,7 +1006,7 @@ func getYandexCreds(link string) (string, string, string, error) {
return "", "", "", err
}
applyBrowserProfile(req, profile)
browserprofile.ApplyHTTP(req, profile)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", "https://telemost.yandex.ru/")
req.Header.Set("Origin", "https://telemost.yandex.ru")
+5 -3
View File
@@ -18,6 +18,8 @@ import (
"runtime"
"strings"
"time"
"github.com/cacggghp/vk-turn-proxy/client/internal/browserprofile"
)
const captchaListenPort = "8765"
@@ -626,8 +628,8 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
// We only save it if device is present. componentDone usually has it.
if device != "" && browserFp != "" {
sp := SavedProfile{
Profile: Profile{
sp := browserprofile.Saved{
Profile: browserprofile.Profile{
UserAgent: req.Header.Get("User-Agent"),
SecChUa: req.Header.Get("Sec-Ch-Ua"),
SecChUaMobile: req.Header.Get("Sec-Ch-Ua-Mobile"),
@@ -636,7 +638,7 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
DeviceJSON: device,
BrowserFp: browserFp,
}
if err := SaveProfileToDisk(sp); err != nil {
if err := browserprofile.Save(sp); err != nil {
log.Printf("[Captcha Proxy] Failed to save browser profile: %v", err)
} else {
log.Printf("[Captcha Proxy] Successfully intercepted and saved real browser profile!")