feat(mobile): переживание сна и рестарта на Android
This commit is contained in:
1 parent
0a6b0e0e85
commit
681dde8a6d
29 files changed
+1253
-93
No files matched your search
@@ -0,0 +1,264 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider/vk/internal/browserprofile"
|
||||
)
|
||||
|
||||
// PoW-скрипт страницы обфусцирован, имена переменных генерируются заново на каждый
|
||||
// релиз. Стабильны только аргументы IIFE (input, difficulty, метка ошибки) и
|
||||
// префикс версии конверта.
|
||||
var (
|
||||
rePowArgs = regexp.MustCompile(`\}\(\s*["']([A-Za-z0-9_-]{8,})["']\s*,\s*(\d+)\s*,\s*["'][^"']*["']\s*\)\s*\)`)
|
||||
rePowPrefix = regexp.MustCompile(`captchaPowResult["'\]]{0,3}\s*=\s*["']([A-Za-z0-9._-]{0,8})["']\s*\+`)
|
||||
)
|
||||
|
||||
type powParams struct {
|
||||
Input string
|
||||
Difficulty int
|
||||
Prefix string
|
||||
}
|
||||
|
||||
// powResult - конверт window.captchaPowResult: виджету уходит не голый хэш.
|
||||
// Порядок полей повторяет порядок ключей у JSON.stringify страницы.
|
||||
type powResult struct {
|
||||
Hash string `json:"hash"`
|
||||
Nonce int `json:"nonce"`
|
||||
DurationMs int64 `json:"duration_ms"`
|
||||
Telemetry json.RawMessage `json:"telemetry"`
|
||||
TelHash string `json:"tel_hash"`
|
||||
}
|
||||
|
||||
func parsePowParams(html string) (powParams, error) {
|
||||
m := rePowArgs.FindStringSubmatch(html)
|
||||
if len(m) < 3 {
|
||||
return powParams{}, errors.New("captcha pow args not found")
|
||||
}
|
||||
difficulty, err := strconv.Atoi(m[2])
|
||||
if err != nil || difficulty <= 0 {
|
||||
return powParams{}, fmt.Errorf("invalid captcha difficulty %q", m[2])
|
||||
}
|
||||
prefix := rePowPrefix.FindStringSubmatch(html)
|
||||
if len(prefix) < 2 {
|
||||
return powParams{}, errors.New("captcha pow envelope not recognized")
|
||||
}
|
||||
return powParams{Input: m[1], Difficulty: difficulty, Prefix: prefix[1]}, nil
|
||||
}
|
||||
|
||||
func (s *captchaSession) powEnvelope(p powParams) (string, error) {
|
||||
hash, nonce := solvePoW(s.ctx, p.Input, p.Difficulty)
|
||||
if hash == "" {
|
||||
return "", errors.New("captcha pow failed")
|
||||
}
|
||||
telemetry, err := marshalJS(s.powTelemetry())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("captcha pow telemetry: %w", err)
|
||||
}
|
||||
telHash, err := telemetryHash(telemetry)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("captcha pow tel_hash: %w", err)
|
||||
}
|
||||
envelope, err := marshalJS(powResult{
|
||||
Hash: hash,
|
||||
Nonce: nonce,
|
||||
DurationMs: powDurationMs(nonce),
|
||||
Telemetry: telemetry,
|
||||
TelHash: telHash,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("captcha pow encode: %w", err)
|
||||
}
|
||||
return p.Prefix + base64.StdEncoding.EncodeToString(envelope), nil
|
||||
}
|
||||
|
||||
func solvePoW(ctx context.Context, input string, difficulty int) (string, int) {
|
||||
if input == "" || difficulty <= 0 {
|
||||
return "", 0
|
||||
}
|
||||
target := strings.Repeat("0", difficulty)
|
||||
buf := make([]byte, 0, len(input)+20)
|
||||
buf = append(buf, input...)
|
||||
for nonce := 0; nonce <= 10_000_000; nonce++ {
|
||||
if nonce&1023 == 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", 0
|
||||
default:
|
||||
}
|
||||
}
|
||||
buf = strconv.AppendInt(buf[:len(input)], int64(nonce), 10)
|
||||
sum := sha256.Sum256(buf)
|
||||
hashHex := hex.EncodeToString(sum[:])
|
||||
if strings.HasPrefix(hashHex, target) {
|
||||
return hashHex, nonce
|
||||
}
|
||||
}
|
||||
return "", 0
|
||||
}
|
||||
|
||||
// Цикл в браузере синхронный: nonce 53 -> 1 мс, 267 -> 4 мс.
|
||||
func powDurationMs(nonce int) int64 {
|
||||
return max(1, int64(math.Round(float64(nonce+1)*0.015)))
|
||||
}
|
||||
|
||||
// telemetryHash повторяет канонизатор страницы: ключи по алфавиту (map в Go
|
||||
// сортирует их сам), undefined на нашей стороне не бывает.
|
||||
func telemetryHash(telemetry []byte) (string, error) {
|
||||
var v any
|
||||
if err := json.Unmarshal(telemetry, &v); err != nil {
|
||||
return "", err
|
||||
}
|
||||
canonical, err := marshalJS(v)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(canonical)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
// marshalJS - JSON без HTML-экранирования: JSON.stringify не трогает < > &.
|
||||
func marshalJS(v any) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bytes.TrimRight(buf.Bytes(), "\n"), nil
|
||||
}
|
||||
|
||||
// powTelemetryData - пробы PoW-скрипта; порядок полей = порядок проб, так их
|
||||
// пишет JSON.stringify.
|
||||
type powTelemetryData struct {
|
||||
Globals powProbe `json:"globals"`
|
||||
UA powProbe `json:"ua"`
|
||||
Frame powProbe `json:"frame"`
|
||||
MatchMedia powProbe `json:"match_media"`
|
||||
Plugins powProbe `json:"plugins"`
|
||||
NavTamper powProbe `json:"nav_tamper"`
|
||||
Referrer powProbe `json:"referrer"`
|
||||
DevTools powProbe `json:"devtools"`
|
||||
CSS powProbe `json:"css"`
|
||||
NativeIntegrity powProbe `json:"native_integrity"`
|
||||
}
|
||||
|
||||
type powProbe struct {
|
||||
OK bool `json:"ok"`
|
||||
Result any `json:"result"`
|
||||
}
|
||||
|
||||
func probe(result any) powProbe { return powProbe{OK: true, Result: result} }
|
||||
|
||||
type powGlobals struct {
|
||||
Doc bool `json:"doc"`
|
||||
Win bool `json:"win"`
|
||||
Nav bool `json:"nav"`
|
||||
Webdriver bool `json:"webdriver"`
|
||||
HW int `json:"hw"`
|
||||
Mem *int `json:"mem"`
|
||||
}
|
||||
|
||||
type powUA struct {
|
||||
UserAgent string `json:"userAgent"`
|
||||
}
|
||||
|
||||
type powFrame struct {
|
||||
FrameElement *string `json:"frameElement"`
|
||||
AncestorOriginsLen int `json:"ancestorOriginsLen"`
|
||||
ParentAccessible bool `json:"parentAccessible"`
|
||||
}
|
||||
|
||||
type powMatchMedia struct {
|
||||
PrefersDark bool `json:"prefersDark"`
|
||||
PrefersLight bool `json:"prefersLight"`
|
||||
ReducedMotion bool `json:"reducedMotion"`
|
||||
PointerFine bool `json:"pointerFine"`
|
||||
}
|
||||
|
||||
type powPlugins struct {
|
||||
Length int `json:"length"`
|
||||
Names []string `json:"names"`
|
||||
IsChrome bool `json:"isChrome"`
|
||||
}
|
||||
|
||||
type powNavTamper struct {
|
||||
Tampered bool `json:"tampered"`
|
||||
}
|
||||
|
||||
type powReferrer struct {
|
||||
Referrer string `json:"referrer"`
|
||||
InIframe bool `json:"inIframe"`
|
||||
Domain string `json:"domain"`
|
||||
}
|
||||
|
||||
type powDevTools struct {
|
||||
Open bool `json:"open"`
|
||||
}
|
||||
|
||||
type powCSS struct {
|
||||
ExpectedMissing int `json:"expectedMissing"`
|
||||
}
|
||||
|
||||
type powNativeIntegrity struct {
|
||||
ProtoMatch bool `json:"protoMatch"`
|
||||
XHRNative bool `json:"xhrNative"`
|
||||
}
|
||||
|
||||
// Chrome отдаёт пять фиктивных PDF-плагинов везде, где умеет показывать PDF.
|
||||
var chromePDFPlugins = []string{
|
||||
"PDF Viewer",
|
||||
"Chrome PDF Viewer",
|
||||
"Chromium PDF Viewer",
|
||||
"Microsoft Edge PDF Viewer",
|
||||
"WebKit built-in PDF",
|
||||
}
|
||||
|
||||
// powTelemetry описывает страницу такой, какой её видел бы браузер персоны:
|
||||
// страницу мы тянем верхнеуровневой навигацией (Sec-Fetch-Dest: document),
|
||||
// поэтому frame и referrer описывают top-level документ - врозь их менять нельзя.
|
||||
func (s *captchaSession) powTelemetry() powTelemetryData {
|
||||
p := s.profile
|
||||
// На Android нет встроенного PDF-вьювера, значит и списка плагинов.
|
||||
plugins := powPlugins{Names: []string{}}
|
||||
if !p.IsMobile() {
|
||||
plugins = powPlugins{Length: len(chromePDFPlugins), Names: chromePDFPlugins, IsChrome: true}
|
||||
}
|
||||
dark := prefersDark(p)
|
||||
return powTelemetryData{
|
||||
Globals: probe(powGlobals{
|
||||
Doc: true, Win: true, Nav: true,
|
||||
Webdriver: p.Webdriver(),
|
||||
HW: p.HardwareConcurrency(),
|
||||
Mem: p.DeviceMemory(),
|
||||
}),
|
||||
UA: probe(powUA{UserAgent: p.UserAgent}),
|
||||
Frame: probe(powFrame{ParentAccessible: true}),
|
||||
MatchMedia: probe(powMatchMedia{PrefersDark: dark, PrefersLight: !dark, PointerFine: !p.IsMobile()}),
|
||||
Plugins: probe(plugins),
|
||||
NavTamper: probe(powNavTamper{}),
|
||||
Referrer: probe(powReferrer{
|
||||
Referrer: "https://" + s.domain + "/",
|
||||
Domain: strings.TrimPrefix(s.pageOrigin, "https://"),
|
||||
}),
|
||||
DevTools: probe(powDevTools{}),
|
||||
CSS: probe(powCSS{}),
|
||||
NativeIntegrity: probe(powNativeIntegrity{ProtoMatch: true, XHRNative: true}),
|
||||
}
|
||||
}
|
||||
|
||||
// prefers-color-scheme у живого посетителя не скачет между сессиями - берём бит персоны.
|
||||
func prefersDark(p browserprofile.Profile) bool {
|
||||
return len(p.VisitorID) > 0 && p.VisitorID[0]%2 == 1
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/provider/vk/internal/browserprofile"
|
||||
)
|
||||
|
||||
// Живая страница captcha, снятая целиком: PoW-скрипт обфусцирован, поэтому
|
||||
// контракт проверяется на настоящей разметке, а не на её пересказе. Обновлять
|
||||
// фикстуру - task captcha:page.
|
||||
func TestParseCaptchaPageFixture(t *testing.T) {
|
||||
html, err := os.ReadFile("testdata/not_robot_captcha.html")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
page, err := parseCaptchaPage(string(html))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page.Pow.Input != "fnZQN7lKKXvo37tH" || page.Pow.Difficulty != 2 || page.Pow.Prefix != "v2." {
|
||||
t.Fatalf("pow = %+v", page.Pow)
|
||||
}
|
||||
if page.ScriptURL != "https://static.vk.ru/vkid/1.1.1394/not_robot_captcha.js" {
|
||||
t.Fatalf("script url = %q", page.ScriptURL)
|
||||
}
|
||||
if !page.Init.Found || page.Init.APIHost != "api.vk.ru" || page.Init.ShowType != "checkbox" {
|
||||
t.Fatalf("init = %+v", page.Init)
|
||||
}
|
||||
}
|
||||
|
||||
// Незнакомая разметка обязана ронять авторешение, а не уезжать в check заведомо
|
||||
// неверным hash.
|
||||
func TestParsePowParamsRejectsUnknownMarkup(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
html string
|
||||
}{
|
||||
{name: "no pow script", html: `<html><body><div id="spa_root"></div></body></html>`},
|
||||
{
|
||||
name: "args without envelope",
|
||||
html: `<script>(function(a,b,c){})("fnZQN7lKKXvo37tH",2,"pow_timeout"));</script>`,
|
||||
},
|
||||
{
|
||||
name: "envelope without args",
|
||||
html: `<script>window['captchaPowResult']='v2.'+btoa(x);}(powInput,difficulty,"pow_timeout"));</script>`,
|
||||
},
|
||||
{
|
||||
name: "zero difficulty",
|
||||
html: `<script>window['captchaPowResult']='v2.'+btoa(x);}("fnZQN7lKKXvo37tH",0,"pow_timeout"));</script>`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := parsePowParams(tt.html); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolvePoW(t *testing.T) {
|
||||
got, nonce := solvePoW(context.Background(), "input", 1)
|
||||
if len(got) != 64 || !strings.HasPrefix(got, "0") {
|
||||
t.Fatalf("pow = %q, want 64-hex with leading zero", got)
|
||||
}
|
||||
sum := sha256.Sum256([]byte("input" + strconv.Itoa(nonce)))
|
||||
if hex.EncodeToString(sum[:]) != got {
|
||||
t.Fatalf("pow hash does not match sha256(input+nonce)")
|
||||
}
|
||||
}
|
||||
|
||||
// Эталон снят с персоны seed=fixture; tel_hash сверен с канонизатором самой
|
||||
// страницы. Любая правка значений телеметрии обязана осознанно двигать эталон.
|
||||
const (
|
||||
goldenTelemetry = `{"globals":{"ok":true,"result":{"doc":true,"win":true,"nav":true,"webdriver":false,"hw":12,"mem":8}},` +
|
||||
`"ua":{"ok":true,"result":{"userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"}},` +
|
||||
`"frame":{"ok":true,"result":{"frameElement":null,"ancestorOriginsLen":0,"parentAccessible":true}},` +
|
||||
`"match_media":{"ok":true,"result":{"prefersDark":true,"prefersLight":false,"reducedMotion":false,"pointerFine":true}},` +
|
||||
`"plugins":{"ok":true,"result":{"length":5,"names":["PDF Viewer","Chrome PDF Viewer","Chromium PDF Viewer","Microsoft Edge PDF Viewer","WebKit built-in PDF"],"isChrome":true}},` +
|
||||
`"nav_tamper":{"ok":true,"result":{"tampered":false}},` +
|
||||
`"referrer":{"ok":true,"result":{"referrer":"https://vk.com/","inIframe":false,"domain":"id.vk.ru"}},` +
|
||||
`"devtools":{"ok":true,"result":{"open":false}},` +
|
||||
`"css":{"ok":true,"result":{"expectedMissing":0}},` +
|
||||
`"native_integrity":{"ok":true,"result":{"protoMatch":true,"xhrNative":true}}}`
|
||||
goldenTelHash = "4edea10bbb2b35b8790cfd79ad510fd8e833158c7095788841c2fd92b2edd3d1"
|
||||
)
|
||||
|
||||
// Конверт целиком: порядок ключей, телеметрия персоны и её sha256 - всё, что VK
|
||||
// проверяет на check.
|
||||
func TestPowEnvelope(t *testing.T) {
|
||||
s := &captchaSession{
|
||||
ctx: context.Background(),
|
||||
profile: browserprofile.For(browserprofile.Desktop, browserprofile.Identity{Seed: "fixture"}),
|
||||
domain: "vk.com",
|
||||
pageOrigin: "https://id.vk.ru",
|
||||
}
|
||||
|
||||
got, err := s.powEnvelope(powParams{Input: "input", Difficulty: 1, Prefix: "v2."})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload, ok := strings.CutPrefix(got, "v2.")
|
||||
if !ok {
|
||||
t.Fatalf("envelope = %q, want v2. prefix", got)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
hash, nonce := solvePoW(context.Background(), "input", 1)
|
||||
want := `{"hash":"` + hash + `","nonce":` + strconv.Itoa(nonce) +
|
||||
`,"duration_ms":` + strconv.FormatInt(powDurationMs(nonce), 10) +
|
||||
`,"telemetry":` + goldenTelemetry + `,"tel_hash":"` + goldenTelHash + `"}`
|
||||
if string(raw) != want {
|
||||
t.Fatalf("envelope =\n%s\nwant\n%s", raw, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelemetryHashCanonicalizesKeys(t *testing.T) {
|
||||
// Тот же объект с переставленными ключами обязан дать тот же tel_hash.
|
||||
shuffled := `{"b":{"y":1,"x":[2,{"n":null,"m":"s"}]},"a":true}`
|
||||
ordered := `{"a":true,"b":{"x":[2,{"m":"s","n":null}],"y":1}}`
|
||||
|
||||
first, err := telemetryHash([]byte(shuffled))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := telemetryHash([]byte(ordered))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first != second {
|
||||
t.Fatalf("tel_hash = %s vs %s", first, second)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(ordered))
|
||||
if first != hex.EncodeToString(sum[:]) {
|
||||
t.Fatalf("tel_hash = %s, want sha256 of canonical form", first)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<!DOCTYPE html><html><head>
|
||||
<script nonce="bb3ce87d42d0" src="https://static.vk.ru/vkid/1.1.1394/not_robot_captcha.js" defer></script>
|
||||
<script nonce="bb3ce87d42d0">window.init = {"hosts":{"host":"vk.ru","api":"api.vk.ru","id":"id.vk.ru","login":"login.vk.ru","oauth":"oauth.vk.ru","domain":"vk.ru"},"auth":{"access_token":"","anonymous_token":"REDACTED","host_app_id":0,"auth_app_id":0,"user_id":0},"params":{"debug":false,"origin":"","localhost":false,"vkui_scheme":"","sdk_type":"sak","lang_id":5,"scheme_provider":"vkid"},"data":{"variant":"popup","domain":"vk.com","session_token":"REDACTED","autofocus":"","blank":"1","is_old_client":false,"show_captcha_type":"checkbox","captcha_settings":[{"type":"slider","settings":"REDACTED"},{"type":"sound","settings":"REDACTED"}],"platform":"web","captcha_id":"6b34b29d-5a4a-403c-bfe4-aa54a7b5f8c4","logo_enabled":true},"error":{"message":"App not available through VK ID sign-in","code":7,"additional_data":[]}};</script>
|
||||
</head><body><div id="spa_root"></div>
|
||||
<script>(function(_0x1be24c,_0x543e3e,_0x23e37e){const _0x445645=typeof window!=='undefined'&&!!window['crypto']&&!!window['crypto']['subtle']&&typeof window['crypto']['subtle']['digest']==='function';var _0x549a17=0x8;function _0x57b4b5(){var _0x6bef44={};function _0x2f6942(_0x311a3e,_0x18379a){try{_0x6bef44[_0x311a3e]={'ok':!![],'result':_0x18379a()};}catch(_0x544e57){_0x6bef44[_0x311a3e]={'ok':![],'error':'exception'};}}return _0x2f6942('globals',function(){return{'doc':typeof document==='object','win':typeof window==='object','nav':typeof navigator==='object','webdriver':!!navigator['webdriver'],'hw':navigator['hardwareConcurrency']||null,'mem':navigator['deviceMemory']||null};}),_0x2f6942('ua',function(){return{'userAgent':navigator['userAgent']||''};}),_0x2f6942('frame',function(){var _0x2a45d0=null,_0x5c6650=0x0,_0x51e2fb=![];try{_0x2a45d0=window['frameElement']?'set':null;}catch(_0xf4df71){}try{if(window['location']&&window['location']['ancestorOrigins'])_0x5c6650=window['location']['ancestorOrigins']['length'];}catch(_0x36b6d0){}try{var _0x42973f=window['parent'];if(_0x42973f&&_0x42973f['location']){var _0x5989be=_0x42973f['location']['href'];_0x51e2fb=!![];}}catch(_0x4469ea){}return{'frameElement':_0x2a45d0,'ancestorOriginsLen':_0x5c6650,'parentAccessible':_0x51e2fb};}),_0x2f6942('match_media',function(){return{'prefersDark':!!window['matchMedia']('(prefers-color-scheme:\x20dark)')['matches'],'prefersLight':!!window['matchMedia']('(prefers-color-scheme:\x20light)')['matches'],'reducedMotion':!!window['matchMedia']('(prefers-reduced-motion:\x20reduce)')['matches'],'pointerFine':!!window['matchMedia']('(pointer:\x20fine)')['matches']};}),_0x2f6942('plugins',function(){var _0xe02728=[];if(navigator['plugins'])for(var _0x454dbf=0x0;_0x454dbf<Math['min'](navigator['plugins']['length'],0x5);_0x454dbf++){_0xe02728['push'](navigator['plugins'][_0x454dbf]['name']);}var _0x2f1156=_0xe02728['some'](function(_0x2cbe8e){return String(_0x2cbe8e)['indexOf']('Chrome\x20PDF')>=0x0;});return{'length':navigator['plugins']?navigator['plugins']['length']:0x0,'names':_0xe02728,'isChrome':_0x2f1156};}),_0x2f6942('nav_tamper',function(){var _0x2629d5=![];try{var _0x1707fc=Object['getOwnPropertyDescriptor'](Navigator['prototype'],'userAgent');_0x2629d5=!!(_0x1707fc&&_0x1707fc['get']&&_0x1707fc['get']['toString']()['indexOf']('[native\x20code]')===-0x1);}catch(_0x43a2c1){}return{'tampered':_0x2629d5};}),_0x2f6942('referrer',function(){return{'referrer':document['referrer']||'','inIframe':window['self']!==window['top'],'domain':document['domain']||''};}),_0x2f6942('devtools',function(){var _0x301f35=![];try{var _0x37ccd9=performance['now']();debugger;_0x301f35=performance['now']()-_0x37ccd9>0x5;}catch(_0x4c99e4){}return{'open':_0x301f35};}),_0x2f6942('css',function(){var _0x4bd37e=0x0,_0x5d490e=['display:\x20grid','aspect-ratio:\x201\x20/\x201','container-type:\x20inline-size','selector(:has(*))','color:\x20oklch(40%\x200.4\x20200)'];for(var _0x3af6f8=0x0;_0x3af6f8<_0x5d490e['length'];_0x3af6f8++){try{if(!CSS['supports'](_0x5d490e[_0x3af6f8]))_0x4bd37e++;}catch(_0x58fa51){_0x4bd37e++;}}return{'expectedMissing':_0x4bd37e};}),_0x2f6942('native_integrity',function(){var _0x12e932=![],_0x5d78e9=![];try{var _0x4ea2d4=document['createElement']('div');_0x12e932=Object['getPrototypeOf'](_0x4ea2d4)===HTMLDivElement['prototype'];var _0x15f9cd=new XMLHttpRequest();_0x5d78e9=_0x15f9cd['toString']()['indexOf']('[object')>=0x0;}catch(_0x13d44f){}return{'protoMatch':_0x12e932,'xhrNative':_0x5d78e9};}),_0x6bef44;}function _0x265e99(_0x5bd15c){if(_0x5bd15c===null||_0x5bd15c===undefined)return'null';if(typeof _0x5bd15c!=='object')return JSON['stringify'](_0x5bd15c);if(Array['isArray'](_0x5bd15c))return'['+_0x5bd15c['map'](_0x265e99)['join'](',')+']';var _0x4de6ae=Object['keys'](_0x5bd15c)['filter'](function(_0x4b66e8){return _0x5bd15c[_0x4b66e8]!==undefined;})['sort']();return'{'+_0x4de6ae['map'](function(_0x429bc4){return JSON['stringify'](_0x429bc4)+':'+_0x265e99(_0x5bd15c[_0x429bc4]);})['join'](',')+'}';}function _0x2a1c54(_0x4b805f){var _0x36b593=JSON['stringify'](_0x4b805f)['replace'](/[^\x00-\x7F]/g,function(_0x32f54b){var _0x54d62c=_0x32f54b['charCodeAt'](0x0);return'\x5cu'+('0000'+_0x54d62c['toString'](0x10))['slice'](-0x4);});return btoa(_0x36b593);}function _0x50b9ee(_0x4337fb){function _0x309c22(_0x4902a0,_0x3468f1){return _0x4902a0>>>_0x3468f1|_0x4902a0<<0x20-_0x3468f1;}var _0x56dc78=[0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748Line truncated
|
||||
</body></html>
|
||||
@@ -0,0 +1,49 @@
|
||||
package vkauth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/samosvalishe/free-turn-proxy/internal/statedir"
|
||||
)
|
||||
|
||||
// PersonaStateFile - имя файла с поколением персоны рядом с client_config.json.
|
||||
const PersonaStateFile = "vk_persona.json"
|
||||
|
||||
// personaState переживает перезапуск: без него сожжённый отпечаток воскресает на
|
||||
// старте и VK каждый раз видит тот, что уже отверг. Seed фиксирует, чьё это
|
||||
// поколение - смена -client-id даёт новую личность и счётчик с нуля.
|
||||
type personaState struct {
|
||||
Seed string `json:"seed"`
|
||||
Gen int `json:"gen"`
|
||||
}
|
||||
|
||||
// genStore с пустым paths - no-op (тесты и хосты без записи на диск).
|
||||
type genStore struct {
|
||||
paths []string
|
||||
}
|
||||
|
||||
func (s genStore) load(seed string) int {
|
||||
for _, b := range statedir.ReadEach(s.paths) {
|
||||
var st personaState
|
||||
if json.Unmarshal(b, &st) == nil && st.Seed == seed && st.Gen > 0 {
|
||||
return st.Gen
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// save не понижает поколение: несколько vk.Provider (multi-link) делят один файл
|
||||
// и сжигают персоны независимо.
|
||||
func (s genStore) save(seed string, gen int) bool {
|
||||
if len(s.paths) == 0 {
|
||||
return false
|
||||
}
|
||||
if gen <= s.load(seed) {
|
||||
return true
|
||||
}
|
||||
b, err := json.Marshal(personaState{Seed: seed, Gen: gen})
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return statedir.WriteFirst(s.paths, b)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package vkauth
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func statePaths(t *testing.T) []string {
|
||||
t.Helper()
|
||||
return []string{filepath.Join(t.TempDir(), PersonaStateFile)}
|
||||
}
|
||||
|
||||
func TestBurnedPersonaSurvivesRestart(t *testing.T) {
|
||||
paths := statePaths(t)
|
||||
|
||||
c := New(Config{FingerprintSeed: "install-1", StatePaths: paths})
|
||||
burned := c.currentPersona()
|
||||
c.burnPersona(1)
|
||||
fresh := c.currentPersona()
|
||||
|
||||
restarted := New(Config{FingerprintSeed: "install-1", StatePaths: paths})
|
||||
if got := restarted.currentPersona(); got.VisitorID == burned.VisitorID {
|
||||
t.Fatal("restart resurrected the burned persona")
|
||||
} else if got.VisitorID != fresh.VisitorID {
|
||||
t.Fatal("restart did not continue from the persisted generation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersonaStateIsSeedScoped(t *testing.T) {
|
||||
paths := statePaths(t)
|
||||
|
||||
c := New(Config{FingerprintSeed: "install-1", StatePaths: paths})
|
||||
c.burnPersona(1)
|
||||
|
||||
other := New(Config{FingerprintSeed: "install-2", StatePaths: paths})
|
||||
if other.identity.Gen != 0 {
|
||||
t.Fatalf("gen = %d for a foreign seed, want 0", other.identity.Gen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersonaStateSurvivesCorruptFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
broken, good := filepath.Join(dir, "broken.json"), filepath.Join(dir, PersonaStateFile)
|
||||
if err := os.WriteFile(broken, []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(good, []byte(`{"seed":"install-1","gen":4}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
c := New(Config{FingerprintSeed: "install-1", StatePaths: []string{broken, good}})
|
||||
if c.identity.Gen != 4 {
|
||||
t.Fatalf("gen = %d, want 4", c.identity.Gen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenStoreKeepsHighestGen(t *testing.T) {
|
||||
s := genStore{paths: statePaths(t)}
|
||||
if !s.save("install-1", 3) || !s.save("install-1", 2) {
|
||||
t.Fatal("save reported failure")
|
||||
}
|
||||
if got := s.load("install-1"); got != 3 {
|
||||
t.Fatalf("gen = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenStoreWithoutPathsIsNoop(t *testing.T) {
|
||||
var s genStore
|
||||
if s.save("install-1", 1) || s.load("install-1") != 0 {
|
||||
t.Fatal("empty genStore touched state")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user