style: перевести комментарии на русский, убрать очевидные

This commit is contained in:
samosvalishe committed 2026-05-21 12:31:50 +03:00
1 parent ada9b949a4
commit e417dac087
48 files changed
+659 -671

No files matched your search

+3 -3
View File
@@ -10,9 +10,9 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// DefaultAutoSolve drives the in-page widget flow. It loads a saved real
// browser profile when available so the captcha origin sees consistent
// fingerprints across the page load and the solve POST.
// DefaultAutoSolve запускает in-page widget flow. Загружает сохранённый профиль
// браузера, если доступен, — капча видит стабильные fingerprints на этапе
// загрузки страницы и POST-запроса.
func DefaultAutoSolve(
ctx context.Context,
captchaErr *captcha.Error,
+6 -6
View File
@@ -6,8 +6,8 @@ import (
"sync/atomic"
)
// StreamCredentialsCache holds the resolved TURN creds for a group of streams
// plus auth-error tracking for invalidation decisions.
// StreamCredentialsCache хранит TURN-реквизиты для группы потоков
// и счётчик ошибок для решений об инвалидации.
type StreamCredentialsCache struct {
creds TurnCredentials
mutex sync.RWMutex
@@ -15,7 +15,7 @@ type StreamCredentialsCache struct {
lastErrorTime atomic.Int64
}
// Store maps cache-id (streamID / streamsPerCache) -> StreamCredentialsCache.
// Store отображает cache-id (streamID / streamsPerCache) → StreamCredentialsCache.
type Store struct {
mu sync.RWMutex
caches map[int]*StreamCredentialsCache
@@ -57,7 +57,7 @@ func (s *Store) Get(streamID int) *StreamCredentialsCache {
return cache
}
// Invalidate clears the creds for the given stream's cache and resets error state.
// Invalidate сбрасывает реквизиты кэша потока и обнуляет счётчик ошибок.
func (c *StreamCredentialsCache) Invalidate() {
c.mutex.Lock()
c.creds = TurnCredentials{}
@@ -67,8 +67,8 @@ func (c *StreamCredentialsCache) Invalidate() {
c.lastErrorTime.Store(0)
}
// IsAuthError matches the historical heuristic used by the TURN client: a TURN
// allocate failure mentioning auth/401/stale-nonce should trigger cache invalidate.
// IsAuthError проверяет ошибку по эвристике TURN-клиента:
// auth/401/stale-nonce — признак инвалидации кэша.
func IsAuthError(err error) bool {
if err == nil {
return false
+31 -32
View File
@@ -16,37 +16,38 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// Config configures a Client. Zero values pick safe defaults except for Dialer
// (must be set explicitly to preserve the existing custom-DNS behavior).
// Config конфигурирует Client. Нулевые значения — безопасные дефолты,
// кроме Dialer (должен быть задан явно для кастомного DNS).
type Config struct {
// Credentials to try in order. nil/empty -> DefaultCredentials.
// Credentials для перебора по порядку. nil/empty → DefaultCredentials.
Credentials []VKCredentials
// Dialer used by the HTTP transport for VK API requests.
// Dialer для HTTP-транспорта запросов к VK API.
Dialer net.Dialer
// ManualOnly forces the manual captcha path on the first attempt.
// ManualOnly форсирует ручной путь captcha с первой попытки.
ManualOnly bool
// StreamsPerCache is the divisor for streamID -> cacheID. <=0 -> default.
// StreamsPerCache — делитель streamID → cacheID. <=0 → дефолт.
StreamsPerCache int
// StreamsAlive returns the count of currently-connected streams; used to
// decide whether an exhausted captcha is fatal vs throttleable. nil -> 1.
// StreamsAlive возвращает число подключённых потоков; используется для
// решения, является ли исчерпанная captcha фатальной или только throttle.
// nil → 1.
StreamsAlive func() int32
// AutoSolver / ManualSolver are pluggable captcha solvers. nil values
// disable that path (the flow will fall through to the next attempt).
// AutoSolver / ManualSolver — подключаемые решалки captcha. nil отключает
// соответствующий путь (поток переходит к следующей попытке).
AutoSolver AutoSolveFunc
ManualSolver ManualSolveFunc
// Log is the leveled logger. nil -> no-op.
// Log — уровневый логгер. nil → no-op.
Log logx.Logger
}
// Client is the VK auth + creds-cache facade used by callers. It owns the
// per-stream-group cache, the global request throttle, the captcha lockout
// timer, and the auth-error counter used to invalidate stale TURN creds.
// Client — фасад VK-аутентификации и кэша реквизитов. Владеет кэшем группы
// потоков, глобальным throttle запросов, таймером блокировки captcha и счётчиком
// ошибок аутентификации для инвалидации устаревших TURN-реквизитов.
type Client struct {
credentials []VKCredentials
dialer net.Dialer
@@ -63,17 +64,16 @@ type Client struct {
fetchMu sync.Mutex
lastFetchTime time.Time
// tokenChain is the per-creds 4-step fetcher. Production wires this to
// (*Client).getTokenChain; tests inject a fake.
// tokenChain — 4-шаговый получатель токена для пары credentials.
// В prod подключён (*Client).getTokenChain; тесты подменяют fake.
tokenChain tokenChainFn
// minFetchInterval gates back-to-back VK requests. Tests can lower this.
// minFetchIntervalFn ограничивает частоту запросов к VK. Тесты снижают.
minFetchIntervalFn func() time.Duration
}
type tokenChainFn func(ctx context.Context, link string, streamID int, creds VKCredentials, jar tlsclient.CookieJar) (string, string, []string, error)
// New builds a Client from cfg.
func New(cfg Config) *Client {
c := &Client{
credentials: cfg.Credentials,
@@ -101,8 +101,8 @@ func New(cfg Config) *Client {
return c
}
// GetCredentials returns (username, password, server-addr) suitable for a TURN
// allocate, fetching from VK (with throttle + cache) only when needed.
// GetCredentials возвращает (username, password, server-addr) для TURN-allocate,
// обращаясь к VK (с throttle + кэшем) только при необходимости.
func (c *Client) GetCredentials(ctx context.Context, link string, streamID int) (string, string, string, error) {
cache := c.store.Get(streamID)
cacheID := c.store.CacheID(streamID)
@@ -142,9 +142,9 @@ func (c *Client) GetCredentials(ctx context.Context, link string, streamID int)
return user, pass, addr, nil
}
// HandleAuthError increments the auth-error counter for the stream's cache and
// invalidates when the threshold is reached within the rolling window.
// Returns true when the cache was invalidated.
// HandleAuthError увеличивает счётчик ошибок аутентификации кэша потока и
// инвалидирует кэш при достижении порога внутри скользящего окна.
// Возвращает true при инвалидации.
func (c *Client) HandleAuthError(streamID int) bool {
cache := c.store.Get(streamID)
cacheID := c.store.CacheID(streamID)
@@ -167,28 +167,27 @@ func (c *Client) HandleAuthError(streamID int) bool {
return false
}
// ResetErrors zeroes the auth-error counter (call on successful allocate).
// ResetErrors обнуляет счётчик ошибок аутентификации (вызывать при успешном allocate).
func (c *Client) ResetErrors(streamID int) {
c.store.Get(streamID).errorCount.Store(0)
}
// LockoutUntilUnix returns the unix-second deadline the global captcha lockout
// is set to, or 0 when no lockout is active.
// LockoutUntilUnix возвращает unix-секунду дедлайна глобальной блокировки captcha
// или 0, если блокировки нет.
func (c *Client) LockoutUntilUnix() int64 {
return c.lockout.Load()
}
// IsAuthError mirrors the package-level IsAuthError as a method so callers can
// program against a small interface.
// IsAuthError оборачивает пакетный IsAuthError как метод для работы через интерфейс.
func (c *Client) IsAuthError(err error) bool { return IsAuthError(err) }
// engageLockout arms the global captcha lockout for d from now.
// engageLockout устанавливает глобальную блокировку captcha на d с момента вызова.
func (c *Client) engageLockout(d time.Duration) {
c.lockout.Store(time.Now().Add(d).Unix())
}
// fetchSerialized enforces the 3s + jitter inter-request gap and then performs
// the try-all-credentials fetch.
// fetchSerialized соблюдает интервал 3s+jitter между запросами, затем
// выполняет перебор всех credentials.
func (c *Client) fetchSerialized(ctx context.Context, link string, streamID int) (string, string, []string, error) {
c.fetchMu.Lock()
defer c.fetchMu.Unlock()
@@ -208,7 +207,7 @@ func (c *Client) fetchSerialized(ctx context.Context, link string, streamID int)
return c.fetch(ctx, link, streamID)
}
// fetch loops over c.credentials, returning on first success or terminal error.
// fetch перебирает c.credentials, возвращая первый успех или терминальную ошибку.
func (c *Client) fetch(ctx context.Context, link string, streamID int) (string, string, []string, error) {
if time.Now().Unix() < c.lockout.Load() {
return "", "", nil, fmt.Errorf("%w: %w", ErrCaptchaWaitRequired, ErrLockoutActive)
+8 -8
View File
@@ -10,7 +10,7 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// CaptchaSolveMode selects between auto-solving and manual-browser fallback.
// CaptchaSolveMode — выбор между автоматическим решением и ручным браузерным fallback.
type CaptchaSolveMode int
const (
@@ -18,8 +18,8 @@ const (
CaptchaSolveModeManual
)
// CaptchaSolveModeForAttempt picks the solver to use on a given retry attempt.
// Returns (mode, true) when a mode is available, (_, false) when exhausted.
// CaptchaSolveModeForAttempt выбирает решалку для конкретной попытки retry.
// Возвращает (mode, true) если режим доступен, (_, false) если исчерпан.
func CaptchaSolveModeForAttempt(attempt int, manualOnly bool) (CaptchaSolveMode, bool) {
if manualOnly {
return CaptchaSolveModeManual, attempt == 0
@@ -44,8 +44,8 @@ func CaptchaSolveModeLabel(mode CaptchaSolveMode) string {
}
}
// AutoSolveFunc returns a success_token for the captcha when solvable via the
// in-page widget flow. Implementations must respect ctx cancellation.
// AutoSolveFunc возвращает success_token для captcha через in-page widget flow.
// Реализации обязаны соблюдать отмену ctx.
type AutoSolveFunc func(
ctx context.Context,
captchaErr *captcha.Error,
@@ -54,9 +54,9 @@ type AutoSolveFunc func(
profile browserprofile.Profile,
) (token string, err error)
// ManualSolveFunc opens the local browser-based fallback. Returns either a
// success_token (token != "") or a captcha_key, depending on which path the
// VK error exposed.
// ManualSolveFunc открывает локальный браузерный fallback. Возвращает либо
// success_token (token != ""), либо captcha_key — в зависимости от пути
// ошибки VK.
type ManualSolveFunc func(
ctx context.Context,
captchaErr *captcha.Error,
+8 -8
View File
@@ -12,9 +12,9 @@ import (
"github.com/bogdanfinn/tls-client/profiles"
)
// getTokenChain walks the 4-step VK token exchange for one client_id/secret
// pair and returns the resulting TURN allocate triple. Captcha errors trigger
// the configured auto/manual solver chain.
// getTokenChain выполняет 4-шаговый обмен токенами VK для одной пары client_id/secret
// и возвращает тройку TURN-allocate. Ошибки captcha запускают настроенную цепочку
// auto/manual solver.
func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, creds VKCredentials, jar tlsclient.CookieJar) (string, string, []string, error) {
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",
@@ -38,7 +38,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
c.log.Infof("[STREAM %d] [VK Auth] Connecting Identity - Name: %s | User-Agent: %s", streamID, name, profile.UserAgent)
// Step 1: anonymous app token.
// Шаг 1: анонимный app-токен.
token1, err := c.fetchAnonToken(ctx, httpClient, profile, creds)
if err != nil {
return "", "", nil, err
@@ -46,7 +46,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
vkDelayRandom(100, 150)
// Step 1a: getCallPreview warmup (non-fatal).
// Шаг 1a: прогрев getCallPreview (не критично).
previewData := fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&fields=photo_200&access_token=%s", link, token1)
if _, prevErr := c.doRequest(ctx, httpClient, profile, previewData,
"https://api.vk.ru/method/calls.getCallPreview?v=5.275&client_id="+creds.ClientID); prevErr != nil {
@@ -55,7 +55,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
vkDelayRandom(200, 400)
// Step 2: anonymous call token (captcha may trigger here).
// Шаг 2: анонимный call-токен (здесь может сработать captcha).
token2, err := c.fetchCallToken(ctx, httpClient, profile, streamID, link, escapedName, token1, creds)
if err != nil {
return "", "", nil, err
@@ -63,7 +63,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
vkDelayRandom(100, 150)
// Step 3: ok.ru session_key.
// Шаг 3: ok.ru session_key.
sessionKey, err := c.fetchOkRuSession(ctx, httpClient, profile)
if err != nil {
return "", "", nil, err
@@ -71,6 +71,6 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
vkDelayRandom(100, 150)
// Step 4: TURN credentials.
// Шаг 4: TURN-реквизиты.
return c.fetchTurnCreds(ctx, httpClient, profile, streamID, link, token2, sessionKey)
}
+2 -2
View File
@@ -9,8 +9,8 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// fetchAnonToken performs step 1 of the token chain: it exchanges the app
// client_id/client_secret for an anonymous access token from login.vk.ru.
// fetchAnonToken — шаг 1 цепочки: обменивает app client_id/client_secret
// на анонимный access token из login.vk.ru.
func (c *Client) fetchAnonToken(ctx context.Context, httpClient tlsclient.HttpClient, profile browserprofile.Profile, creds VKCredentials) (string, error) {
data := fmt.Sprintf("client_id=%s&token_type=messages&client_secret=%s&version=1&app_id=%s",
creds.ClientID, creds.ClientSecret, creds.ClientID)
+8 -9
View File
@@ -13,9 +13,8 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// fetchCallToken performs step 2 of the token chain: it calls
// calls.getAnonymousToken and drives the captcha-retry loop until a call token
// is returned or all solve modes are exhausted.
// fetchCallToken — шаг 2 цепочки: вызывает calls.getAnonymousToken и ведёт
// цикл retry captcha до получения call-токена или исчерпания всех режимов решения.
func (c *Client) fetchCallToken(
ctx context.Context,
httpClient tlsclient.HttpClient,
@@ -59,8 +58,8 @@ func (c *Client) fetchCallToken(
}
}
// solveCaptcha drives one captcha solve attempt and returns the POST body for
// the next retry, or an error when all modes are exhausted.
// solveCaptcha выполняет одну попытку решения captcha и возвращает тело POST
// для следующего retry или ошибку при исчерпании всех режимов.
func (c *Client) solveCaptcha(
ctx context.Context,
httpClient tlsclient.HttpClient,
@@ -105,9 +104,9 @@ func (c *Client) solveCaptcha(
break
}
c.log.Infof("[STREAM %d] [Captcha] Triggering manual captcha fallback", streamID)
// Manual solver gets its own 3-min budget so a tight parent deadline
// doesn't cut user solve time. Parent cancellation (app shutdown) still
// propagates so the goroutine doesn't outlive the process.
// Ручной решалке выделяется свой 3-минутный бюджет — жёсткий parent-deadline
// не обрезает время пользователя. Отмена parent (завершение приложения)
// всё равно propagate, горутина не переживает процесс.
manualCtx, manualCancel := context.WithTimeout(ctx, 3*time.Minute)
type manualRes struct {
@@ -168,7 +167,7 @@ func (c *Client) solveCaptcha(
return buildCaptchaRetryData(link, escapedName, token1, captchaErr, successToken, captchaKey), nil
}
// buildCaptchaRetryData constructs the POST body for the next captcha attempt.
// buildCaptchaRetryData формирует тело POST для следующей попытки captcha.
func buildCaptchaRetryData(link, escapedName, token1 string, captchaErr *captcha.Error, successToken, captchaKey string) string {
if captchaKey != "" {
return fmt.Sprintf(
+2 -3
View File
@@ -10,9 +10,8 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// fetchTurnCreds performs step 4 of the token chain: it calls
// vchat.joinConversationByLink and extracts the TURN username, credential, and
// address list from the response.
// fetchTurnCreds — шаг 4 цепочки: вызывает vchat.joinConversationByLink
// и извлекает TURN username, credential и список адресов из ответа.
func (c *Client) fetchTurnCreds(
ctx context.Context,
httpClient tlsclient.HttpClient,
+2 -2
View File
@@ -11,8 +11,8 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// fetchOkRuSession performs step 3 of the token chain: it obtains an anonymous
// ok.ru session_key via auth.anonymLogin.
// fetchOkRuSession — шаг 3 цепочки: получает анонимный ok.ru session_key
// через auth.anonymLogin.
func (c *Client) fetchOkRuSession(ctx context.Context, httpClient tlsclient.HttpClient, profile browserprofile.Profile) (string, error) {
sessionData := fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":1.1,"client_type":"SDK_JS"}`, uuid.New())
data := fmt.Sprintf("session_data=%s&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA",
+2 -2
View File
@@ -14,8 +14,8 @@ import (
tlsclient "github.com/bogdanfinn/tls-client"
)
// doRequest sends a POST form request to url using the given tls client and
// browser profile, and unmarshals the JSON response body.
// doRequest отправляет POST form-запрос по url через tls-клиент с браузерным
// профилем и десериализует JSON-тело ответа.
func (c *Client) doRequest(ctx context.Context, httpClient tlsclient.HttpClient, profile browserprofile.Profile, data, url string) (map[string]any, error) {
parsedURL, err := neturl.Parse(url)
if err != nil {
+4 -5
View File
@@ -5,13 +5,13 @@ import (
"time"
)
// VKCredentials is one app_id/app_secret pair used to obtain anonymous tokens.
// VKCredentials — пара app_id/app_secret для получения анонимных токенов.
type VKCredentials struct {
ClientID string
ClientSecret string
}
// TurnCredentials is the resolved TURN allocation for a stream group.
// TurnCredentials — разрешённые TURN-реквизиты для группы потоков.
type TurnCredentials struct {
Username string
Password string
@@ -20,7 +20,7 @@ type TurnCredentials struct {
Link string
}
// DefaultCredentials mirrors the public VK SDK app IDs the client tries in order.
// DefaultCredentials — публичные app_id VK SDK; клиент перебирает по порядку.
var DefaultCredentials = []VKCredentials{
{ClientID: "6287487", ClientSecret: "QbYic1K3lEV5kTGiqlq2"}, // VK_WEB_APP_ID
{ClientID: "7879029", ClientSecret: "aR5NKGmm03GYrCiNKsaw"}, // VK_MVK_APP_ID
@@ -38,8 +38,7 @@ const (
DefaultStreamsPerCache = 10
)
// Sentinel errors produced by the auth flow. Callers use errors.Is.
// The string forms remain stable for log output.
// Sentinel-ошибки auth-потока. Строковые формы стабильны (используются в логах).
var (
ErrCaptchaWaitRequired = errors.New("CAPTCHA_WAIT_REQUIRED")
ErrFatalCaptchaNoStreams = errors.New("FATAL_CAPTCHA_FAILED_NO_STREAMS")
@@ -0,0 +1,47 @@
package vkauth
import (
"errors"
"time"
)
// VKCredentials — пара app_id/app_secret для получения anonymous-токенов.
type VKCredentials struct {
ClientID string
ClientSecret string
}
// TurnCredentials — резолвленный TURN-allocation для группы потоков.
type TurnCredentials struct {
Username string
Password string
ServerAddrs []string
ExpiresAt time.Time
Link string
}
// DefaultCredentials — публичные VK SDK app ID, которые клиент пробует по порядку.
var DefaultCredentials = []VKCredentials{
{ClientID: "6287487", ClientSecret: "QbYic1K3lEV5kTGiqlq2"}, // VK_WEB_APP_ID
{ClientID: "7879029", ClientSecret: "aR5NKGmm03GYrCiNKsaw"}, // VK_MVK_APP_ID
{ClientID: "52461373", ClientSecret: "o557NLIkAErNhakXrQ7A"}, // VK_WEB_VKVIDEO_APP_ID
{ClientID: "52649896", ClientSecret: "WStp4ihWG4l3nmXZgIbC"}, // VK_MVK_VKVIDEO_APP_ID
{ClientID: "51781872", ClientSecret: "IjjCNl4L4Tf5QZEXIHKK"}, // VK_ID_AUTH_APP
}
const (
CredentialLifetime = 10 * time.Minute
CacheSafetyMargin = 60 * time.Second
MaxCacheErrors = 3
ErrorWindow = 10 * time.Second
DefaultStreamsPerCache = 10
)
// Sentinel errors produced by the auth flow. Callers use errors.Is.
// The string forms remain stable for log output.
var (
ErrCaptchaWaitRequired = errors.New("CAPTCHA_WAIT_REQUIRED")
ErrFatalCaptchaNoStreams = errors.New("FATAL_CAPTCHA_FAILED_NO_STREAMS")
ErrLockoutActive = errors.New("global lockout active")
)