style: перевести комментарии на русский, убрать очевидные
This commit is contained in:
1 parent
ada9b949a4
commit
e417dac087
48 files changed
+659
-671
No files matched your search
@@ -25,12 +25,12 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/logx"
|
||||
)
|
||||
|
||||
// Log is the package-level logger. Defaults to no-op; main wires it via
|
||||
// SetLogger so captcha output respects the global -debug flag and levels.
|
||||
// Solve also accepts an explicit logger parameter for callers that want DI.
|
||||
// Log — пакетный логгер. По умолчанию no-op; main устанавливает его через
|
||||
// SetLogger, чтобы captcha-вывод подчинялся глобальному -debug. Solve также
|
||||
// принимает logger параметром для DI.
|
||||
var Log logx.Logger = logx.Nop()
|
||||
|
||||
// SetLogger installs a logger for this package. Safe to call once at startup.
|
||||
// SetLogger ставит логгер пакета. Безопасно вызывать один раз при старте.
|
||||
func SetLogger(l logx.Logger) { Log = logx.OrNop(l) }
|
||||
|
||||
const (
|
||||
@@ -124,9 +124,9 @@ func (s *captchaSession) logger() logx.Logger {
|
||||
return Log
|
||||
}
|
||||
|
||||
// Solve runs the automatic captcha challenge against VK's captchaNotRobot API
|
||||
// and returns a success token on success. log may be nil, in which case the
|
||||
// package-level Log is used.
|
||||
// Solve запускает авторешение captcha против VK captchaNotRobot API
|
||||
// и возвращает success-токен при успехе. log может быть nil — тогда
|
||||
// используется пакетный Log.
|
||||
func Solve(
|
||||
ctx context.Context,
|
||||
captchaErr *Error,
|
||||
@@ -479,8 +479,8 @@ func solveCaptchaPoW(ctx context.Context, input string, difficulty int) string {
|
||||
return ""
|
||||
}
|
||||
target := strings.Repeat("0", difficulty)
|
||||
// ctx-check every 1024 iterations keeps cancel latency under a few ms
|
||||
// even on weak ARM (was every 4096).
|
||||
// ctx-check каждые 1024 итерации — задержка отмены в пределах нескольких мс
|
||||
// даже на слабом ARM (было 4096).
|
||||
buf := make([]byte, 0, len(input)+20)
|
||||
buf = append(buf, input...)
|
||||
for nonce := 1; nonce <= 10_000_000; nonce++ {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
neturl "net/url"
|
||||
)
|
||||
|
||||
// Error describes a VK API "captcha required" error (error_code 14) and the
|
||||
// fields the solver needs to drive the challenge.
|
||||
// Error описывает ошибку VK API "captcha required" (error_code 14) и поля,
|
||||
// необходимые для решения challenge.
|
||||
type Error struct {
|
||||
ErrorCode int
|
||||
ErrorMsg string
|
||||
@@ -19,8 +19,8 @@ type Error struct {
|
||||
CaptchaAttempt string
|
||||
}
|
||||
|
||||
// ParseError extracts a captcha challenge from a VK API error payload. Returns
|
||||
// nil if required fields are missing.
|
||||
// ParseError извлекает captcha-challenge из payload ошибки VK API.
|
||||
// Возвращает nil, если обязательные поля отсутствуют.
|
||||
func ParseError(errData map[string]any) *Error {
|
||||
codeFloat, ok := errData["error_code"].(float64)
|
||||
if !ok {
|
||||
@@ -104,8 +104,8 @@ func ParseError(errData map[string]any) *Error {
|
||||
}
|
||||
}
|
||||
|
||||
// IsCaptcha reports whether this error represents an actionable captcha
|
||||
// challenge (error_code 14 with both redirect_uri and session_token present).
|
||||
// IsCaptcha сообщает, является ли это actionable captcha-challenge
|
||||
// (error_code 14 с непустыми redirect_uri и session_token).
|
||||
func (e *Error) IsCaptcha() bool {
|
||||
return e.ErrorCode == 14 && e.RedirectURI != "" && e.SessionToken != ""
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
// Package manual implements the manual CAPTCHA solving flow used as a
|
||||
// fallback when the auto solver (internal/client/captcha) fails or when
|
||||
// the user passes -manual-captcha. It runs a local HTTP server on
|
||||
// 127.0.0.1:8765 that proxies the VK CAPTCHA page (rewriting absolute
|
||||
// URLs and gzipping), opens it in the user's browser, and waits for the
|
||||
// token/key produced after the user completes the puzzle.
|
||||
// Package manual реализует ручное решение CAPTCHA — fallback, когда автосолвер
|
||||
// (internal/client/captcha) не справился или пользователь дал -manual-captcha.
|
||||
// Поднимает локальный HTTP-сервер 127.0.0.1:8765, проксирующий страницу VK
|
||||
// CAPTCHA (с переписыванием абсолютных URL и gzip), открывает её в браузере и
|
||||
// ждёт токен/ключ после решения пользователем.
|
||||
package manual
|
||||
|
||||
import (
|
||||
@@ -29,15 +28,15 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/logx"
|
||||
)
|
||||
|
||||
// Debug toggles verbose request/response logging for the proxied browser
|
||||
// traffic. Set from main once cfg is parsed.
|
||||
// Debug включает подробное логирование request/response проксируемого
|
||||
// браузерного трафика. Ставится из main после разбора cfg.
|
||||
var Debug bool
|
||||
|
||||
// Log is the package-level logger; defaults to no-op. main wires it via
|
||||
// SetLogger so manual-captcha output respects -debug and levels.
|
||||
// Log — пакетный логгер; по умолчанию no-op. main устанавливает его через
|
||||
// SetLogger, чтобы вывод подчинялся -debug.
|
||||
var Log logx.Logger = logx.Nop()
|
||||
|
||||
// SetLogger installs a logger for this package.
|
||||
// SetLogger ставит логгер пакета.
|
||||
func SetLogger(l logx.Logger) { Log = logx.OrNop(l) }
|
||||
|
||||
const captchaListenPort = "8765"
|
||||
@@ -144,7 +143,7 @@ func rewriteProxyRequest(req *http.Request, targetURL *neturl.URL) {
|
||||
req.Host = targetURL.Host
|
||||
|
||||
req.Header.Del("Accept-Encoding")
|
||||
req.Header.Del("TE") // Disable transfer encoding compression
|
||||
req.Header.Del("TE") // отключить transfer encoding compression
|
||||
for _, h := range []string{
|
||||
"X-Requested-With",
|
||||
"X-Android-Package",
|
||||
@@ -196,28 +195,21 @@ func rewriteProxyCookies(header http.Header) {
|
||||
}
|
||||
}
|
||||
|
||||
// htmlURLAttrDoubleRe matches src/href/action attributes with double-quoted absolute or protocol-relative URLs.
|
||||
var htmlURLAttrDoubleRe = regexp.MustCompile(`(?i)((?:src|href|action)\s*=\s*)"((?:https?:)?//[^"]+)"`)
|
||||
|
||||
// htmlURLAttrSingleRe matches src/href/action attributes with single-quoted absolute or protocol-relative URLs.
|
||||
var htmlURLAttrSingleRe = regexp.MustCompile(`(?i)((?:src|href|action)\s*=\s*)'((?:https?:)?//[^']+)'`)
|
||||
|
||||
// htmlScriptContentRe matches <script> tags to extract their content.
|
||||
var htmlScriptContentRe = regexp.MustCompile(`(?is)(<script[^>]*>)(.*?)(</script>)`)
|
||||
|
||||
// htmlStyleContentRe matches <style> tags to extract their content.
|
||||
var htmlStyleContentRe = regexp.MustCompile(`(?is)(<style[^>]*>)(.*?)(</style>)`)
|
||||
|
||||
// rewriteHTMLAttrsServerSide rewrites absolute and protocol-relative URLs in src/href/action
|
||||
// attributes of raw HTML. URLs matching the upstream origin are redirected to localhost;
|
||||
// all other absolute URLs are routed through /generic_proxy so that cross-domain resources
|
||||
// (st.vk.com, userapi.com, etc.) load correctly through the proxy.
|
||||
// rewriteHTMLAttrsServerSide переписывает абсолютные и protocol-relative URL
|
||||
// в src/href/action HTML на стороне сервера. URL, совпадающие с upstream origin,
|
||||
// идут на localhost; остальные — через /generic_proxy, чтобы cross-domain
|
||||
// ресурсы (st.vk.com, userapi.com и т.д.) грузились через прокси.
|
||||
func rewriteHTMLAttrsServerSide(html string, targetURL *neturl.URL) string {
|
||||
localOrigin := localCaptchaOrigin()
|
||||
upstreamOrigin := targetOrigin(targetURL)
|
||||
|
||||
rewriteURL := func(rawURL string) string {
|
||||
// Normalise protocol-relative URL to absolute using the upstream scheme
|
||||
// нормализовать protocol-relative URL в абсолютный по upstream scheme
|
||||
absURL := rawURL
|
||||
if strings.HasPrefix(rawURL, "//") {
|
||||
absURL = targetURL.Scheme + ":" + rawURL
|
||||
@@ -225,11 +217,10 @@ func rewriteHTMLAttrsServerSide(html string, targetURL *neturl.URL) string {
|
||||
if strings.HasPrefix(absURL, upstreamOrigin) {
|
||||
return localOrigin + absURL[len(upstreamOrigin):]
|
||||
}
|
||||
// Already points to local proxy — leave as-is
|
||||
if strings.HasPrefix(absURL, localOrigin) {
|
||||
return rawURL
|
||||
}
|
||||
// Any other absolute URL → route through generic_proxy
|
||||
// прочие абсолютные URL → через generic_proxy
|
||||
return "/generic_proxy?proxy_url=" + neturl.QueryEscape(absURL)
|
||||
}
|
||||
|
||||
@@ -282,12 +273,12 @@ func rewriteCaptchaHTML(html string, targetURL *neturl.URL) string {
|
||||
localOrigin := localCaptchaOrigin()
|
||||
upstreamOrigin := targetOrigin(targetURL)
|
||||
|
||||
// Step 1: plain text replacement for the primary upstream origin
|
||||
// Шаг 1: текстовая замена основного upstream origin
|
||||
html = strings.ReplaceAll(html, upstreamOrigin, localOrigin)
|
||||
|
||||
// Step 2: rewrite all other absolute URLs in HTML attributes server-side.
|
||||
// This is critical: the browser begins downloading <script src> / <link href> / <img src>
|
||||
// resources immediately as it parses HTML — before any injected JS can intercept them.
|
||||
// Шаг 2: серверный rewrite остальных абсолютных URL в HTML-атрибутах.
|
||||
// Критично: браузер начинает грузить <script src> / <link href> / <img src>
|
||||
// сразу при парсинге HTML — раньше любых инжектированных JS-перехватов.
|
||||
html = rewriteHTMLAttrsServerSide(html, targetURL)
|
||||
|
||||
script := fmt.Sprintf(`
|
||||
@@ -484,8 +475,8 @@ func rewriteCaptchaHTML(html string, targetURL *neturl.URL) string {
|
||||
</script>
|
||||
`, localOrigin, upstreamOrigin)
|
||||
|
||||
// Step 3: inject the client-side script as early as possible — at the opening <head> tag
|
||||
// so that XHR/fetch overrides are active before any inline <script> block in <head> runs.
|
||||
// Шаг 3: инжектируем клиентский скрипт как можно раньше — после <head>,
|
||||
// чтобы XHR/fetch-перехваты были активны до любого inline <script> в <head>.
|
||||
switch {
|
||||
case strings.Contains(html, "<head>"):
|
||||
return strings.Replace(html, "<head>", "<head>"+script, 1)
|
||||
@@ -540,8 +531,8 @@ func startCaptchaServer(srv *http.Server, logPrefix string) error {
|
||||
return fmt.Errorf("captcha listeners failed: %s", strings.Join(listenErrs, "; "))
|
||||
}
|
||||
|
||||
// runCaptchaServerAndWait triggers the browser, and waiting gracefully for the solution token.
|
||||
// Returns ctx.Err() if ctx fires before a key arrives; in both cases the HTTP server is shut down.
|
||||
// runCaptchaServerAndWait открывает браузер и ждёт токен решения.
|
||||
// При срабатывании ctx возвращает ctx.Err(); в обоих случаях HTTP-сервер останавливается.
|
||||
func runCaptchaServerAndWait(ctx context.Context, handler http.Handler, captchaURL string, keyCh <-chan string, logPrefix string) (string, error) {
|
||||
srv := &http.Server{Handler: handler}
|
||||
|
||||
@@ -550,8 +541,8 @@ func runCaptchaServerAndWait(ctx context.Context, handler http.Handler, captchaU
|
||||
}
|
||||
|
||||
defer func() {
|
||||
// Best-effort shutdown. On iSH SetDeadline is a no-op and Shutdown may
|
||||
// time out while listeners drain; we still propagate the result.
|
||||
// best-effort shutdown. На iSH SetDeadline — no-op, Shutdown может
|
||||
// таймаутить при сливе listener'ов; результат всё равно прокидываем.
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer shutCancel()
|
||||
if err := srv.Shutdown(shutCtx); err != nil {
|
||||
@@ -577,7 +568,7 @@ func runCaptchaServerAndWait(ctx context.Context, handler http.Handler, captchaU
|
||||
}
|
||||
}
|
||||
|
||||
// notifyKey pushes the key string to the given channel without blocking
|
||||
// notifyKey пушит ключ в канал без блокировки.
|
||||
func notifyKey(keyCh chan<- string, key string) {
|
||||
if key != "" {
|
||||
select {
|
||||
@@ -587,9 +578,8 @@ func notifyKey(keyCh chan<- string, key string) {
|
||||
}
|
||||
}
|
||||
|
||||
// SolveViaHTTP serves a tiny HTML page asking the user to solve the
|
||||
// pictured CAPTCHA, opens it in the browser, and blocks until the key
|
||||
// is posted back.
|
||||
// SolveViaHTTP отдаёт минимальную HTML-страницу для решения картинки CAPTCHA,
|
||||
// открывает её в браузере и блокируется до прихода ключа.
|
||||
func SolveViaHTTP(ctx context.Context, captchaImg string) (string, error) {
|
||||
keyCh := make(chan string, 1)
|
||||
mux := http.NewServeMux()
|
||||
@@ -651,7 +641,7 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
|
||||
device := parsedBody.Get("device")
|
||||
browserFp := parsedBody.Get("browser_fp")
|
||||
|
||||
// We only save it if device is present. componentDone usually has it.
|
||||
// сохраняем только если есть device. componentDone обычно его содержит.
|
||||
if device != "" && browserFp != "" {
|
||||
sp := browserprofile.Saved{
|
||||
Profile: browserprofile.Profile{
|
||||
@@ -674,10 +664,9 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
|
||||
return t.rt.RoundTrip(req)
|
||||
}
|
||||
|
||||
// SolveViaProxy proxies the VK redirect_uri page through a local HTTP
|
||||
// server, rewriting absolute URLs so the browser stays on
|
||||
// 127.0.0.1:8765 throughout the puzzle, then returns the resulting
|
||||
// auth token.
|
||||
// SolveViaProxy проксирует VK redirect_uri через локальный HTTP-сервер,
|
||||
// переписывая абсолютные URL так, чтобы браузер всё время оставался на
|
||||
// 127.0.0.1:8765; возвращает результирующий auth-токен.
|
||||
func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (string, error) {
|
||||
keyCh := make(chan string, 1)
|
||||
|
||||
@@ -704,7 +693,7 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
|
||||
if res.StatusCode >= 300 && res.StatusCode < 400 {
|
||||
if loc := res.Header.Get("Location"); loc != "" {
|
||||
// Don't log the full redirect URL to keep console clean
|
||||
// не логируем полный redirect URL — шум в консоли
|
||||
if rewritten, ok := rewriteProxyRedirectLocation(loc, targetURL); ok {
|
||||
res.Header.Set("Location", rewritten)
|
||||
} else {
|
||||
@@ -809,8 +798,8 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
rewriteProxyRequest(req.Out, targetParsed)
|
||||
},
|
||||
ModifyResponse: func(res *http.Response) error {
|
||||
// Strip security headers that can block cross-origin resource loading
|
||||
// when static assets (JS/CSS) are served through the proxy.
|
||||
// убираем security-заголовки, блокирующие cross-origin загрузку
|
||||
// статики (JS/CSS) при проксировании.
|
||||
for _, h := range []string{
|
||||
"Content-Security-Policy",
|
||||
"Content-Security-Policy-Report-Only",
|
||||
@@ -824,13 +813,13 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
} {
|
||||
res.Header.Del(h)
|
||||
}
|
||||
// Allow the browser to use the resource cross-origin
|
||||
// разрешаем cross-origin доступ к ресурсу
|
||||
res.Header.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// captchaNotRobot.check goes to api.vk.ru (different host from the main
|
||||
// proxy upstream vk.com), so it is routed through /generic_proxy.
|
||||
// Extract the success_token here so the server path works on iOS
|
||||
// even if the browser-side JS callback never fires.
|
||||
// captchaNotRobot.check уходит на api.vk.ru (другой хост, чем
|
||||
// upstream vk.com), поэтому идёт через /generic_proxy. Извлекаем
|
||||
// success_token здесь — серверный путь работает на iOS даже если
|
||||
// JS-callback в браузере не сработал.
|
||||
if strings.Contains(targetAuthURL, "captchaNotRobot.check") {
|
||||
bodyBytes, readErr := io.ReadAll(res.Body)
|
||||
if readErr == nil {
|
||||
@@ -851,7 +840,7 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
Log.Debugf("[Captcha Proxy] HTTP %s %s", r.Method, r.URL.Path)
|
||||
if r.URL.Path == "/" && targetURL.Path != "" && targetURL.Path != "/" && r.URL.RawQuery == "" {
|
||||
// Don't log the full redirect URL to keep console clean
|
||||
// не логируем полный redirect URL — шум в консоли
|
||||
http.Redirect(w, r, localCaptchaURLForTarget(targetURL), http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
@@ -872,11 +861,11 @@ func openBrowser(url string) {
|
||||
func browserOpenCommands(goos string, url string) []browserCommand {
|
||||
switch goos {
|
||||
case "windows":
|
||||
// 'rundll32 url.dll,FileProtocolHandler' is more reliable than 'cmd /c start'
|
||||
// because it doesn't involve the shell (cmd.exe), avoiding issues with '&' and other special characters.
|
||||
// 'rundll32 url.dll,FileProtocolHandler' надёжнее 'cmd /c start' —
|
||||
// не задействует shell (cmd.exe), нет проблем с '&' и спец-символами.
|
||||
return []browserCommand{
|
||||
{name: "rundll32", args: []string{"url.dll,FileProtocolHandler", url}},
|
||||
// Fallback with empty title argument for 'start' to handle potential quoting issues
|
||||
// fallback с пустым title для 'start' — обход проблем с кавычками
|
||||
{name: "cmd", args: []string{"/c", "start", "", url}},
|
||||
}
|
||||
case "darwin":
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
_ "image/jpeg" // register JPEG decoder for image.Decode
|
||||
_ "image/jpeg" // регистрация JPEG-декодера для image.Decode
|
||||
"math"
|
||||
mathrand "math/rand"
|
||||
"runtime"
|
||||
|
||||
@@ -17,15 +17,15 @@ func sharedDohResolver() *DohResolver {
|
||||
return dohResolverInstance
|
||||
}
|
||||
|
||||
// AppDialer returns the net.Dialer used by tls-client and other HTTP callers.
|
||||
// DNS transport is selected by mode (udp | doh | auto).
|
||||
// AppDialer возвращает net.Dialer для tls-client и других HTTP-вызывающих.
|
||||
// DNS-транспорт выбирается по mode (udp | doh | auto).
|
||||
func AppDialer(mode string) net.Dialer {
|
||||
return buildDialer(mode, sharedDohResolver())
|
||||
}
|
||||
|
||||
// InstallGlobalResolver wires net.DefaultResolver to the same DNS transport
|
||||
// as AppDialer, so third-party libs that build their own http.Client without
|
||||
// our Dialer still use DoH / auto-fallback instead of the OS resolver.
|
||||
// InstallGlobalResolver выставляет net.DefaultResolver на тот же DNS-транспорт,
|
||||
// что и AppDialer — чтобы сторонние библиотеки, собирающие свой http.Client
|
||||
// без нашего Dialer, тоже шли через DoH / auto-fallback, а не OS resolver.
|
||||
func InstallGlobalResolver(mode string) {
|
||||
d := AppDialer(mode)
|
||||
if d.Resolver != nil {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package dnsdial owns DNS resolution and the net.Dialer wired into all
|
||||
// outbound HTTP/TLS clients. Selects between UDP/53, DNS-over-HTTPS, or
|
||||
// auto (UDP probe → sticky DoH fallback) based on Mode.
|
||||
// Package dnsdial владеет DNS-резолвингом и net.Dialer'ом, прокинутым во все
|
||||
// outbound HTTP/TLS клиенты. По Mode выбирает UDP/53, DNS-over-HTTPS или auto
|
||||
// (UDP-probe → sticky DoH fallback).
|
||||
package dnsdial
|
||||
|
||||
import (
|
||||
@@ -21,21 +21,20 @@ import (
|
||||
|
||||
"github.com/samosvalishe/btp/internal/logx"
|
||||
|
||||
// Embedded Mozilla CA roots for CGO_ENABLED=0 builds (Android).
|
||||
// встроенные Mozilla CA roots для CGO_ENABLED=0 сборок (Android).
|
||||
_ "golang.org/x/crypto/x509roots/fallback"
|
||||
)
|
||||
|
||||
// Log is the package-level logger. Defaults to no-op; main wires it via
|
||||
// SetLogger so DNS-mode output respects the global -debug flag and levels.
|
||||
// Log — пакетный логгер. По умолчанию no-op; main устанавливает через SetLogger.
|
||||
var Log logx.Logger = logx.Nop()
|
||||
|
||||
// SetLogger installs a logger for this package.
|
||||
// SetLogger ставит логгер пакета.
|
||||
func SetLogger(l logx.Logger) { Log = logx.OrNop(l) }
|
||||
|
||||
const (
|
||||
dohQueryTimeout = 6 * time.Second
|
||||
// Total budget across all endpoint attempts in forwardRaw. Must be a
|
||||
// multiple of dohQueryTimeout to give every fallback a real chance.
|
||||
// общий бюджет для всех попыток endpoint'ов в forwardRaw. Кратно
|
||||
// dohQueryTimeout — чтобы каждому fallback хватило времени.
|
||||
dohForwardBudget = 25 * time.Second
|
||||
dohMaxResponseBytes = 64 * 1024
|
||||
dohContentType = "application/dns-message"
|
||||
@@ -51,33 +50,31 @@ const (
|
||||
autoUDPBudget = 1500 * time.Millisecond
|
||||
)
|
||||
|
||||
// DohEndpoint describes a single DNS-over-HTTPS server together with the IPs
|
||||
// we bootstrap to — so that resolving the endpoint hostname does not itself
|
||||
// require DNS.
|
||||
// DohEndpoint — один DNS-over-HTTPS сервер с bootstrap-IP, чтобы резолв самого
|
||||
// hostname не требовал DNS.
|
||||
type DohEndpoint struct {
|
||||
URL string
|
||||
Hostname string
|
||||
BootstrapIPs []string
|
||||
}
|
||||
|
||||
// Yandex is tried first because it tends to stay reachable on RU mobile
|
||||
// operators even when international resolvers get blocked; Google and
|
||||
// Cloudflare follow as fallbacks.
|
||||
// Yandex — первый, т.к. остаётся доступен у RU мобильных операторов даже когда
|
||||
// международные резолверы блокируются; Google и Cloudflare — fallback.
|
||||
var defaultDohEndpoints = []DohEndpoint{
|
||||
{"https://common.dot.dns.yandex.net/dns-query", "common.dot.dns.yandex.net", []string{"77.88.8.8", "77.88.8.1"}},
|
||||
{"https://secure.dot.dns.yandex.net/dns-query", "secure.dot.dns.yandex.net", []string{"77.88.8.88", "77.88.8.2"}},
|
||||
{"https://family.dot.dns.yandex.net/dns-query", "family.dot.dns.yandex.net", []string{"77.88.8.7", "77.88.8.3"}},
|
||||
}
|
||||
|
||||
// DohResolver POSTs DNS wire queries to one of several DoH endpoints.
|
||||
// DohResolver делает POST с DNS-wire запросом к одному из DoH endpoint'ов.
|
||||
type DohResolver struct {
|
||||
endpoints []DohEndpoint
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewDohResolver constructs a resolver using defaultDohEndpoints if endpoints
|
||||
// is nil. Endpoint hostnames are dialed by IP using BootstrapIPs, so the DoH
|
||||
// transport never depends on the system resolver.
|
||||
// NewDohResolver конструирует резолвер; если endpoints=nil, берёт
|
||||
// defaultDohEndpoints. Имена endpoint'ов диалятся по BootstrapIPs — DoH-транспорт
|
||||
// не зависит от системного резолвера.
|
||||
func NewDohResolver(endpoints []DohEndpoint) *DohResolver {
|
||||
if len(endpoints) == 0 {
|
||||
endpoints = defaultDohEndpoints
|
||||
@@ -88,14 +85,13 @@ func NewDohResolver(endpoints []DohEndpoint) *DohResolver {
|
||||
}
|
||||
}
|
||||
|
||||
// newDohResolverWithClient is a test hook that skips the bootstrap transport.
|
||||
// newDohResolverWithClient — тестовый hook, минующий bootstrap-транспорт.
|
||||
func newDohResolverWithClient(endpoints []DohEndpoint, client *http.Client) *DohResolver {
|
||||
return &DohResolver{endpoints: endpoints, client: client}
|
||||
}
|
||||
|
||||
// newBootstrapTransport returns an http.Transport whose DialContext only
|
||||
// knows how to reach the configured DoH endpoint hostnames, by mapping each
|
||||
// to its BootstrapIPs.
|
||||
// newBootstrapTransport возвращает http.Transport, чей DialContext знает только
|
||||
// заданные hostname'ы DoH endpoint'ов и резолвит их в BootstrapIPs.
|
||||
func newBootstrapTransport(endpoints []DohEndpoint) *http.Transport {
|
||||
bootstrap := make(map[string][]string, len(endpoints))
|
||||
for _, ep := range endpoints {
|
||||
@@ -128,9 +124,9 @@ func newBootstrapTransport(endpoints []DohEndpoint) *http.Transport {
|
||||
}
|
||||
return nil, lastErr
|
||||
},
|
||||
// Explicit DialTLSContext ensures SNI = endpoint hostname even when
|
||||
// the underlying TCP dial targets a bootstrap IP. Without this, some
|
||||
// HTTP/2 paths can leak the literal IP as ServerName and fail TLS.
|
||||
// явный DialTLSContext гарантирует SNI = hostname, даже если TCP-dial
|
||||
// идёт на bootstrap-IP. Без этого некоторые HTTP/2 пути сливают
|
||||
// литерал IP как ServerName и TLS падает.
|
||||
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
@@ -164,15 +160,14 @@ func newBootstrapTransport(endpoints []DohEndpoint) *http.Transport {
|
||||
}
|
||||
}
|
||||
|
||||
// forwardRaw POSTs an opaque DNS-wire query to the configured DoH endpoints
|
||||
// in order and returns the first successful raw response together with the
|
||||
// endpoint that produced it. No parsing — useful for the local forwarder
|
||||
// which needs to pass through whatever the upstream resolver answers
|
||||
// (RESINFO/HTTPS/SVCB/EDNS options/…).
|
||||
// forwardRaw делает POST opaque DNS-wire запроса к настроенным DoH endpoint'ам
|
||||
// по порядку и возвращает первый успешный raw-ответ вместе с endpoint'ом.
|
||||
// Без парсинга — удобно для локального форвардера, который пропускает что бы
|
||||
// upstream ни ответил (RESINFO/HTTPS/SVCB/EDNS options/…).
|
||||
//
|
||||
// Each endpoint gets its own per-attempt deadline (dohQueryTimeout) so a
|
||||
// slow first endpoint does not consume the entire budget and starve the
|
||||
// fallbacks. The parent ctx still bounds the total wait via cancel chain.
|
||||
// Каждому endpoint'у — свой per-attempt deadline (dohQueryTimeout), чтобы
|
||||
// медленный первый не сожрал весь бюджет и не зарезал fallback'и. Parent ctx
|
||||
// всё ещё ограничивает общее ожидание через cancel chain.
|
||||
func (r *DohResolver) forwardRaw(ctx context.Context, query []byte) ([]byte, DohEndpoint, error) {
|
||||
if len(r.endpoints) == 0 {
|
||||
return nil, DohEndpoint{}, errors.New("doh: no endpoints configured")
|
||||
@@ -195,7 +190,7 @@ func (r *DohResolver) forwardRaw(ctx context.Context, query []byte) ([]byte, Doh
|
||||
return nil, DohEndpoint{}, lastErr
|
||||
}
|
||||
|
||||
// postWire performs a single application/dns-message POST to one endpoint.
|
||||
// postWire делает один application/dns-message POST к одному endpoint'у.
|
||||
func (r *DohResolver) postWire(ctx context.Context, ep DohEndpoint, query []byte) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", ep.URL, bytes.NewReader(query))
|
||||
if err != nil {
|
||||
@@ -221,10 +216,10 @@ func (r *DohResolver) postWire(ctx context.Context, ep DohEndpoint, query []byte
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// Go's net.Resolver dials this stub like a regular nameserver, which avoids
|
||||
// the many edge cases of a fake-net.Conn approach (RESINFO probes, EDNS
|
||||
// handshakes, truncation, …). Whatever it reads on UDP/TCP is sent verbatim
|
||||
// to a DoH endpoint and the wire response is sent back to the client.
|
||||
// net.Resolver Go дозванивается до этого stub'а как до обычного nameserver'а —
|
||||
// обходит уйму edge-case'ов fake-net.Conn (RESINFO probes, EDNS handshakes,
|
||||
// truncation, …). Что бы он ни прочитал на UDP/TCP — уходит дословно в DoH
|
||||
// endpoint, ответ отдаётся клиенту.
|
||||
|
||||
type dohForwarder struct {
|
||||
udpAddr string
|
||||
@@ -237,9 +232,9 @@ var (
|
||||
dohForwarderErr error
|
||||
)
|
||||
|
||||
// sharedDohForwarder lazily starts a process-wide forwarder bound to the
|
||||
// supplied resolver. The first caller wins; subsequent callers reuse the
|
||||
// same forwarder regardless of what they pass in.
|
||||
// sharedDohForwarder лениво запускает process-wide форвардер, привязанный к
|
||||
// заданному resolver. Побеждает первый caller; следующие переиспользуют тот же
|
||||
// форвардер независимо от того, что передали.
|
||||
func sharedDohForwarder(r *DohResolver) (*dohForwarder, error) {
|
||||
dohForwarderOnce.Do(func() {
|
||||
dohForwarderInst, dohForwarderErr = startDohForwarder(r)
|
||||
@@ -350,8 +345,8 @@ func handleDohForwarderTCP(conn net.Conn, r *DohResolver) {
|
||||
}
|
||||
}
|
||||
|
||||
// dohForwarderDial returns a Resolver.Dial that connects to the local DoH
|
||||
// forwarder over UDP or TCP (whichever the resolver asked for).
|
||||
// dohForwarderDial возвращает Resolver.Dial, подключающийся к локальному DoH
|
||||
// форвардеру по UDP или TCP (что запросил резолвер).
|
||||
func dohForwarderDial(r *DohResolver) dialFunc {
|
||||
return func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||
fwd, err := sharedDohForwarder(r)
|
||||
@@ -387,13 +382,13 @@ func init() {
|
||||
|
||||
func udpDNSServers() []string { return *udpDNSServersPtr.Load() }
|
||||
|
||||
// SetUDPDNSServers replaces the default UDP/53 server list. Each entry may be
|
||||
// "ip" or "ip:port" — bare IPs get :53 appended. Empty list keeps the defaults.
|
||||
// Used on Android to inject the carrier's resolver IPs from
|
||||
// LinkProperties.dnsServers, which often work where public DoH/DoT do not.
|
||||
// SetUDPDNSServers заменяет дефолтный список UDP/53 серверов. Каждый элемент —
|
||||
// "ip" или "ip:port"; голые IP получают :53. Пустой список оставляет дефолт.
|
||||
// На Android используется для подсовывания резолверов оператора из
|
||||
// LinkProperties.dnsServers — часто работают там, где публичный DoH/DoT нет.
|
||||
//
|
||||
// Safe to call concurrently with resolver use — the list pointer is swapped
|
||||
// atomically. Existing in-flight dials see whichever snapshot they captured.
|
||||
// Безопасно вызывать конкурентно с использованием резолвера — указатель списка
|
||||
// меняется атомарно. Уже идущие dial видят свой захваченный снимок.
|
||||
func SetUDPDNSServers(servers []string) {
|
||||
if len(servers) == 0 {
|
||||
return
|
||||
@@ -417,9 +412,9 @@ func SetUDPDNSServers(servers []string) {
|
||||
|
||||
type dialFunc = func(context.Context, string, string) (net.Conn, error)
|
||||
|
||||
// buildDialer returns a net.Dialer whose internal Go resolver uses the
|
||||
// chosen DNS transport. In "auto" mode the first total-failure of UDP/53
|
||||
// sticks the process onto DoH for the rest of its lifetime.
|
||||
// buildDialer возвращает net.Dialer, чей внутренний Go-резолвер использует
|
||||
// выбранный DNS-транспорт. В режиме "auto" первый полный отказ UDP/53
|
||||
// залипает процесс на DoH до конца его жизни.
|
||||
func buildDialer(mode string, r *DohResolver) net.Dialer {
|
||||
switch mode {
|
||||
case DNSModeUDP:
|
||||
@@ -433,8 +428,8 @@ func buildDialer(mode string, r *DohResolver) net.Dialer {
|
||||
}
|
||||
}
|
||||
|
||||
// newAppDialer wraps a Resolver.Dial with the timeouts used everywhere in
|
||||
// the app for outbound TCP/HTTP connections.
|
||||
// newAppDialer оборачивает Resolver.Dial таймаутами, используемыми везде в
|
||||
// приложении для outbound TCP/HTTP.
|
||||
func newAppDialer(dial dialFunc) net.Dialer {
|
||||
return net.Dialer{
|
||||
Timeout: appDialerTimeout,
|
||||
@@ -443,7 +438,7 @@ func newAppDialer(dial dialFunc) net.Dialer {
|
||||
}
|
||||
}
|
||||
|
||||
// udpDNSDial picks the first reachable UDP/53 resolver from udpDNSServers.
|
||||
// udpDNSDial берёт первый достижимый UDP/53 резолвер из udpDNSServers.
|
||||
func udpDNSDial(ctx context.Context, _ string, _ string) (net.Conn, error) {
|
||||
var (
|
||||
d net.Dialer
|
||||
@@ -462,14 +457,12 @@ func udpDNSDial(ctx context.Context, _ string, _ string) (net.Conn, error) {
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// autoDial returns a Dial that probes UDP/53 once with a real DNS round-trip;
|
||||
// if the probe fails it latches onto DoH for the rest of the process. Built
|
||||
// for Android, where the network can flip between Wi-Fi (UDP/53 works) and
|
||||
// mobile (UDP/53 blocked).
|
||||
// autoDial возвращает Dial, который один раз пробит UDP/53 реальным DNS
|
||||
// round-trip'ом; при провале залипает на DoH до конца процесса. Сделано под
|
||||
// Android, где сеть скачет между Wi-Fi (UDP/53 работает) и мобилкой (блок).
|
||||
//
|
||||
// A simple dial-timeout doesn't work for UDP because UDP "dial" is
|
||||
// connectionless and always succeeds instantly. The only way to know whether
|
||||
// UDP/53 actually works is to send a real query and wait for a response.
|
||||
// Просто dial-timeout не годится: UDP "dial" безсоединительный и всегда успешен
|
||||
// мгновенно. Единственный способ узнать — реально отправить запрос и ждать ответ.
|
||||
func autoDial(r *DohResolver) dialFunc {
|
||||
var (
|
||||
probed sync.Once
|
||||
@@ -492,10 +485,9 @@ func autoDial(r *DohResolver) dialFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// udpProbe sends a real DNS A query for a well-known domain via UDP and
|
||||
// checks whether any response arrives within the deadline. We try the first
|
||||
// two servers from udpDNSServers under a shared deadline — if neither
|
||||
// responds, UDP/53 is blocked.
|
||||
// udpProbe шлёт реальный DNS A-запрос к known-домену по UDP и проверяет, придёт
|
||||
// ли ответ до дедлайна. Пробуем первые два сервера из udpDNSServers под общим
|
||||
// deadline — если ни один не ответил, UDP/53 заблокирован.
|
||||
func udpProbe(timeout time.Duration) bool {
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion("dns.google.", dns.TypeA)
|
||||
|
||||
@@ -17,8 +17,8 @@ type listener struct {
|
||||
fd int
|
||||
}
|
||||
|
||||
// WrapListener overrides the standard net.Listener with a legacy syscall listener
|
||||
// designed specifically for the iSH simulator on iOS, which lacks modern `accept4`.
|
||||
// WrapListener подменяет стандартный net.Listener на legacy-syscall listener,
|
||||
// заточенный под iSH-симулятор на iOS, где нет современного `accept4`.
|
||||
func WrapListener(ln net.Listener) (net.Listener, error) {
|
||||
tl, ok := ln.(*net.TCPListener)
|
||||
if !ok {
|
||||
@@ -29,13 +29,14 @@ func WrapListener(ln net.Listener) (net.Listener, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Keep a reference to *os.File so the garbage collector doesn't close the FD.
|
||||
// держим ссылку на *os.File, чтобы GC не закрыл FD.
|
||||
return &listener{Listener: ln, f: f, fd: int(f.Fd())}, nil
|
||||
}
|
||||
|
||||
func (l *listener) Accept() (net.Conn, error) {
|
||||
// Set the listener socket to blocking mode. Go makes it non-blocking by default.
|
||||
// This avoids using time.Sleep in a spin-loop, which triggers futex_time64 SIGSYS in modern Go on iSH.
|
||||
// ставим listener-сокет в blocking. Go по умолчанию делает его non-blocking.
|
||||
// Это избавляет от time.Sleep в spin-loop, который триггерит futex_time64 SIGSYS
|
||||
// в современном Go на iSH.
|
||||
if err := syscall.SetNonblock(l.fd, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -44,11 +45,11 @@ func (l *listener) Accept() (net.Conn, error) {
|
||||
addr := make([]byte, 128)
|
||||
addrlen := uintptr(128)
|
||||
|
||||
// i386 network syscalls are multiplexed via socketcall (102).
|
||||
// SYS_ACCEPT is subcall 5.
|
||||
// i386 сетевые syscall'ы мультиплексируются через socketcall (102).
|
||||
// SYS_ACCEPT — subcall 5.
|
||||
args := [3]uintptr{uintptr(l.fd), uintptr(unsafe.Pointer(&addr[0])), uintptr(unsafe.Pointer(&addrlen))}
|
||||
|
||||
// Use Syscall6 to ensure we have enough arguments registers for the platform.
|
||||
// Syscall6 — чтобы хватило регистров аргументов на этой платформе.
|
||||
r1, _, errno := syscall.Syscall6(102, 5, uintptr(unsafe.Pointer(&args)), 0, 0, 0, 0)
|
||||
if errno != 0 {
|
||||
if errno == syscall.EINTR {
|
||||
@@ -62,16 +63,15 @@ func (l *listener) Accept() (net.Conn, error) {
|
||||
_ = syscall.SetsockoptInt(nfd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 256*1024)
|
||||
_ = syscall.SetsockoptInt(nfd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, 256*1024)
|
||||
|
||||
// We avoid Go's net.FileConn because it tries to register the fd with Go's epoll poller,
|
||||
// which in iSH emulator consistency fails with EEXIST (file exists).
|
||||
// Instead, we return a custom blocking net.Conn wrapper.
|
||||
// избегаем net.FileConn — она регистрирует fd в Go epoll poller'е, что в
|
||||
// iSH стабильно падает с EEXIST. Возвращаем кастомный blocking net.Conn.
|
||||
conn := &ishConn{fd: nfd}
|
||||
return conn, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (l *listener) Close() error {
|
||||
// Close both the duplicated FD and the original listener.
|
||||
// закрываем и дублированный FD, и оригинальный listener.
|
||||
err1 := l.f.Close()
|
||||
err2 := l.Listener.Close()
|
||||
if err1 != nil {
|
||||
@@ -80,7 +80,7 @@ func (l *listener) Close() error {
|
||||
return err2
|
||||
}
|
||||
|
||||
// ishConn bypasses Go's network poller to prevent EEXIST bugs in iSH
|
||||
// ishConn обходит сетевой poller Go, чтобы не словить EEXIST в iSH.
|
||||
type ishConn struct {
|
||||
fd int
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
//go:build !(linux && 386)
|
||||
|
||||
// Package ish provides a TCP listener shim for iSH (https://ish.app), a
|
||||
// Linux user-mode emulator that runs on iOS. iSH targets linux/386 and lacks
|
||||
// modern accept4 / Go's epoll-based poller, so a sandbox-aware accept loop
|
||||
// is needed there. On every other GOOS/GOARCH WrapListener is a no-op
|
||||
// pass-through.
|
||||
// Package ish — TCP listener shim для iSH (https://ish.app), Linux user-mode
|
||||
// эмулятор на iOS. iSH таргетит linux/386 и не имеет современного accept4 /
|
||||
// epoll-poller Go, поэтому там нужен sandbox-aware accept loop. На любом
|
||||
// другом GOOS/GOARCH WrapListener — no-op passthrough.
|
||||
package ish
|
||||
|
||||
import "net"
|
||||
|
||||
// WrapListener returns ln unchanged on non-iSH platforms.
|
||||
// WrapListener возвращает ln без изменений на не-iSH платформах.
|
||||
func WrapListener(ln net.Listener) (net.Listener, error) {
|
||||
return ln, nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package namegen produces random Russian-style display names for
|
||||
// client identities. Name pools are embedded from data/*.txt.
|
||||
// Package namegen генерирует случайные русскоязычные display name'ы для
|
||||
// идентичностей клиента. Пулы имён встроены из data/*.txt.
|
||||
package namegen
|
||||
|
||||
import (
|
||||
@@ -35,10 +35,10 @@ func parseLines(s string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// feminizeSurname converts a Russian male surname to its female form.
|
||||
// Operates on runes since Cyrillic letters are multibyte in UTF-8.
|
||||
// Surnames whose suffixes do not match Russian patterns are returned
|
||||
// unchanged (covers foreign / meme surnames).
|
||||
// feminizeSurname переводит мужскую фамилию в женскую форму.
|
||||
// Работает по рунам — кириллица многобайтовая в UTF-8.
|
||||
// Фамилии с не-русскими суффиксами возвращаются без изменений
|
||||
// (иностранные / мемные).
|
||||
func feminizeSurname(surname string) string {
|
||||
rs := []rune(surname)
|
||||
n := len(rs)
|
||||
@@ -54,11 +54,11 @@ func feminizeSurname(surname string) string {
|
||||
return surname
|
||||
}
|
||||
|
||||
// SurnameProbability is the chance that Generate returns a name with a surname.
|
||||
// SurnameProbability — вероятность того, что Generate вернёт имя с фамилией.
|
||||
const SurnameProbability = 0.7
|
||||
|
||||
// Generate returns a random "FirstName" or "FirstName LastName".
|
||||
// Gender is chosen uniformly; surnames are feminized for female names.
|
||||
// Generate возвращает случайное "Имя" или "Имя Фамилия".
|
||||
// Пол выбирается равномерно; женские фамилии феминизируются.
|
||||
func Generate() string {
|
||||
isFemale := rand.IntN(2) == 0
|
||||
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
)
|
||||
Reference in new issue
Block a user