feat: отпилил костыли с ручным обходом капчи
This commit is contained in:
1 parent
dba7a48097
commit
ec8f94166d
7 files changed
+2
-363
No files matched your search
@@ -35,7 +35,6 @@ import kotlinx.coroutines.withContext
|
||||
sealed class StartupResult {
|
||||
data object Success : StartupResult()
|
||||
data class Failed(val message: String) : StartupResult()
|
||||
data class Captcha(val url: String) : StartupResult()
|
||||
}
|
||||
|
||||
class ProxyService : Service() {
|
||||
@@ -47,10 +46,7 @@ class ProxyService : Service() {
|
||||
val logs = MutableStateFlow<List<String>>(emptyList())
|
||||
val proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
|
||||
val startupResult = MutableStateFlow<StartupResult?>(null)
|
||||
val captchaUrl = MutableStateFlow<String?>(null)
|
||||
private val processStdin = AtomicReference<java.io.OutputStream?>(null)
|
||||
|
||||
private val REDIRECT_URI_REGEX = Regex("""redirect_uri:(https?://\S+)""")
|
||||
|
||||
fun addLog(msg: String) {
|
||||
logs.update { current ->
|
||||
@@ -63,21 +59,6 @@ class ProxyService : Service() {
|
||||
logs.value = emptyList()
|
||||
}
|
||||
|
||||
fun clearCaptcha() {
|
||||
captchaUrl.value = null
|
||||
}
|
||||
|
||||
fun sendSuccessToken(token: String) {
|
||||
processStdin.get()?.let { stdin ->
|
||||
try {
|
||||
stdin.write("$token\n".toByteArray())
|
||||
stdin.flush()
|
||||
addLog(">>> Отправляем success_token в процесс")
|
||||
} catch (e: Exception) {
|
||||
addLog("Ошибка отправки токена: ${e.message}")
|
||||
}
|
||||
} ?: addLog("Ошибка: stdin процесса недоступен")
|
||||
}
|
||||
}
|
||||
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
@@ -179,7 +160,6 @@ class ProxyService : Service() {
|
||||
val startedAt = System.currentTimeMillis()
|
||||
var startupEmitted = false
|
||||
var startupFailed = false
|
||||
var captchaDetected = false
|
||||
try {
|
||||
addLog("Команда: ${cmdArgs.joinToString(" ")}")
|
||||
|
||||
@@ -189,7 +169,6 @@ class ProxyService : Service() {
|
||||
.start()
|
||||
}
|
||||
process.set(proc)
|
||||
processStdin.set(proc.outputStream)
|
||||
|
||||
BufferedReader(InputStreamReader(proc.inputStream)).use { reader ->
|
||||
var line: String?
|
||||
@@ -197,26 +176,6 @@ class ProxyService : Service() {
|
||||
val l = line ?: continue
|
||||
addLog(l)
|
||||
|
||||
// Детекция капчи: ищем redirect_uri в выводе бинарника
|
||||
if (l.lowercase().contains("captcha")) {
|
||||
val match = REDIRECT_URI_REGEX.find(l)
|
||||
if (match != null && !captchaDetected) {
|
||||
captchaUrl.value = match.groupValues[1]
|
||||
addLog(">>> ОБНАРУЖЕНА КАПЧА — ожидаем токен через stdin")
|
||||
startupResult.value = StartupResult.Captcha(match.groupValues[1])
|
||||
updateNotification("VK TURN Proxy", "Требуется капча")
|
||||
captchaDetected = true
|
||||
// НЕ убиваем процесс — Go ждёт success_token из stdin
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// После капчи: если токен уже принят и captcha сброшена — снова ловим startup
|
||||
if (captchaDetected && captchaUrl.value == null) {
|
||||
captchaDetected = false
|
||||
startupEmitted = false
|
||||
}
|
||||
|
||||
// P2-1: сигнализируем результат запуска по первой строке stdout
|
||||
if (!startupEmitted) {
|
||||
val lower = l.lowercase()
|
||||
@@ -262,18 +221,12 @@ class ProxyService : Service() {
|
||||
} catch (e: Exception) {
|
||||
addLog("КРИТИЧЕСКАЯ ОШИБКА: ${e.message}")
|
||||
} finally {
|
||||
processStdin.set(null)
|
||||
process.set(null)
|
||||
when {
|
||||
userStopped.get() -> {
|
||||
isRunning.value = false
|
||||
stopSelf()
|
||||
}
|
||||
captchaDetected -> {
|
||||
addLog("=== Ожидание прохождения капчи ===")
|
||||
isRunning.value = false
|
||||
stopSelf()
|
||||
}
|
||||
startupFailed -> {
|
||||
addLog("=== Ошибка при запуске, watchdog не активирован ===")
|
||||
isRunning.value = false
|
||||
|
||||
@@ -42,14 +42,6 @@ class LocalProxyManager(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun observeCaptchaEvents() {
|
||||
ProxyService.captchaUrl.collect { url ->
|
||||
if (url != null) {
|
||||
_proxyState.value = ProxyState.CaptchaRequired(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun observeProxyServiceStatus() {
|
||||
ProxyService.isRunning.collect { running ->
|
||||
if (!running && _proxyState.value == ProxyState.Running) {
|
||||
@@ -93,10 +85,6 @@ class LocalProxyManager(private val context: Context) {
|
||||
stopProxy()
|
||||
setErrorWithAutoReset(result.message)
|
||||
}
|
||||
is StartupResult.Captcha -> {
|
||||
// НЕ останавливаем — процесс ждёт токен из stdin
|
||||
_proxyState.value = ProxyState.CaptchaRequired(result.url)
|
||||
}
|
||||
is StartupResult.Success -> _proxyState.value = ProxyState.Running
|
||||
}
|
||||
}
|
||||
@@ -115,32 +103,6 @@ class LocalProxyManager(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun onCaptchaSolved(cfg: ClientConfig, successToken: String?) {
|
||||
ProxyService.clearCaptcha()
|
||||
|
||||
if (successToken != null && ProxyService.isRunning.value) {
|
||||
// Процесс жив — шлём токен через stdin, он сам продолжит
|
||||
_proxyState.value = ProxyState.Starting
|
||||
ProxyService.startupResult.value = null
|
||||
ProxyService.sendSuccessToken(successToken)
|
||||
|
||||
val result = withTimeoutOrNull(15_000L) {
|
||||
ProxyService.startupResult.filterNotNull().first()
|
||||
}
|
||||
when (result) {
|
||||
null -> { stopProxy(); setErrorWithAutoReset("Нет ответа после капчи") }
|
||||
is StartupResult.Failed -> { stopProxy(); setErrorWithAutoReset(result.message) }
|
||||
is StartupResult.Captcha -> _proxyState.value = ProxyState.CaptchaRequired(result.url)
|
||||
is StartupResult.Success -> _proxyState.value = ProxyState.Running
|
||||
}
|
||||
} else {
|
||||
// Процесс уже упал — перезапускаем
|
||||
_proxyState.value = ProxyState.Idle
|
||||
delay(1500)
|
||||
startProxy(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setCustomKernel(uri: Uri) = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val dest = File(context.filesDir, "custom_vkturn")
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package com.freeturn.app.ui.screens
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Bitmap
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
fun CaptchaWebViewDialog(
|
||||
captchaUrl: String,
|
||||
onCaptchaSolved: (successToken: String?) -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
var isLoading by remember { mutableStateOf(true) }
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(
|
||||
usePlatformDefaultWidth = false,
|
||||
dismissOnBackPress = true,
|
||||
dismissOnClickOutside = false
|
||||
)
|
||||
) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {
|
||||
Column {
|
||||
Text(
|
||||
"Проверка VK",
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
Text(
|
||||
"Пройдите проверку и прокси перезапустится",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text("Отмена", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
TextButton(onClick = { onCaptchaSolved(null) }) {
|
||||
Text("Готово")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
) {
|
||||
AndroidView(
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
|
||||
settings.apply {
|
||||
javaScriptEnabled = true
|
||||
domStorageEnabled = true
|
||||
useWideViewPort = true
|
||||
loadWithOverviewMode = true
|
||||
setSupportZoom(true)
|
||||
builtInZoomControls = true
|
||||
displayZoomControls = false
|
||||
setSupportMultipleWindows(true)
|
||||
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
||||
userAgentString = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36"
|
||||
}
|
||||
|
||||
// Включаем cookies — VK использует их для трекинга прохождения капчи
|
||||
val webViewRef = this
|
||||
CookieManager.getInstance().apply {
|
||||
setAcceptCookie(true)
|
||||
setAcceptThirdPartyCookies(webViewRef, true)
|
||||
}
|
||||
|
||||
addJavascriptInterface(object {
|
||||
@android.webkit.JavascriptInterface
|
||||
fun onToken(token: String) {
|
||||
android.util.Log.d("CaptchaWV", "onToken: $token")
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
onCaptchaSolved(if (token == "closed" || token == "null") null else token)
|
||||
}
|
||||
}
|
||||
@android.webkit.JavascriptInterface
|
||||
fun onDebug(msg: String) {
|
||||
android.util.Log.d("CaptchaWV", "JS: $msg")
|
||||
}
|
||||
}, "AndroidCaptcha")
|
||||
|
||||
// Перехват XHR и fetch — ловим success_token из ответов VK API
|
||||
val openerScript = """
|
||||
(function() {
|
||||
function tryExtract(text) {
|
||||
try {
|
||||
var d = typeof text === 'string' ? JSON.parse(text) : text;
|
||||
var token = d.success_token
|
||||
|| (d.data && d.data.success_token)
|
||||
|| (d.payload && d.payload.success_token)
|
||||
|| (d.response && d.response.success_token)
|
||||
|| null;
|
||||
if (token) {
|
||||
AndroidCaptcha.onDebug('token found: ' + token.substring(0, 20));
|
||||
AndroidCaptcha.onToken(token);
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
// Перехват XHR
|
||||
var _open = XMLHttpRequest.prototype.open;
|
||||
var _send = XMLHttpRequest.prototype.send;
|
||||
XMLHttpRequest.prototype.open = function(m, url) {
|
||||
this._xUrl = url;
|
||||
return _open.apply(this, arguments);
|
||||
};
|
||||
XMLHttpRequest.prototype.send = function() {
|
||||
this.addEventListener('load', function() {
|
||||
AndroidCaptcha.onDebug('XHR ' + this._xUrl + ' => ' + (this.responseText||'').substring(0, 120));
|
||||
tryExtract(this.responseText);
|
||||
});
|
||||
return _send.apply(this, arguments);
|
||||
};
|
||||
|
||||
// Перехват fetch
|
||||
var _fetch = window.fetch;
|
||||
window.fetch = function(input, init) {
|
||||
return _fetch.apply(this, arguments).then(function(resp) {
|
||||
var clone = resp.clone();
|
||||
clone.text().then(function(t) {
|
||||
AndroidCaptcha.onDebug('fetch ' + input + ' => ' + t.substring(0, 120));
|
||||
tryExtract(t);
|
||||
}).catch(function(){});
|
||||
return resp;
|
||||
});
|
||||
};
|
||||
|
||||
// window.opener как запасной вариант
|
||||
window.opener = {
|
||||
postMessage: function(data, origin) {
|
||||
try {
|
||||
var d = typeof data === 'string' ? JSON.parse(data) : data;
|
||||
AndroidCaptcha.onDebug('opener.pm: ' + JSON.stringify(d).substring(0, 120));
|
||||
tryExtract(d);
|
||||
} catch(e) {}
|
||||
}
|
||||
};
|
||||
window.close = function() {
|
||||
AndroidCaptcha.onDebug('window.close');
|
||||
AndroidCaptcha.onToken('closed');
|
||||
};
|
||||
window.addEventListener('message', function(e) {
|
||||
AndroidCaptcha.onDebug('msg ' + e.origin + ': ' + JSON.stringify(e.data).substring(0,120));
|
||||
tryExtract(e.data);
|
||||
});
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
|
||||
WebViewCompat.addDocumentStartJavaScript(this, openerScript, setOf("*"))
|
||||
}
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
isLoading = true
|
||||
android.util.Log.d("CaptchaWV", "start: $url")
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
isLoading = false
|
||||
android.util.Log.d("CaptchaWV", "finish: $url")
|
||||
// Фолбэк если DOCUMENT_START_SCRIPT не поддерживается
|
||||
if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
|
||||
view?.evaluateJavascript(openerScript, null)
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
request: WebResourceRequest?
|
||||
): Boolean {
|
||||
val url = request?.url ?: return false
|
||||
android.util.Log.d("CaptchaWV", "nav: $url")
|
||||
val token = url.getQueryParameter("success_token")
|
||||
if (token != null) {
|
||||
android.util.Log.d("CaptchaWV", "token in url: $token")
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
onCaptchaSolved(token)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
loadUrl(captchaUrl)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
|
||||
if (isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.align(Alignment.Center)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,14 +195,12 @@ fun HomeScreen(
|
||||
is ProxyState.Running -> stringResource(R.string.proxy_active)
|
||||
is ProxyState.Starting -> stringResource(R.string.proxy_connecting)
|
||||
is ProxyState.Error -> (proxyState as ProxyState.Error).message
|
||||
is ProxyState.CaptchaRequired -> "Требуется прохождение капчи"
|
||||
else -> stringResource(R.string.proxy_press_to_start)
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = when (proxyState) {
|
||||
is ProxyState.Running -> StatusGreen
|
||||
is ProxyState.Error -> MaterialTheme.colorScheme.error
|
||||
is ProxyState.CaptchaRequired -> MaterialTheme.colorScheme.error
|
||||
else -> MaterialTheme.colorScheme.onBackground.copy(alpha = 0.65f)
|
||||
},
|
||||
textAlign = TextAlign.Center
|
||||
@@ -292,14 +290,6 @@ fun HomeScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// Диалог капчи VK
|
||||
if (proxyState is ProxyState.CaptchaRequired) {
|
||||
CaptchaWebViewDialog(
|
||||
captchaUrl = (proxyState as ProxyState.CaptchaRequired).url,
|
||||
onCaptchaSolved = { token -> viewModel.onCaptchaSolved(token) },
|
||||
onDismiss = { viewModel.dismissCaptcha() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -23,5 +23,4 @@ sealed class ProxyState {
|
||||
object Starting : ProxyState()
|
||||
object Running : ProxyState()
|
||||
data class Error(val message: String) : ProxyState()
|
||||
data class CaptchaRequired(val url: String) : ProxyState()
|
||||
}
|
||||
@@ -51,9 +51,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
viewModelScope.launch {
|
||||
proxyManager.observeProxyServiceStatus()
|
||||
}
|
||||
viewModelScope.launch {
|
||||
proxyManager.observeCaptchaEvents()
|
||||
}
|
||||
proxyManager.syncInitialState()
|
||||
}
|
||||
|
||||
@@ -154,17 +151,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
proxyManager.stopProxy()
|
||||
}
|
||||
|
||||
fun onCaptchaSolved(successToken: String?) {
|
||||
viewModelScope.launch {
|
||||
proxyManager.onCaptchaSolved(clientConfig.value, successToken)
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissCaptcha() {
|
||||
ProxyService.clearCaptcha()
|
||||
proxyManager.stopProxy()
|
||||
}
|
||||
|
||||
fun clearLogs() {
|
||||
ProxyService.clearLogs()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user