games_app/prediqo_mobile/lib/shared/widgets/turnstile_captcha.dart
2026-11-15 20:25:13 +02:00

233 lines
6.6 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../core/config/app_config.dart';
import '../../core/di/injection.dart';
/// Cloudflare Turnstile widget for native login (WebView + explicit render).
///
/// Delivers the token via JS channel, custom navigation callback, and a short
/// poll — Android `loadHtmlString` often drops JS-channel messages alone.
class TurnstileCaptcha extends StatefulWidget {
const TurnstileCaptcha({
super.key,
required this.siteKey,
required this.onToken,
});
final String siteKey;
final ValueChanged<String?> onToken;
@override
State<TurnstileCaptcha> createState() => _TurnstileCaptchaState();
}
class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
static const _bridgeHost = 'turnstile.bridge';
late final WebViewController _controller;
Timer? _pollTimer;
var _ready = false;
String? _lastEmitted;
@override
void initState() {
super.initState();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..addJavaScriptChannel(
'TurnstileBridge',
onMessageReceived: (message) => _emit(message.message),
)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (request) {
final uri = Uri.tryParse(request.url);
if (uri != null && uri.host == _bridgeHost) {
final raw = uri.fragment.isNotEmpty
? uri.fragment
: (uri.queryParameters['t'] ?? '');
final token = Uri.decodeComponent(raw);
_emit(token);
return NavigationDecision.prevent;
}
// Allow Turnstile assets + initial document only.
if (request.url.startsWith('https://challenges.cloudflare.com') ||
request.url.startsWith('about:') ||
request.url.startsWith('data:')) {
return NavigationDecision.navigate;
}
final base = Uri.tryParse(_baseUrl);
if (base != null &&
uri != null &&
uri.host == base.host &&
request.isMainFrame == false) {
return NavigationDecision.navigate;
}
if (base != null && uri != null && uri.host == base.host) {
return NavigationDecision.navigate;
}
return NavigationDecision.prevent;
},
onPageFinished: (_) {
if (mounted) setState(() => _ready = true);
_startPolling();
},
),
);
_load();
}
@override
void dispose() {
_pollTimer?.cancel();
super.dispose();
}
String get _baseUrl {
final api = Uri.tryParse(sl<AppConfig>().apiBaseUrl);
if (api != null &&
api.hasScheme &&
api.host.isNotEmpty &&
api.host != 'localhost' &&
api.host != '127.0.0.1' &&
api.host != '10.0.2.2') {
return '${api.scheme}://${api.host}/';
}
return '${AppConfig.defaultProductionApiBaseUrl}/';
}
void _emit(String? raw) {
final value = raw?.trim();
if (value == null ||
value.isEmpty ||
value == 'expired' ||
value == 'error' ||
value == 'null' ||
value == 'undefined') {
if (_lastEmitted != null) {
_lastEmitted = null;
widget.onToken(null);
}
return;
}
if (value == _lastEmitted) return;
_lastEmitted = value;
widget.onToken(value);
}
void _startPolling() {
_pollTimer?.cancel();
_pollTimer = Timer.periodic(const Duration(milliseconds: 400), (_) async {
if (!mounted || _lastEmitted != null) return;
try {
final result = await _controller.runJavaScriptReturningResult(
r'(window.__cfTurnstileToken || "")',
);
final raw = result.toString().replaceAll('"', '').trim();
if (raw.isNotEmpty) _emit(raw);
} catch (_) {
/* WebView not ready */
}
});
}
String _html(String siteKey) {
final escaped = const JsonEncoder().convert(siteKey);
return '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" async defer></script>
<style>
html, body {
margin: 0;
padding: 0;
background: transparent;
overflow: hidden;
}
#cf-turnstile { display: flex; justify-content: center; width: 100%; }
</style>
</head>
<body>
<div id="cf-turnstile"></div>
<script>
window.__cfTurnstileToken = '';
function notify(msg) {
var value = String(msg || '');
window.__cfTurnstileToken = value;
try { TurnstileBridge.postMessage(value); } catch (e) {}
try {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'https://$_bridgeHost/token#' + encodeURIComponent(value);
document.body.appendChild(iframe);
setTimeout(function () {
try { document.body.removeChild(iframe); } catch (e3) {}
}, 500);
} catch (e2) {}
}
function renderWhenReady() {
if (!window.turnstile) {
setTimeout(renderWhenReady, 50);
return;
}
window.turnstile.render('#cf-turnstile', {
sitekey: $escaped,
theme: 'auto',
callback: function (token) { notify(token); },
'expired-callback': function () { notify('expired'); },
'error-callback': function () { notify('error'); }
});
}
renderWhenReady();
</script>
</body>
</html>
''';
}
Future<void> _load() async {
_pollTimer?.cancel();
_lastEmitted = null;
widget.onToken(null);
if (mounted) setState(() => _ready = false);
await _controller.loadHtmlString(_html(widget.siteKey), baseUrl: _baseUrl);
}
@override
void didUpdateWidget(covariant TurnstileCaptcha oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.siteKey != widget.siteKey) {
_load();
}
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: 80,
width: double.infinity,
child: Stack(
alignment: Alignment.center,
children: [
WebViewWidget(controller: _controller),
if (!_ready)
const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2),
),
],
),
);
}
}