refactor(vkauth): разбить token.go на файлы по шагам

token.go теперь тонкий оркестратор (~75 строк). Каждый шаг VK-токена в своём
файле:
- token_request.go: хелпер doRequest (POST + browser-заголовки + JSON)
- token_anon.go: fetchAnonToken (шаг 1, login.vk.ru)
- token_call.go: fetchCallToken + captcha-loop + solveCaptcha (шаг 2)
- token_oksession.go: fetchOkRuSession (шаг 3, calls.okcdn.ru)
- token_creds.go: fetchTurnCreds (шаг 4, vchat.joinConversationByLink)

Публичный API (Client, getTokenChain, tokenChainFn) не изменён. Поведение
идентично оригиналу.
This commit is contained in:
samosvalishe committed 2026-05-21 01:26:21 +03:00
1 parent d82258f844
commit 0e2d42c912
6 files changed
+385 -245

No files matched your search

+15 -245
View File
@@ -1,24 +1,15 @@
package vkauth
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
neturl "net/url"
"strings"
"time"
"github.com/samosvalishe/btp/internal/client/browserprofile"
"github.com/samosvalishe/btp/internal/client/captcha"
"github.com/samosvalishe/btp/internal/client/namegen"
fhttp "github.com/bogdanfinn/fhttp"
tlsclient "github.com/bogdanfinn/tls-client"
"github.com/bogdanfinn/tls-client/profiles"
"github.com/google/uuid"
)
// getTokenChain walks the 4-step VK token exchange for one client_id/secret
@@ -32,7 +23,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
SecChUaPlatform: `"Windows"`,
}
client, err := tlsclient.NewHttpClient(tlsclient.NewNoopLogger(),
httpClient, err := tlsclient.NewHttpClient(tlsclient.NewNoopLogger(),
tlsclient.WithTimeoutSeconds(20),
tlsclient.WithClientProfile(profiles.Chrome_146),
tlsclient.WithCookieJar(jar),
@@ -47,260 +38,39 @@ 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)
doRequest := func(data string, url string) (resp map[string]any, err error) {
parsedURL, err := neturl.Parse(url)
if err != nil {
return nil, fmt.Errorf("parse request URL: %w", err)
}
domain := parsedURL.Hostname()
req, err := fhttp.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer([]byte(data)))
if err != nil {
return nil, err
}
req.Host = domain
browserprofile.ApplyFhttp(req, profile)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "*/*")
req.Header.Set("Origin", "https://vk.ru")
req.Header.Set("Referer", "https://vk.ru/")
req.Header.Set("Sec-Fetch-Site", "same-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Priority", "u=1, i")
httpResp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if closeErr := httpResp.Body.Close(); closeErr != nil {
c.log.Warnf("[VK Auth] close response body: %s", closeErr)
}
}()
body, err := io.ReadAll(httpResp.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(body, &resp); err != nil {
return nil, err
}
return resp, nil
}
// Token 1: anonymous app token.
data := fmt.Sprintf("client_id=%s&token_type=messages&client_secret=%s&version=1&app_id=%s", creds.ClientID, creds.ClientSecret, creds.ClientID)
resp, err := doRequest(data, "https://login.vk.ru/?act=get_anonym_token")
// Step 1: anonymous app token.
token1, err := c.fetchAnonToken(ctx, httpClient, profile, creds)
if err != nil {
return "", "", nil, err
}
dataMap, ok := resp["data"].(map[string]any)
if !ok {
return "", "", nil, fmt.Errorf("unexpected anon token response: %v", resp)
}
token1, ok := dataMap["access_token"].(string)
if !ok {
return "", "", nil, fmt.Errorf("missing access_token in response: %v", resp)
}
vkDelayRandom(100, 150)
// Token 1 -> getCallPreview (warmup, non-fatal).
data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&fields=photo_200&access_token=%s", link, token1)
if _, prevErr := doRequest(data, "https://api.vk.ru/method/calls.getCallPreview?v=5.275&client_id="+creds.ClientID); prevErr != nil {
// Step 1a: getCallPreview warmup (non-fatal).
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 {
c.log.Warnf("[STREAM %d] [VK Auth] getCallPreview failed: %v", streamID, prevErr)
}
vkDelayRandom(200, 400)
// Token 2: anonymous call token (captcha may trigger here).
data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=%s&access_token=%s", link, escapedName, token1)
urlAddr := fmt.Sprintf("https://api.vk.ru/method/calls.getAnonymousToken?v=5.275&client_id=%s", creds.ClientID)
var token2 string
for attempt := 0; ; attempt++ {
resp, err = doRequest(data, urlAddr)
if err != nil {
return "", "", nil, err
}
if errObj, hasErr := resp["error"].(map[string]any); hasErr {
captchaErr := captcha.ParseError(errObj)
if captchaErr != nil && captchaErr.IsCaptcha() {
solveMode, hasSolveMode := CaptchaSolveModeForAttempt(attempt, c.manualOnly)
if !hasSolveMode {
c.log.Warnf("[STREAM %d] [Captcha] No more solve modes available (attempt %d)", streamID, attempt+1)
c.engageLockout(60 * time.Second)
if c.streamsFn() == 0 {
c.log.Errorf("[STREAM %d] [Captcha] FATAL: 0 connected streams and solve modes exhausted", streamID)
return "", "", nil, ErrFatalCaptchaNoStreams
}
return "", "", nil, ErrCaptchaWaitRequired
}
var successToken string
var captchaKey string
var solveErr error
switch solveMode {
case CaptchaSolveModeAuto:
solveFn := c.autoSolver
if solveFn == nil {
solveFn = DefaultAutoSolve
}
if captchaErr.SessionToken != "" && captchaErr.RedirectURI != "" {
successToken, solveErr = solveFn(ctx, captchaErr, streamID, client, profile)
if solveErr != nil {
c.log.Warnf("[STREAM %d] [Captcha] Auto captcha failed: %v", streamID, solveErr)
}
} else {
solveErr = fmt.Errorf("missing fields for auto solve")
}
case CaptchaSolveModeManual:
if c.manualSolve == nil {
solveErr = fmt.Errorf("manual captcha solver not configured")
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. We still propagate
// parent cancellation (app shutdown) so the in-flight solver
// goroutine doesn't outlive the process.
manualCtx, manualCancel := context.WithTimeout(ctx, 3*time.Minute)
type manualRes struct {
token string
key string
err error
}
resCh := make(chan manualRes, 1)
go func() {
t, k, e := c.manualSolve(manualCtx, captchaErr, c.dialer)
resCh <- manualRes{t, k, e}
}()
select {
case res := <-resCh:
successToken = res.token
captchaKey = res.key
solveErr = res.err
if successToken != "" || captchaKey != "" {
if solveErr != nil {
c.log.Debugf("[STREAM %d] [Captcha] Token received (ignoring cleanup error: %v)", streamID, solveErr)
solveErr = nil
}
c.log.Infof("[STREAM %d] [Captcha] Got token from browser", streamID)
} else if solveErr != nil {
c.log.Warnf("[STREAM %d] [Captcha] Manual solver error: %v", streamID, solveErr)
}
case <-manualCtx.Done():
if errors.Is(manualCtx.Err(), context.DeadlineExceeded) {
solveErr = fmt.Errorf("manual captcha timed out after 3m")
} else {
solveErr = fmt.Errorf("manual captcha interrupted: %w", manualCtx.Err())
}
}
manualCancel()
}
if solveErr != nil {
c.log.Warnf("[STREAM %d] [Captcha] %s failed (attempt %d): %v", streamID, CaptchaSolveModeLabel(solveMode), attempt+1, solveErr)
nextSolveMode, hasNextSolveMode := CaptchaSolveModeForAttempt(attempt+1, c.manualOnly)
if hasNextSolveMode {
c.log.Infof("[STREAM %d] [Captcha] Falling back to %s", streamID, CaptchaSolveModeLabel(nextSolveMode))
continue
}
c.engageLockout(60 * time.Second)
if c.streamsFn() == 0 {
c.log.Errorf("[STREAM %d] [Captcha] FATAL: 0 connected streams and manual captcha failed/timed out", streamID)
return "", "", nil, ErrFatalCaptchaNoStreams
}
return "", "", nil, ErrCaptchaWaitRequired
}
if captchaErr.CaptchaAttempt == "0" || captchaErr.CaptchaAttempt == "" {
captchaErr.CaptchaAttempt = "1"
}
if captchaKey != "" {
data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=%s&captcha_key=%s&captcha_sid=%s&access_token=%s",
link, escapedName, neturl.QueryEscape(captchaKey), captchaErr.CaptchaSid, token1)
} else {
data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=%s&captcha_key=&captcha_sid=%s&is_sound_captcha=0&success_token=%s&captcha_ts=%s&captcha_attempt=%s&access_token=%s",
link, escapedName, captchaErr.CaptchaSid, neturl.QueryEscape(successToken), captchaErr.CaptchaTs, captchaErr.CaptchaAttempt, token1)
}
continue
}
return "", "", nil, fmt.Errorf("VK API error: %v", errObj)
}
respMap, okLoop := resp["response"].(map[string]any)
if !okLoop {
return "", "", nil, fmt.Errorf("unexpected getAnonymousToken response: %v", resp)
}
token2, okLoop = respMap["token"].(string)
if !okLoop {
return "", "", nil, fmt.Errorf("missing token in response: %v", resp)
}
break
// Step 2: anonymous call token (captcha may trigger here).
token2, err := c.fetchCallToken(ctx, httpClient, profile, streamID, link, escapedName, token1, creds)
if err != nil {
return "", "", nil, err
}
vkDelayRandom(100, 150)
// Token 3: ok.ru session_key.
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", neturl.QueryEscape(sessionData))
resp, err = doRequest(data, "https://calls.okcdn.ru/fb.do")
// Step 3: ok.ru session_key.
sessionKey, err := c.fetchOkRuSession(ctx, httpClient, profile)
if err != nil {
return "", "", nil, err
}
token3, ok := resp["session_key"].(string)
if !ok {
return "", "", nil, fmt.Errorf("missing session_key in response: %v", resp)
}
vkDelayRandom(100, 150)
// Token 4 -> TURN creds.
data = fmt.Sprintf("joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s", link, token2, token3)
resp, err = doRequest(data, "https://calls.okcdn.ru/fb.do")
if err != nil {
return "", "", nil, err
}
tsRaw, ok := resp["turn_server"].(map[string]any)
if !ok {
return "", "", nil, fmt.Errorf("missing turn_server in response: %v", resp)
}
user, ok := tsRaw["username"].(string)
if !ok {
return "", "", nil, fmt.Errorf("missing username in turn_server")
}
pass, ok := tsRaw["credential"].(string)
if !ok {
return "", "", nil, fmt.Errorf("missing credential in turn_server")
}
urlsRaw, ok := tsRaw["urls"].([]any)
if !ok || len(urlsRaw) == 0 {
return "", "", nil, fmt.Errorf("missing or empty urls in turn_server")
}
c.log.Infof("[STREAM %d] [VK Auth] TURN urls (%d total):", streamID, len(urlsRaw))
for i, u := range urlsRaw {
c.log.Infof("[STREAM %d] [VK Auth] [%d] %v", streamID, i, u)
}
var addresses []string
for _, u := range urlsRaw {
urlStr, ok := u.(string)
if !ok {
continue
}
clean := strings.Split(urlStr, "?")[0]
address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
addresses = append(addresses, address)
}
if len(addresses) == 0 {
return "", "", nil, fmt.Errorf("no valid TURN addresses found")
}
return user, pass, addresses, nil
// Step 4: TURN credentials.
return c.fetchTurnCreds(ctx, httpClient, profile, streamID, link, token2, sessionKey)
}
+30
View File
@@ -0,0 +1,30 @@
package vkauth
import (
"context"
"fmt"
"github.com/samosvalishe/btp/internal/client/browserprofile"
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.
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)
resp, err := c.doRequest(ctx, httpClient, profile, data, "https://login.vk.ru/?act=get_anonym_token")
if err != nil {
return "", err
}
dataMap, ok := resp["data"].(map[string]any)
if !ok {
return "", fmt.Errorf("unexpected anon token response: %v", resp)
}
token, ok := dataMap["access_token"].(string)
if !ok {
return "", fmt.Errorf("missing access_token in response: %v", resp)
}
return token, nil
}
+184
View File
@@ -0,0 +1,184 @@
package vkauth
import (
"context"
"errors"
"fmt"
neturl "net/url"
"time"
"github.com/samosvalishe/btp/internal/client/browserprofile"
"github.com/samosvalishe/btp/internal/client/captcha"
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.
func (c *Client) fetchCallToken(
ctx context.Context,
httpClient tlsclient.HttpClient,
profile browserprofile.Profile,
streamID int,
link, escapedName, token1 string,
creds VKCredentials,
) (string, error) {
urlAddr := fmt.Sprintf("https://api.vk.ru/method/calls.getAnonymousToken?v=5.275&client_id=%s", creds.ClientID)
data := fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=%s&access_token=%s",
link, escapedName, token1)
for attempt := 0; ; attempt++ {
resp, err := c.doRequest(ctx, httpClient, profile, data, urlAddr)
if err != nil {
return "", err
}
if errObj, hasErr := resp["error"].(map[string]any); hasErr {
captchaErr := captcha.ParseError(errObj)
if captchaErr != nil && captchaErr.IsCaptcha() {
retryData, err := c.solveCaptcha(ctx, httpClient, profile, streamID, attempt, link, escapedName, token1, captchaErr)
if err != nil {
return "", err
}
data = retryData
continue
}
return "", fmt.Errorf("VK API error: %v", errObj)
}
respMap, ok := resp["response"].(map[string]any)
if !ok {
return "", fmt.Errorf("unexpected getAnonymousToken response: %v", resp)
}
token2, ok := respMap["token"].(string)
if !ok {
return "", fmt.Errorf("missing token in response: %v", resp)
}
return token2, nil
}
}
// solveCaptcha drives one captcha solve attempt and returns the POST body for
// the next retry, or an error when all modes are exhausted.
func (c *Client) solveCaptcha(
ctx context.Context,
httpClient tlsclient.HttpClient,
profile browserprofile.Profile,
streamID, attempt int,
link, escapedName, token1 string,
captchaErr *captcha.Error,
) (retryData string, err error) {
solveMode, hasSolveMode := CaptchaSolveModeForAttempt(attempt, c.manualOnly)
if !hasSolveMode {
c.log.Warnf("[STREAM %d] [Captcha] No more solve modes available (attempt %d)", streamID, attempt+1)
c.engageLockout(60 * time.Second)
if c.streamsFn() == 0 {
c.log.Errorf("[STREAM %d] [Captcha] FATAL: 0 connected streams and solve modes exhausted", streamID)
return "", ErrFatalCaptchaNoStreams
}
return "", ErrCaptchaWaitRequired
}
var successToken string
var captchaKey string
var solveErr error
switch solveMode {
case CaptchaSolveModeAuto:
solveFn := c.autoSolver
if solveFn == nil {
solveFn = DefaultAutoSolve
}
if captchaErr.SessionToken != "" && captchaErr.RedirectURI != "" {
successToken, solveErr = solveFn(ctx, captchaErr, streamID, httpClient, profile)
if solveErr != nil {
c.log.Warnf("[STREAM %d] [Captcha] Auto captcha failed: %v", streamID, solveErr)
}
} else {
solveErr = fmt.Errorf("missing fields for auto solve")
}
case CaptchaSolveModeManual:
if c.manualSolve == nil {
solveErr = fmt.Errorf("manual captcha solver not configured")
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.
manualCtx, manualCancel := context.WithTimeout(ctx, 3*time.Minute)
type manualRes struct {
token string
key string
err error
}
resCh := make(chan manualRes, 1)
go func() {
t, k, e := c.manualSolve(manualCtx, captchaErr, c.dialer)
resCh <- manualRes{t, k, e}
}()
select {
case res := <-resCh:
successToken = res.token
captchaKey = res.key
solveErr = res.err
if successToken != "" || captchaKey != "" {
if solveErr != nil {
c.log.Debugf("[STREAM %d] [Captcha] Token received (ignoring cleanup error: %v)", streamID, solveErr)
solveErr = nil
}
c.log.Infof("[STREAM %d] [Captcha] Got token from browser", streamID)
} else if solveErr != nil {
c.log.Warnf("[STREAM %d] [Captcha] Manual solver error: %v", streamID, solveErr)
}
case <-manualCtx.Done():
if errors.Is(manualCtx.Err(), context.DeadlineExceeded) {
solveErr = fmt.Errorf("manual captcha timed out after 3m")
} else {
solveErr = fmt.Errorf("manual captcha interrupted: %w", manualCtx.Err())
}
}
manualCancel()
}
if solveErr != nil {
c.log.Warnf("[STREAM %d] [Captcha] %s failed (attempt %d): %v",
streamID, CaptchaSolveModeLabel(solveMode), attempt+1, solveErr)
nextSolveMode, hasNextSolveMode := CaptchaSolveModeForAttempt(attempt+1, c.manualOnly)
if hasNextSolveMode {
c.log.Infof("[STREAM %d] [Captcha] Falling back to %s",
streamID, CaptchaSolveModeLabel(nextSolveMode))
return buildCaptchaRetryData(link, escapedName, token1, captchaErr, "", captchaKey), nil
}
c.engageLockout(60 * time.Second)
if c.streamsFn() == 0 {
c.log.Errorf("[STREAM %d] [Captcha] FATAL: 0 connected streams and manual captcha failed/timed out", streamID)
return "", ErrFatalCaptchaNoStreams
}
return "", ErrCaptchaWaitRequired
}
if captchaErr.CaptchaAttempt == "0" || captchaErr.CaptchaAttempt == "" {
captchaErr.CaptchaAttempt = "1"
}
return buildCaptchaRetryData(link, escapedName, token1, captchaErr, successToken, captchaKey), nil
}
// buildCaptchaRetryData constructs the POST body for the next captcha attempt.
func buildCaptchaRetryData(link, escapedName, token1 string, captchaErr *captcha.Error, successToken, captchaKey string) string {
if captchaKey != "" {
return fmt.Sprintf(
"vk_join_link=https://vk.com/call/join/%s&name=%s&captcha_key=%s&captcha_sid=%s&access_token=%s",
link, escapedName, neturl.QueryEscape(captchaKey), captchaErr.CaptchaSid, token1,
)
}
return fmt.Sprintf(
"vk_join_link=https://vk.com/call/join/%s&name=%s&captcha_key=&captcha_sid=%s&is_sound_captcha=0&success_token=%s&captcha_ts=%s&captcha_attempt=%s&access_token=%s",
link, escapedName, captchaErr.CaptchaSid, neturl.QueryEscape(successToken),
captchaErr.CaptchaTs, captchaErr.CaptchaAttempt, token1,
)
}
+67
View File
@@ -0,0 +1,67 @@
package vkauth
import (
"context"
"fmt"
"strings"
"github.com/samosvalishe/btp/internal/client/browserprofile"
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.
func (c *Client) fetchTurnCreds(
ctx context.Context,
httpClient tlsclient.HttpClient,
profile browserprofile.Profile,
streamID int,
link, token2, sessionKey string,
) (user, pass string, addresses []string, err error) {
data := fmt.Sprintf(
"joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s",
link, token2, sessionKey,
)
resp, err := c.doRequest(ctx, httpClient, profile, data, "https://calls.okcdn.ru/fb.do")
if err != nil {
return "", "", nil, err
}
tsRaw, ok := resp["turn_server"].(map[string]any)
if !ok {
return "", "", nil, fmt.Errorf("missing turn_server in response: %v", resp)
}
user, ok = tsRaw["username"].(string)
if !ok {
return "", "", nil, fmt.Errorf("missing username in turn_server")
}
pass, ok = tsRaw["credential"].(string)
if !ok {
return "", "", nil, fmt.Errorf("missing credential in turn_server")
}
urlsRaw, ok := tsRaw["urls"].([]any)
if !ok || len(urlsRaw) == 0 {
return "", "", nil, fmt.Errorf("missing or empty urls in turn_server")
}
c.log.Infof("[STREAM %d] [VK Auth] TURN urls (%d total):", streamID, len(urlsRaw))
for i, u := range urlsRaw {
c.log.Infof("[STREAM %d] [VK Auth] [%d] %v", streamID, i, u)
}
for _, u := range urlsRaw {
urlStr, ok := u.(string)
if !ok {
continue
}
clean := strings.Split(urlStr, "?")[0]
address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
addresses = append(addresses, address)
}
if len(addresses) == 0 {
return "", "", nil, fmt.Errorf("no valid TURN addresses found")
}
return user, pass, addresses, nil
}
+29
View File
@@ -0,0 +1,29 @@
package vkauth
import (
"context"
"fmt"
neturl "net/url"
"github.com/samosvalishe/btp/internal/client/browserprofile"
"github.com/google/uuid"
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.
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",
neturl.QueryEscape(sessionData))
resp, err := c.doRequest(ctx, httpClient, profile, data, "https://calls.okcdn.ru/fb.do")
if err != nil {
return "", err
}
sessionKey, ok := resp["session_key"].(string)
if !ok {
return "", fmt.Errorf("missing session_key in response: %v", resp)
}
return sessionKey, nil
}
+60
View File
@@ -0,0 +1,60 @@
package vkauth
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
neturl "net/url"
"github.com/samosvalishe/btp/internal/client/browserprofile"
fhttp "github.com/bogdanfinn/fhttp"
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.
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 {
return nil, fmt.Errorf("parse request URL: %w", err)
}
domain := parsedURL.Hostname()
req, err := fhttp.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer([]byte(data)))
if err != nil {
return nil, err
}
req.Host = domain
browserprofile.ApplyFhttp(req, profile)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "*/*")
req.Header.Set("Origin", "https://vk.ru")
req.Header.Set("Referer", "https://vk.ru/")
req.Header.Set("Sec-Fetch-Site", "same-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Priority", "u=1, i")
httpResp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
if closeErr := httpResp.Body.Close(); closeErr != nil {
c.log.Warnf("[VK Auth] close response body: %s", closeErr)
}
}()
body, err := io.ReadAll(httpResp.Body)
if err != nil {
return nil, err
}
var resp map[string]any
if err := json.Unmarshal(body, &resp); err != nil {
return nil, err
}
return resp, nil
}