refactor: убрать суффикс V2 из солвера captcha

После удаления POC-пути суффикс V2 рудиментарен — нет v1, от которого надо
отличать. Механическое переименование в captcha.go и captcha_slider.go
(бывшие captcha_v2{,_slider}.go):

- captchaV2* → captcha* (имена структур/переменных/констант/regex/ошибок)
- *V2 → * (slider-хелперы, sample/score-функции, abs-хелперы)
- solveVkCaptchaV2 → solveCaptchaAuto (вызов обновлён)
- log-префиксы "v2 captcha" / "v2 slider" убраны
This commit is contained in:
samosvalishe committed 2026-05-18 16:07:04 +03:00
1 parent 5137ddd80b
commit 130d5e9298
3 files changed
+148 -148

No files matched your search

+92 -92
View File
@@ -24,26 +24,26 @@ import (
) )
const ( const (
captchaV2APIVersion = "5.131" captchaAPIVersion = "5.131"
captchaV2ScriptVersion = "1.1.1324" captchaScriptVersion = "1.1.1324"
captchaV2DeviceInfo = `{"screenWidth":1920,"screenHeight":1080,"screenAvailWidth":1920,"screenAvailHeight":1080,"innerWidth":1920,"innerHeight":951,"devicePixelRatio":1,"language":"en-US","languages":["en-US","en"],"webdriver":false,"hardwareConcurrency":8,"notificationsPermission":"denied"}` captchaDeviceInfo = `{"screenWidth":1920,"screenHeight":1080,"screenAvailWidth":1920,"screenAvailHeight":1080,"innerWidth":1920,"innerHeight":951,"devicePixelRatio":1,"language":"en-US","languages":["en-US","en"],"webdriver":false,"hardwareConcurrency":8,"notificationsPermission":"denied"}`
) )
var ( var (
reCaptchaV2PowInput = regexp.MustCompile(`const\s+powInput\s*=\s*"([^"]+)"`) reCaptchaPowInput = regexp.MustCompile(`const\s+powInput\s*=\s*"([^"]+)"`)
reCaptchaV2Difficulty = regexp.MustCompile(`const\s+difficulty\s*=\s*(\d+)`) reCaptchaDifficulty = regexp.MustCompile(`const\s+difficulty\s*=\s*(\d+)`)
reCaptchaV2WindowInit = regexp.MustCompile(`(?s)window\.init\s*=\s*(\{.*?})\s*;`) reCaptchaWindowInit = regexp.MustCompile(`(?s)window\.init\s*=\s*(\{.*?})\s*;`)
reCaptchaV2ScriptSrc = regexp.MustCompile(`src="(https://[^"]+not_robot_captcha[^"]+)"`) reCaptchaScriptSrc = regexp.MustCompile(`src="(https://[^"]+not_robot_captcha[^"]+)"`)
reCaptchaV2DebugInfo = regexp.MustCompile(`debug_info:(?:[^"]*\|\|)?"([a-fA-F0-9]{64})"`) reCaptchaDebugInfo = regexp.MustCompile(`debug_info:(?:[^"]*\|\|)?"([a-fA-F0-9]{64})"`)
reCaptchaV2Version = regexp.MustCompile(`vkid/([0-9.]*)/not_robot_captcha\.js`) reCaptchaVersion = regexp.MustCompile(`vkid/([0-9.]*)/not_robot_captcha\.js`)
errCaptchaV2RateLimit = errors.New("captcha session rate limit reached") errCaptchaRateLimit = errors.New("captcha session rate limit reached")
errCaptchaV2Bot = errors.New("captcha bot challenge") errCaptchaBot = errors.New("captcha bot challenge")
captchaV2MaxAttempts = 2 captchaMaxAttempts = 2
captchaV2DebugCache sync.Map // scriptURL -> string captchaDebugCache sync.Map // scriptURL -> string
captchaV2HeaderOrder = []string{ captchaHeaderOrder = []string{
"host", "host",
"content-length", "content-length",
"sec-ch-ua-platform", "sec-ch-ua-platform",
@@ -61,52 +61,52 @@ var (
"accept-encoding", "accept-encoding",
"priority", "priority",
} }
captchaV2PHeaderOrder = []string{":method", ":path", ":authority", ":scheme"} captchaPHeaderOrder = []string{":method", ":path", ":authority", ":scheme"}
) )
type captchaV2Init struct { type captchaInit struct {
Data captchaV2InitData `json:"data"` Data captchaInitData `json:"data"`
} }
type captchaV2InitData struct { type captchaInitData struct {
ShowCaptchaType string `json:"show_captcha_type"` ShowCaptchaType string `json:"show_captcha_type"`
CaptchaSettings []captchaV2InitSetting `json:"captcha_settings"` CaptchaSettings []captchaInitSetting `json:"captcha_settings"`
} }
type captchaV2InitSetting struct { type captchaInitSetting struct {
Type string `json:"type"` Type string `json:"type"`
Settings string `json:"settings"` Settings string `json:"settings"`
} }
type captchaV2Page struct { type captchaPage struct {
PowInput string PowInput string
PowDifficulty int PowDifficulty int
ScriptURL string ScriptURL string
Init *captchaV2Init Init *captchaInit
} }
type captchaV2Check struct { type captchaCheck struct {
Status string Status string
SuccessToken string SuccessToken string
ShowType string ShowType string
} }
type captchaV2ShowTypeError struct { type captchaShowTypeError struct {
ShowType string ShowType string
} }
func (e *captchaV2ShowTypeError) Error() string { func (e *captchaShowTypeError) Error() string {
return "captcha show type mismatch: " + e.ShowType return "captcha show type mismatch: " + e.ShowType
} }
type captchaV2Session struct { type captchaSession struct {
ctx context.Context ctx context.Context
client tlsclient.HttpClient client tlsclient.HttpClient
profile Profile profile Profile
savedProfile *SavedProfile savedProfile *SavedProfile
} }
func solveVkCaptchaV2( func solveCaptchaAuto(
ctx context.Context, ctx context.Context,
captchaErr *VkCaptchaError, captchaErr *VkCaptchaError,
streamID int, streamID int,
@@ -119,15 +119,15 @@ func solveVkCaptchaV2(
} }
log.Printf("[STREAM %d] [Captcha] Solving VK Smart Captcha automatically (v2)...", streamID) log.Printf("[STREAM %d] [Captcha] Solving VK Smart Captcha automatically (v2)...", streamID)
s := &captchaV2Session{ctx: ctx, client: client, profile: profile, savedProfile: savedProfile} s := &captchaSession{ctx: ctx, client: client, profile: profile, savedProfile: savedProfile}
for attempt := 1; attempt <= captchaV2MaxAttempts; attempt++ { for attempt := 1; attempt <= captchaMaxAttempts; attempt++ {
token, solveErr := s.solveOnce(captchaErr) token, solveErr := s.solveOnce(captchaErr)
if solveErr == nil { if solveErr == nil {
return token, nil return token, nil
} }
log.Printf("[STREAM %d] [Captcha] v2 captcha solve attempt %d failed: %v", streamID, attempt, solveErr) log.Printf("[STREAM %d] [Captcha] captcha solve attempt %d failed: %v", streamID, attempt, solveErr)
if errors.Is(solveErr, errCaptchaV2RateLimit) { if errors.Is(solveErr, errCaptchaRateLimit) {
return "", solveErr return "", solveErr
} }
@@ -143,16 +143,16 @@ func solveVkCaptchaV2(
case <-timer.C: case <-timer.C:
} }
} }
return "", fmt.Errorf("v2 captcha attempts exhausted") return "", fmt.Errorf("captcha attempts exhausted")
} }
func (s *captchaV2Session) solveOnce(captchaErr *VkCaptchaError) (string, error) { func (s *captchaSession) solveOnce(captchaErr *VkCaptchaError) (string, error) {
html, err := s.fetchCaptchaHTML(captchaErr.RedirectURI) html, err := s.fetchCaptchaHTML(captchaErr.RedirectURI)
if err != nil { if err != nil {
return "", err return "", err
} }
page, err := parseCaptchaV2Page(html) page, err := parseCaptchaPage(html)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -172,19 +172,19 @@ func (s *captchaV2Session) solveOnce(captchaErr *VkCaptchaError) (string, error)
return "", errors.New("failed to find slider captcha settings") return "", errors.New("failed to find slider captcha settings")
} }
log.Printf("v2 captcha solving pow difficulty=%d", page.PowDifficulty) log.Printf("captcha solving pow difficulty=%d", page.PowDifficulty)
hash := solveCaptchaPoWV2(s.ctx, page.PowInput, page.PowDifficulty) hash := solveCaptchaPoW(s.ctx, page.PowInput, page.PowDifficulty)
if hash == "" { if hash == "" {
return "", errors.New("captcha pow failed") return "", errors.New("captcha pow failed")
} }
log.Printf("v2 captcha pow solved") log.Printf("captcha pow solved")
base := captchaV2BaseValues(captchaErr.SessionToken) base := captchaBaseValues(captchaErr.SessionToken)
if _, settingsErr := s.captchaRequest("captchaNotRobot.settings", base); settingsErr != nil { if _, settingsErr := s.captchaRequest("captchaNotRobot.settings", base); settingsErr != nil {
return "", fmt.Errorf("captcha settings failed: %w", settingsErr) return "", fmt.Errorf("captcha settings failed: %w", settingsErr)
} }
browserFP, err := captchaV2BrowserFP() browserFP, err := captchaBrowserFP()
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -192,15 +192,15 @@ func (s *captchaV2Session) solveOnce(captchaErr *VkCaptchaError) (string, error)
browserFP = s.savedProfile.BrowserFp browserFP = s.savedProfile.BrowserFp
} }
if m := reCaptchaV2Version.FindStringSubmatch(page.ScriptURL); len(m) > 1 { if m := reCaptchaVersion.FindStringSubmatch(page.ScriptURL); len(m) > 1 {
if m[1] != captchaV2ScriptVersion { if m[1] != captchaScriptVersion {
log.Printf("v2 captcha script version drift: known=%s latest=%s", captchaV2ScriptVersion, m[1]) log.Printf("captcha script version drift: known=%s latest=%s", captchaScriptVersion, m[1])
} }
} }
debugInfo, err := s.fetchDebugInfo(page.ScriptURL) debugInfo, err := s.fetchDebugInfo(page.ScriptURL)
if err != nil { if err != nil {
return "", fmt.Errorf("failed to fetch debug info: %w (script_version=%s)", err, captchaV2ScriptVersion) return "", fmt.Errorf("failed to fetch debug info: %w (script_version=%s)", err, captchaScriptVersion)
} }
showType := "" showType := ""
@@ -209,7 +209,7 @@ func (s *captchaV2Session) solveOnce(captchaErr *VkCaptchaError) (string, error)
} }
var token string var token string
for { for {
log.Printf("v2 captcha solving show_type=%s", showType) log.Printf("captcha solving show_type=%s", showType)
switch showType { switch showType {
case "slider": case "slider":
token, err = s.solveSliderCaptcha(captchaErr.SessionToken, browserFP, hash, sliderSettings, debugInfo) token, err = s.solveSliderCaptcha(captchaErr.SessionToken, browserFP, hash, sliderSettings, debugInfo)
@@ -221,12 +221,12 @@ func (s *captchaV2Session) solveOnce(captchaErr *VkCaptchaError) (string, error)
if err == nil { if err == nil {
break break
} }
if errors.Is(err, errCaptchaV2Bot) && !strings.EqualFold(showType, "slider") && sliderSettings != "" { if errors.Is(err, errCaptchaBot) && !strings.EqualFold(showType, "slider") && sliderSettings != "" {
log.Printf("v2 captcha checkbox returned BOT, trying slider challenge from page settings") log.Printf("captcha checkbox returned BOT, trying slider challenge from page settings")
showType = "slider" showType = "slider"
continue continue
} }
var stErr *captchaV2ShowTypeError var stErr *captchaShowTypeError
if !errors.As(err, &stErr) || stErr.ShowType == "" { if !errors.As(err, &stErr) || stErr.ShowType == "" {
return "", err return "", err
} }
@@ -234,12 +234,12 @@ func (s *captchaV2Session) solveOnce(captchaErr *VkCaptchaError) (string, error)
} }
if _, endErr := s.captchaRequest("captchaNotRobot.endSession", base); endErr != nil { if _, endErr := s.captchaRequest("captchaNotRobot.endSession", base); endErr != nil {
log.Printf("v2 captcha endSession failed: %v", endErr) log.Printf("captcha endSession failed: %v", endErr)
} }
return token, nil return token, nil
} }
func captchaV2BaseValues(sessionToken string) [][2]string { func captchaBaseValues(sessionToken string) [][2]string {
return [][2]string{ return [][2]string{
{"session_token", sessionToken}, {"session_token", sessionToken},
{"domain", "vk.com"}, {"domain", "vk.com"},
@@ -248,7 +248,7 @@ func captchaV2BaseValues(sessionToken string) [][2]string {
} }
} }
func captchaV2BrowserFP() (string, error) { func captchaBrowserFP() (string, error) {
b := make([]byte, 16) b := make([]byte, 16)
if _, err := rand.Read(b); err != nil { if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("browser fp generate: %w", err) return "", fmt.Errorf("browser fp generate: %w", err)
@@ -256,7 +256,7 @@ func captchaV2BrowserFP() (string, error) {
return hex.EncodeToString(b), nil return hex.EncodeToString(b), nil
} }
func (s *captchaV2Session) fetchCaptchaHTML(redirectURI string) (string, error) { func (s *captchaSession) fetchCaptchaHTML(redirectURI string) (string, error) {
body, err := s.doRaw(fhttp.MethodGet, redirectURI, nil, map[string]string{ body, err := s.doRaw(fhttp.MethodGet, redirectURI, nil, map[string]string{
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Sec-Fetch-Dest": "document", "Sec-Fetch-Dest": "document",
@@ -269,12 +269,12 @@ func (s *captchaV2Session) fetchCaptchaHTML(redirectURI string) (string, error)
return string(body), nil return string(body), nil
} }
func (s *captchaV2Session) fetchDebugInfo(scriptURL string) (string, error) { func (s *captchaSession) fetchDebugInfo(scriptURL string) (string, error) {
if cached, ok := captchaV2DebugCache.Load(scriptURL); ok { if cached, ok := captchaDebugCache.Load(scriptURL); ok {
if cachedDebugInfo, ok := cached.(string); ok { if cachedDebugInfo, ok := cached.(string); ok {
return cachedDebugInfo, nil return cachedDebugInfo, nil
} }
captchaV2DebugCache.Delete(scriptURL) captchaDebugCache.Delete(scriptURL)
} }
body, err := s.doRaw(fhttp.MethodGet, scriptURL, nil, map[string]string{ body, err := s.doRaw(fhttp.MethodGet, scriptURL, nil, map[string]string{
"Accept": "text/javascript,*/*", "Accept": "text/javascript,*/*",
@@ -283,43 +283,43 @@ func (s *captchaV2Session) fetchDebugInfo(scriptURL string) (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
m := reCaptchaV2DebugInfo.FindSubmatch(body) m := reCaptchaDebugInfo.FindSubmatch(body)
if len(m) < 2 { if len(m) < 2 {
return "", errors.New("debug_info match not found") return "", errors.New("debug_info match not found")
} }
v := string(m[1]) v := string(m[1])
captchaV2DebugCache.Store(scriptURL, v) captchaDebugCache.Store(scriptURL, v)
log.Printf("v2 captcha debug_info fetched url=%s", scriptURL) log.Printf("captcha debug_info fetched url=%s", scriptURL)
return v, nil return v, nil
} }
func parseCaptchaV2Page(html string) (*captchaV2Page, error) { func parseCaptchaPage(html string) (*captchaPage, error) {
page := &captchaV2Page{} page := &captchaPage{}
match := reCaptchaV2WindowInit.FindStringSubmatch(html) match := reCaptchaWindowInit.FindStringSubmatch(html)
if len(match) < 2 { if len(match) < 2 {
return nil, errors.New("captcha init json not found") return nil, errors.New("captcha init json not found")
} }
var init captchaV2Init var init captchaInit
if err := json.Unmarshal([]byte(match[1]), &init); err != nil { if err := json.Unmarshal([]byte(match[1]), &init); err != nil {
return nil, fmt.Errorf("captcha init json parse: %w", err) return nil, fmt.Errorf("captcha init json parse: %w", err)
} }
page.Init = &init page.Init = &init
match = reCaptchaV2ScriptSrc.FindStringSubmatch(html) match = reCaptchaScriptSrc.FindStringSubmatch(html)
if len(match) < 2 { if len(match) < 2 {
return nil, errors.New("captcha script url not found") return nil, errors.New("captcha script url not found")
} }
page.ScriptURL = match[1] page.ScriptURL = match[1]
if m := reCaptchaV2PowInput.FindStringSubmatch(html); len(m) >= 2 { if m := reCaptchaPowInput.FindStringSubmatch(html); len(m) >= 2 {
page.PowInput = m[1] page.PowInput = m[1]
} }
if page.PowInput == "" { if page.PowInput == "" {
return page, nil return page, nil
} }
match = reCaptchaV2Difficulty.FindStringSubmatch(html) match = reCaptchaDifficulty.FindStringSubmatch(html)
if len(match) < 2 { if len(match) < 2 {
return nil, errors.New("captcha difficulty const not found") return nil, errors.New("captcha difficulty const not found")
} }
@@ -331,8 +331,8 @@ func parseCaptchaV2Page(html string) (*captchaV2Page, error) {
return page, nil return page, nil
} }
func (s *captchaV2Session) captchaRequest(method string, form [][2]string) (map[string]any, error) { func (s *captchaSession) captchaRequest(method string, form [][2]string) (map[string]any, error) {
endpoint := "https://api.vk.ru/method/" + method + "?v=" + captchaV2APIVersion endpoint := "https://api.vk.ru/method/" + method + "?v=" + captchaAPIVersion
body, err := s.doRaw(fhttp.MethodPost, endpoint, form, map[string]string{ body, err := s.doRaw(fhttp.MethodPost, endpoint, form, map[string]string{
"Origin": "https://id.vk.com", "Origin": "https://id.vk.com",
"Referer": "https://id.vk.com/", "Referer": "https://id.vk.com/",
@@ -348,14 +348,14 @@ func (s *captchaV2Session) captchaRequest(method string, form [][2]string) (map[
return out, nil return out, nil
} }
func (s *captchaV2Session) performCaptchaCheck( func (s *captchaSession) performCaptchaCheck(
sessionToken string, sessionToken string,
browserFP string, browserFP string,
hash string, hash string,
answerJSON string, answerJSON string,
cursor string, cursor string,
debugInfo string, debugInfo string,
) (*captchaV2Check, error) { ) (*captchaCheck, error) {
values := [][2]string{ values := [][2]string{
{"session_token", sessionToken}, {"session_token", sessionToken},
{"domain", "vk.com"}, {"domain", "vk.com"},
@@ -377,27 +377,27 @@ func (s *captchaV2Session) performCaptchaCheck(
if err != nil { if err != nil {
return nil, fmt.Errorf("captcha check failed: %w", err) return nil, fmt.Errorf("captcha check failed: %w", err)
} }
check, err := parseCaptchaV2Check(resp) check, err := parseCaptchaCheck(resp)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if check.ShowType != "" { if check.ShowType != "" {
log.Printf("v2 captcha check status=%s show_type=%s", check.Status, check.ShowType) log.Printf("captcha check status=%s show_type=%s", check.Status, check.ShowType)
} else { } else {
log.Printf("v2 captcha check status=%s", check.Status) log.Printf("captcha check status=%s", check.Status)
} }
return check, nil return check, nil
} }
func parseCaptchaV2Check(raw map[string]any) (*captchaV2Check, error) { func parseCaptchaCheck(raw map[string]any) (*captchaCheck, error) {
resp, ok := raw["response"].(map[string]any) resp, ok := raw["response"].(map[string]any)
if !ok { if !ok {
return nil, fmt.Errorf("invalid captcha check response: %v", raw) return nil, fmt.Errorf("invalid captcha check response: %v", raw)
} }
out := &captchaV2Check{ out := &captchaCheck{
Status: captchaV2StringifyAny(resp["status"]), Status: captchaStringifyAny(resp["status"]),
SuccessToken: captchaV2StringifyAny(resp["success_token"]), SuccessToken: captchaStringifyAny(resp["success_token"]),
ShowType: captchaV2StringifyAny(resp["show_captcha_type"]), ShowType: captchaStringifyAny(resp["show_captcha_type"]),
} }
if out.Status == "" { if out.Status == "" {
return nil, fmt.Errorf("captcha check status missing: %v", raw) return nil, fmt.Errorf("captcha check status missing: %v", raw)
@@ -405,13 +405,13 @@ func parseCaptchaV2Check(raw map[string]any) (*captchaV2Check, error) {
return out, nil return out, nil
} }
func (s *captchaV2Session) solveCheckboxCaptcha( func (s *captchaSession) solveCheckboxCaptcha(
sessionToken string, sessionToken string,
browserFP string, browserFP string,
hash string, hash string,
debugInfo string, debugInfo string,
) (string, error) { ) (string, error) {
deviceJSON := captchaV2DeviceInfo deviceJSON := captchaDeviceInfo
if s.savedProfile != nil && strings.TrimSpace(s.savedProfile.DeviceJSON) != "" { if s.savedProfile != nil && strings.TrimSpace(s.savedProfile.DeviceJSON) != "" {
deviceJSON = s.savedProfile.DeviceJSON deviceJSON = s.savedProfile.DeviceJSON
} }
@@ -437,13 +437,13 @@ func (s *captchaV2Session) solveCheckboxCaptcha(
return "", err return "", err
} }
if check.ShowType != "" && !strings.EqualFold(check.ShowType, "checkbox") { if check.ShowType != "" && !strings.EqualFold(check.ShowType, "checkbox") {
return "", &captchaV2ShowTypeError{ShowType: check.ShowType} return "", &captchaShowTypeError{ShowType: check.ShowType}
} }
if strings.EqualFold(check.Status, "error_limit") { if strings.EqualFold(check.Status, "error_limit") {
return "", errCaptchaV2RateLimit return "", errCaptchaRateLimit
} }
if strings.EqualFold(check.Status, "bot") { if strings.EqualFold(check.Status, "bot") {
return "", fmt.Errorf("%w: checkbox captcha rejected: status=%s", errCaptchaV2Bot, check.Status) return "", fmt.Errorf("%w: checkbox captcha rejected: status=%s", errCaptchaBot, check.Status)
} }
if !strings.EqualFold(check.Status, "ok") { if !strings.EqualFold(check.Status, "ok") {
return "", fmt.Errorf("checkbox captcha rejected: status=%s", check.Status) return "", fmt.Errorf("checkbox captcha rejected: status=%s", check.Status)
@@ -454,7 +454,7 @@ func (s *captchaV2Session) solveCheckboxCaptcha(
return check.SuccessToken, nil return check.SuccessToken, nil
} }
func solveCaptchaPoWV2(ctx context.Context, input string, difficulty int) string { func solveCaptchaPoW(ctx context.Context, input string, difficulty int) string {
if input == "" || difficulty <= 0 { if input == "" || difficulty <= 0 {
return "" return ""
} }
@@ -476,7 +476,7 @@ func solveCaptchaPoWV2(ctx context.Context, input string, difficulty int) string
return "" return ""
} }
func (s *captchaV2Session) doRaw( func (s *captchaSession) doRaw(
method string, method string,
endpoint string, endpoint string,
form [][2]string, form [][2]string,
@@ -484,7 +484,7 @@ func (s *captchaV2Session) doRaw(
) ([]byte, error) { ) ([]byte, error) {
var body []byte var body []byte
if form != nil { if form != nil {
body = []byte(captchaV2EncodeForm(form)) body = []byte(captchaEncodeForm(form))
} }
req, err := fhttp.NewRequestWithContext(s.ctx, method, endpoint, bytes.NewReader(body)) req, err := fhttp.NewRequestWithContext(s.ctx, method, endpoint, bytes.NewReader(body))
if err != nil { if err != nil {
@@ -503,8 +503,8 @@ func (s *captchaV2Session) doRaw(
for k, v := range extraHeaders { for k, v := range extraHeaders {
req.Header.Set(k, v) req.Header.Set(k, v)
} }
req.Header[fhttp.HeaderOrderKey] = captchaV2HeaderOrder req.Header[fhttp.HeaderOrderKey] = captchaHeaderOrder
req.Header[fhttp.PHeaderOrderKey] = captchaV2PHeaderOrder req.Header[fhttp.PHeaderOrderKey] = captchaPHeaderOrder
resp, err := s.client.Do(req) resp, err := s.client.Do(req)
if err != nil { if err != nil {
@@ -512,13 +512,13 @@ func (s *captchaV2Session) doRaw(
} }
defer func() { defer func() {
if closeErr := resp.Body.Close(); closeErr != nil { if closeErr := resp.Body.Close(); closeErr != nil {
log.Printf("v2 captcha close body: %s", closeErr) log.Printf("captcha close body: %s", closeErr)
} }
}() }()
return io.ReadAll(resp.Body) return io.ReadAll(resp.Body)
} }
func captchaV2EncodeForm(values [][2]string) string { func captchaEncodeForm(values [][2]string) string {
if len(values) == 0 { if len(values) == 0 {
return "" return ""
} }
@@ -527,14 +527,14 @@ func captchaV2EncodeForm(values [][2]string) string {
if i > 0 { if i > 0 {
sb.WriteByte('&') sb.WriteByte('&')
} }
sb.WriteString(captchaV2QueryEscape(kv[0])) sb.WriteString(captchaQueryEscape(kv[0]))
sb.WriteByte('=') sb.WriteByte('=')
sb.WriteString(captchaV2QueryEscape(kv[1])) sb.WriteString(captchaQueryEscape(kv[1]))
} }
return sb.String() return sb.String()
} }
func captchaV2QueryEscape(s string) string { func captchaQueryEscape(s string) string {
const upper = "0123456789ABCDEF" const upper = "0123456789ABCDEF"
hexDigits := func(b byte) [3]byte { hexDigits := func(b byte) [3]byte {
return [3]byte{'%', upper[b>>4], upper[b&0xF]} return [3]byte{'%', upper[b>>4], upper[b&0xF]}
@@ -555,7 +555,7 @@ func captchaV2QueryEscape(s string) string {
return string(out) return string(out)
} }
func captchaV2StringifyAny(value any) string { func captchaStringifyAny(value any) string {
switch v := value.(type) { switch v := value.(type) {
case nil: case nil:
return "" return ""
@@ -19,14 +19,14 @@ import (
"sync" "sync"
) )
type sliderPuzzleV2 struct { type sliderPuzzle struct {
Image image.Image Image image.Image
Size int Size int
Swaps []int Swaps []int
Attempts int Attempts int
} }
type sliderGuessV2 struct { type sliderGuess struct {
Index int Index int
Swaps []int Swaps []int
Score int64 Score int64
@@ -36,7 +36,7 @@ type sliderGuessV2 struct {
ConsensusRank int ConsensusRank int
} }
func (s *captchaV2Session) solveSliderCaptcha( func (s *captchaSession) solveSliderCaptcha(
sessionToken string, sessionToken string,
browserFP string, browserFP string,
hash string, hash string,
@@ -55,13 +55,13 @@ func (s *captchaV2Session) solveSliderCaptcha(
if err != nil { if err != nil {
return "", fmt.Errorf("slider getContent failed: %w", err) return "", fmt.Errorf("slider getContent failed: %w", err)
} }
puzzle, err := parseSliderPuzzleV2(resp) puzzle, err := parseSliderPuzzle(resp)
if err != nil { if err != nil {
return "", err return "", err
} }
log.Printf("v2 slider puzzle decoded: grid=%d attempts=%d swaps=%d", puzzle.Size, puzzle.Attempts, len(puzzle.Swaps)) log.Printf("slider puzzle decoded: grid=%d attempts=%d swaps=%d", puzzle.Size, puzzle.Attempts, len(puzzle.Swaps))
guesses, err := rankSliderGuessesV2(puzzle.Image, puzzle.Size, puzzle.Swaps) guesses, err := rankSliderGuesses(puzzle.Image, puzzle.Size, puzzle.Swaps)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -73,9 +73,9 @@ func (s *captchaV2Session) solveSliderCaptcha(
if limit <= 0 { if limit <= 0 {
return "", errors.New("slider has no attempts available") return "", errors.New("slider has no attempts available")
} }
log.Printf("v2 slider guesses ranked: total=%d limit=%d", len(guesses), limit) log.Printf("slider guesses ranked: total=%d limit=%d", len(guesses), limit)
deviceJSON := captchaV2DeviceInfo deviceJSON := captchaDeviceInfo
if s.savedProfile != nil && strings.TrimSpace(s.savedProfile.DeviceJSON) != "" { if s.savedProfile != nil && strings.TrimSpace(s.savedProfile.DeviceJSON) != "" {
deviceJSON = s.savedProfile.DeviceJSON deviceJSON = s.savedProfile.DeviceJSON
} }
@@ -91,7 +91,7 @@ func (s *captchaV2Session) solveSliderCaptcha(
} }
for i := 0; i < limit; i++ { for i := 0; i < limit; i++ {
log.Printf("v2 slider attempt %d/%d (guess #%d)", i+1, limit, guesses[i].Index) log.Printf("slider attempt %d/%d (guess #%d)", i+1, limit, guesses[i].Index)
answerData, err := json.Marshal(struct { answerData, err := json.Marshal(struct {
Value []int `json:"value"` Value []int `json:"value"`
}{Value: guesses[i].Swaps}) }{Value: guesses[i].Swaps})
@@ -103,7 +103,7 @@ func (s *captchaV2Session) solveSliderCaptcha(
browserFP, browserFP,
hash, hash,
string(answerData), string(answerData),
buildSliderCursorV2(guesses[i].Index, len(guesses)), buildSliderCursor(guesses[i].Index, len(guesses)),
debugInfo, debugInfo,
) )
if err != nil { if err != nil {
@@ -113,26 +113,26 @@ func (s *captchaV2Session) solveSliderCaptcha(
if check.SuccessToken == "" { if check.SuccessToken == "" {
return "", errors.New("captcha success token not found") return "", errors.New("captcha success token not found")
} }
log.Printf("v2 slider accepted on attempt %d", i+1) log.Printf("slider accepted on attempt %d", i+1)
return check.SuccessToken, nil return check.SuccessToken, nil
} }
if strings.EqualFold(check.Status, "error_limit") { if strings.EqualFold(check.Status, "error_limit") {
return "", errCaptchaV2RateLimit return "", errCaptchaRateLimit
} }
} }
return "", errors.New("slider guesses exhausted") return "", errors.New("slider guesses exhausted")
} }
func parseSliderPuzzleV2(raw map[string]any) (*sliderPuzzleV2, error) { func parseSliderPuzzle(raw map[string]any) (*sliderPuzzle, error) {
resp, ok := raw["response"].(map[string]any) resp, ok := raw["response"].(map[string]any)
if !ok { if !ok {
return nil, fmt.Errorf("invalid slider content response: %v", raw) return nil, fmt.Errorf("invalid slider content response: %v", raw)
} }
status := captchaV2StringifyAny(resp["status"]) status := captchaStringifyAny(resp["status"])
if !strings.EqualFold(status, "ok") { if !strings.EqualFold(status, "ok") {
return nil, fmt.Errorf("slider getContent status: %s", status) return nil, fmt.Errorf("slider getContent status: %s", status)
} }
rawImage := captchaV2StringifyAny(resp["image"]) rawImage := captchaStringifyAny(resp["image"])
if rawImage == "" { if rawImage == "" {
return nil, errors.New("slider image missing") return nil, errors.New("slider image missing")
} }
@@ -157,7 +157,7 @@ func parseSliderPuzzleV2(raw map[string]any) (*sliderPuzzleV2, error) {
return nil, fmt.Errorf("invalid numeric value: %v", item) return nil, fmt.Errorf("invalid numeric value: %v", item)
} }
} }
size, swaps, attempts, err := splitSliderStepsV2(steps) size, swaps, attempts, err := splitSliderSteps(steps)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -169,10 +169,10 @@ func parseSliderPuzzleV2(raw map[string]any) (*sliderPuzzleV2, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("decode slider image: %w", err) return nil, fmt.Errorf("decode slider image: %w", err)
} }
return &sliderPuzzleV2{Image: img, Size: size, Swaps: swaps, Attempts: attempts}, nil return &sliderPuzzle{Image: img, Size: size, Swaps: swaps, Attempts: attempts}, nil
} }
func splitSliderStepsV2(steps []int) (int, []int, int, error) { func splitSliderSteps(steps []int) (int, []int, int, error) {
if len(steps) < 3 { if len(steps) < 3 {
return 0, nil, 0, errors.New("slider steps payload too short") return 0, nil, 0, errors.New("slider steps payload too short")
} }
@@ -185,7 +185,7 @@ func splitSliderStepsV2(steps []int) (int, []int, int, error) {
if len(tail)%2 != 0 { if len(tail)%2 != 0 {
attempts = tail[len(tail)-1] attempts = tail[len(tail)-1]
tail = tail[:len(tail)-1] tail = tail[:len(tail)-1]
log.Printf("v2 slider payload had odd-length tail; fallback attempts=%d", attempts) log.Printf("slider payload had odd-length tail; fallback attempts=%d", attempts)
} }
if attempts <= 0 { if attempts <= 0 {
attempts = 4 attempts = 4
@@ -196,24 +196,24 @@ func splitSliderStepsV2(steps []int) (int, []int, int, error) {
return size, tail, attempts, nil return size, tail, attempts, nil
} }
func rankSliderGuessesV2(img image.Image, gridSize int, swaps []int) ([]sliderGuessV2, error) { func rankSliderGuesses(img image.Image, gridSize int, swaps []int) ([]sliderGuess, error) {
candidateCount := len(swaps) / 2 candidateCount := len(swaps) / 2
if candidateCount == 0 { if candidateCount == 0 {
return nil, errors.New("slider has no candidates") return nil, errors.New("slider has no candidates")
} }
guesses := make([]sliderGuessV2, candidateCount) guesses := make([]sliderGuess, candidateCount)
for idx := 1; idx <= candidateCount; idx++ { for idx := 1; idx <= candidateCount; idx++ {
active := activeSwapsForIndexV2(swaps, idx) active := activeSwapsForIndex(swaps, idx)
mapping, err := applySliderSwapsV2(gridSize, active) mapping, err := applySliderSwaps(gridSize, active)
if err != nil { if err != nil {
return nil, err return nil, err
} }
guesses[idx-1] = sliderGuessV2{Index: idx, Swaps: active} guesses[idx-1] = sliderGuess{Index: idx, Swaps: active}
guesses[idx-1].ScoreLuma = seamScoreLumaV2(img, gridSize, mapping) guesses[idx-1].ScoreLuma = seamScoreLuma(img, gridSize, mapping)
} }
lumaOrder := append([]sliderGuessV2(nil), guesses...) lumaOrder := append([]sliderGuess(nil), guesses...)
sort.SliceStable(lumaOrder, func(i, j int) bool { sort.SliceStable(lumaOrder, func(i, j int) bool {
if lumaOrder[i].ScoreLuma == lumaOrder[j].ScoreLuma { if lumaOrder[i].ScoreLuma == lumaOrder[j].ScoreLuma {
return lumaOrder[i].Index < lumaOrder[j].Index return lumaOrder[i].Index < lumaOrder[j].Index
@@ -258,12 +258,12 @@ func rankSliderGuessesV2(img image.Image, gridSize int, swaps []int) ([]sliderGu
for range workers { for range workers {
wg.Go(func() { wg.Go(func() {
for index := range jobCh { for index := range jobCh {
mapping, err := applySliderSwapsV2(gridSize, guesses[index-1].Swaps) mapping, err := applySliderSwaps(gridSize, guesses[index-1].Swaps)
if err != nil { if err != nil {
resCh <- stage2Result{index: index, err: err} resCh <- stage2Result{index: index, err: err}
continue continue
} }
rgb, text := seamScoreRGBTextV2(img, gridSize, mapping) rgb, text := seamScoreRGBText(img, gridSize, mapping)
resCh <- stage2Result{index: index, rgb: rgb, text: text} resCh <- stage2Result{index: index, rgb: rgb, text: text}
} }
}) })
@@ -283,14 +283,14 @@ func rankSliderGuessesV2(img image.Image, gridSize int, swaps []int) ([]sliderGu
g.ScoreText = r.text g.ScoreText = r.text
} }
stage2 := make([]sliderGuessV2, 0, stage2Count) stage2 := make([]sliderGuess, 0, stage2Count)
for _, g := range guesses { for _, g := range guesses {
if _, ok := stage2Set[g.Index]; ok { if _, ok := stage2Set[g.Index]; ok {
stage2 = append(stage2, g) stage2 = append(stage2, g)
} }
} }
rgbOrder := append([]sliderGuessV2(nil), stage2...) rgbOrder := append([]sliderGuess(nil), stage2...)
sort.SliceStable(rgbOrder, func(i, j int) bool { sort.SliceStable(rgbOrder, func(i, j int) bool {
if rgbOrder[i].ScoreRGB == rgbOrder[j].ScoreRGB { if rgbOrder[i].ScoreRGB == rgbOrder[j].ScoreRGB {
return rgbOrder[i].Index < rgbOrder[j].Index return rgbOrder[i].Index < rgbOrder[j].Index
@@ -302,7 +302,7 @@ func rankSliderGuessesV2(img image.Image, gridSize int, swaps []int) ([]sliderGu
rgbRank[g.Index] = rank rgbRank[g.Index] = rank
} }
textOrder := append([]sliderGuessV2(nil), stage2...) textOrder := append([]sliderGuess(nil), stage2...)
sort.SliceStable(textOrder, func(i, j int) bool { sort.SliceStable(textOrder, func(i, j int) bool {
if textOrder[i].ScoreText == textOrder[j].ScoreText { if textOrder[i].ScoreText == textOrder[j].ScoreText {
return textOrder[i].Index < textOrder[j].Index return textOrder[i].Index < textOrder[j].Index
@@ -337,7 +337,7 @@ func rankSliderGuessesV2(img image.Image, gridSize int, swaps []int) ([]sliderGu
return guesses, nil return guesses, nil
} }
func activeSwapsForIndexV2(swaps []int, index int) []int { func activeSwapsForIndex(swaps []int, index int) []int {
if index <= 0 { if index <= 0 {
return []int{} return []int{}
} }
@@ -348,7 +348,7 @@ func activeSwapsForIndexV2(swaps []int, index int) []int {
return append([]int(nil), swaps[:end]...) return append([]int(nil), swaps[:end]...)
} }
func applySliderSwapsV2(gridSize int, swaps []int) ([]int, error) { func applySliderSwaps(gridSize int, swaps []int) ([]int, error) {
tileCount := gridSize * gridSize tileCount := gridSize * gridSize
if tileCount <= 0 { if tileCount <= 0 {
return nil, fmt.Errorf("invalid slider tile count: %d", tileCount) return nil, fmt.Errorf("invalid slider tile count: %d", tileCount)
@@ -371,7 +371,7 @@ func applySliderSwapsV2(gridSize int, swaps []int) ([]int, error) {
return mapping, nil return mapping, nil
} }
func seamScoreLumaV2(img image.Image, gridSize int, mapping []int) int64 { func seamScoreLuma(img image.Image, gridSize int, mapping []int) int64 {
bounds := img.Bounds() bounds := img.Bounds()
var score int64 var score int64
for row := 0; row < gridSize; row++ { for row := 0; row < gridSize; row++ {
@@ -388,9 +388,9 @@ func seamScoreLumaV2(img image.Image, gridSize int, mapping []int) int64 {
} }
for y := 0; y < h; y++ { for y := 0; y < h; y++ {
yy := leftDst.Min.Y + y yy := leftDst.Min.Y + y
a := sampleLumaMappedV2(img, leftDst, leftSrc, leftDst.Max.X-1, yy) a := sampleLumaMapped(img, leftDst, leftSrc, leftDst.Max.X-1, yy)
b := sampleLumaMappedV2(img, rightDst, rightSrc, rightDst.Min.X, yy) b := sampleLumaMapped(img, rightDst, rightSrc, rightDst.Min.X, yy)
score += int64(absIntV2(int(a) - int(b))) score += int64(absInt(int(a) - int(b)))
} }
} }
} }
@@ -408,16 +408,16 @@ func seamScoreLumaV2(img image.Image, gridSize int, mapping []int) int64 {
} }
for x := 0; x < w; x++ { for x := 0; x < w; x++ {
xx := topDst.Min.X + x xx := topDst.Min.X + x
a := sampleLumaMappedV2(img, topDst, topSrc, xx, topDst.Max.Y-1) a := sampleLumaMapped(img, topDst, topSrc, xx, topDst.Max.Y-1)
b := sampleLumaMappedV2(img, bottomDst, bottomSrc, xx, bottomDst.Min.Y) b := sampleLumaMapped(img, bottomDst, bottomSrc, xx, bottomDst.Min.Y)
score += int64(absIntV2(int(a) - int(b))) score += int64(absInt(int(a) - int(b)))
} }
} }
} }
return score return score
} }
func seamScoreRGBTextV2(img image.Image, gridSize int, mapping []int) (int64, float64) { func seamScoreRGBText(img image.Image, gridSize int, mapping []int) (int64, float64) {
bounds := img.Bounds() bounds := img.Bounds()
height := float64(bounds.Dy()) height := float64(bounds.Dy())
textCenters := []float64{ textCenters := []float64{
@@ -431,9 +431,9 @@ func seamScoreRGBTextV2(img image.Image, gridSize int, mapping []int) (int64, fl
} }
weight := func(y int) float64 { weight := func(y int) float64 {
yf := float64(y) yf := float64(y)
best := absFloatV2(yf - textCenters[0]) best := absFloat(yf - textCenters[0])
for i := 1; i < len(textCenters); i++ { for i := 1; i < len(textCenters); i++ {
d := absFloatV2(yf - textCenters[i]) d := absFloat(yf - textCenters[i])
if d < best { if d < best {
best = d best = d
} }
@@ -457,12 +457,12 @@ func seamScoreRGBTextV2(img image.Image, gridSize int, mapping []int) (int64, fl
} }
for y := 0; y < h; y++ { for y := 0; y < h; y++ {
yy := leftDst.Min.Y + y yy := leftDst.Min.Y + y
l := sampleColorMappedV2(img, leftDst, leftSrc, leftDst.Max.X-1, yy) l := sampleColorMapped(img, leftDst, leftSrc, leftDst.Max.X-1, yy)
r := sampleColorMappedV2(img, rightDst, rightSrc, rightDst.Min.X, yy) r := sampleColorMapped(img, rightDst, rightSrc, rightDst.Min.X, yy)
rgbScore += pixelDiff(l, r) rgbScore += pixelDiff(l, r)
_, _, lb, _ := l.RGBA() _, _, lb, _ := l.RGBA()
_, _, rb, _ := r.RGBA() _, _, rb, _ := r.RGBA()
textScore += weight(yy) * float64(absIntV2(int(lb>>8)-int(rb>>8))) textScore += weight(yy) * float64(absInt(int(lb>>8)-int(rb>>8)))
} }
} }
} }
@@ -480,19 +480,19 @@ func seamScoreRGBTextV2(img image.Image, gridSize int, mapping []int) (int64, fl
} }
for x := 0; x < w; x++ { for x := 0; x < w; x++ {
xx := topDst.Min.X + x xx := topDst.Min.X + x
t := sampleColorMappedV2(img, topDst, topSrc, xx, topDst.Max.Y-1) t := sampleColorMapped(img, topDst, topSrc, xx, topDst.Max.Y-1)
b := sampleColorMappedV2(img, bottomDst, bottomSrc, xx, bottomDst.Min.Y) b := sampleColorMapped(img, bottomDst, bottomSrc, xx, bottomDst.Min.Y)
rgbScore += pixelDiff(t, b) rgbScore += pixelDiff(t, b)
_, _, tb, _ := t.RGBA() _, _, tb, _ := t.RGBA()
_, _, bb, _ := b.RGBA() _, _, bb, _ := b.RGBA()
textScore += 0.65 * float64(absIntV2(int(tb>>8)-int(bb>>8))) textScore += 0.65 * float64(absInt(int(tb>>8)-int(bb>>8)))
} }
} }
} }
return rgbScore, textScore return rgbScore, textScore
} }
func sampleColorMappedV2(img image.Image, dstRect image.Rectangle, srcRect image.Rectangle, dstX int, dstY int) color.Color { func sampleColorMapped(img image.Image, dstRect image.Rectangle, srcRect image.Rectangle, dstX int, dstY int) color.Color {
dx := dstRect.Dx() dx := dstRect.Dx()
if dx < 1 { if dx < 1 {
dx = 1 dx = 1
@@ -506,21 +506,21 @@ func sampleColorMappedV2(img image.Image, dstRect image.Rectangle, srcRect image
return img.At(sx, sy) return img.At(sx, sy)
} }
func sampleLumaMappedV2(img image.Image, dstRect image.Rectangle, srcRect image.Rectangle, dstX int, dstY int) uint8 { func sampleLumaMapped(img image.Image, dstRect image.Rectangle, srcRect image.Rectangle, dstX int, dstY int) uint8 {
c := sampleColorMappedV2(img, dstRect, srcRect, dstX, dstY) c := sampleColorMapped(img, dstRect, srcRect, dstX, dstY)
r, g, b, _ := c.RGBA() r, g, b, _ := c.RGBA()
y := (299*(r>>8) + 587*(g>>8) + 114*(b>>8)) / 1000 y := (299*(r>>8) + 587*(g>>8) + 114*(b>>8)) / 1000
return uint8(y) return uint8(y)
} }
func absFloatV2(v float64) float64 { func absFloat(v float64) float64 {
if v < 0 { if v < 0 {
return -v return -v
} }
return v return v
} }
func absIntV2(v int) int { func absInt(v int) int {
if v < 0 { if v < 0 {
return -v return -v
} }
@@ -550,7 +550,7 @@ func absDiff(left uint32, right uint32) int64 {
return int64(right - left) return int64(right - left)
} }
func buildSliderCursorV2(candidateIndex int, candidateCount int) string { func buildSliderCursor(candidateIndex int, candidateCount int) string {
if candidateCount <= 0 { if candidateCount <= 0 {
return "[]" return "[]"
} }
+1 -1
View File
@@ -460,7 +460,7 @@ func solveVkCaptcha(ctx context.Context, captchaErr *VkCaptchaError, streamID in
profile = sp.Profile profile = sp.Profile
} }
successToken, err := solveVkCaptchaV2(ctx, captchaErr, streamID, client, profile, savedProfile) successToken, err := solveCaptchaAuto(ctx, captchaErr, streamID, client, profile, savedProfile)
if err != nil { if err != nil {
return "", err return "", err
} }