diff --git a/backend/src/controllers/authController.ts b/backend/src/controllers/authController.ts index 2fb8e81f..f315dcf1 100644 --- a/backend/src/controllers/authController.ts +++ b/backend/src/controllers/authController.ts @@ -82,13 +82,24 @@ export async function validateReferralCode(req: Request, res: Response): Promise } } +function preferMathCaptcha(req: Request): boolean { + const platform = String(req.headers['x-tloto-platform'] || '').toLowerCase(); + if (platform === 'android' || platform === 'ios') return true; + const prefer = String(req.query.prefer || '').toLowerCase(); + return prefer === 'math'; +} + /** * Public captcha configuration for the login form (Turnstile or built-in math). */ -export async function getCaptchaConfig(_req: Request, res: Response): Promise { +export async function getCaptchaConfig(req: Request, res: Response): Promise { const settings = await settingsRepository.getSettings(); const afterFailures = settings.login_captcha_after_failures; - const provider = captchaService.getCaptchaProvider(); + const preferMath = preferMathCaptcha(req); + const provider = + preferMath || captchaService.getCaptchaProvider() !== 'turnstile' + ? 'math' + : 'turnstile'; res.json({ enabled: captchaService.isCaptchaAvailable(afterFailures), provider, @@ -100,13 +111,15 @@ export async function getCaptchaConfig(_req: Request, res: Response): Promise { +export async function getCaptchaChallenge(req: Request, res: Response): Promise { const settings = await settingsRepository.getSettings(); if (!captchaService.isCaptchaAvailable(settings.login_captcha_after_failures)) { res.status(404).json({ error: 'Captcha is disabled' }); return; } - res.json(captchaService.createLoginCaptchaChallenge()); + res.json( + captchaService.createLoginCaptchaChallenge({ preferMath: preferMathCaptcha(req) }) + ); } /** @@ -121,11 +134,18 @@ export async function login(req: Request, res: Response): Promise { res.status(400).json({ error: 'Email and password required' }); return; } - const result = await authService.login(email, password, totpCode, { - ipAddress: req.ip || undefined, - userAgent: resolveClientUserAgent(req), - visitorSupportToken: readVisitorToken(req as AuthRequest), - }, captchaToken); + const result = await authService.login( + email, + password, + totpCode, + { + ipAddress: req.ip || undefined, + userAgent: resolveClientUserAgent(req), + visitorSupportToken: readVisitorToken(req as AuthRequest), + }, + captchaToken, + { preferMath: preferMathCaptcha(req) } + ); res.json(result); } catch (e) { const code = (e as { code?: string }).code; diff --git a/backend/src/services/authService.ts b/backend/src/services/authService.ts index ec655fe6..3f91bcd3 100644 --- a/backend/src/services/authService.ts +++ b/backend/src/services/authService.ts @@ -259,7 +259,8 @@ export async function login( password: string, totpCode?: string, auditContext?: { ipAddress?: string; userAgent?: string; visitorSupportToken?: string | null }, - captchaToken?: string + captchaToken?: string, + captchaOptions?: { preferMath?: boolean } ): Promise<{ accessToken: string; refreshToken: string; @@ -316,7 +317,9 @@ export async function login( try { await captchaService.verifyCaptchaToken(captchaToken, auditIp); } catch (e) { - throw captchaService.withCaptchaChallenge(e as Error & { code?: string }); + throw captchaService.withCaptchaChallenge(e as Error & { code?: string }, { + preferMath: captchaOptions?.preferMath === true, + }); } } diff --git a/backend/src/services/captchaService.ts b/backend/src/services/captchaService.ts index 64683806..d7a9657d 100644 --- a/backend/src/services/captchaService.ts +++ b/backend/src/services/captchaService.ts @@ -88,8 +88,15 @@ export function createMathChallenge(): CaptchaChallengePayload { }; } -export function createLoginCaptchaChallenge(): CaptchaChallengePayload { - if (getCaptchaProvider() === 'turnstile') { +export type CaptchaChallengeOptions = { + /** Native apps use signed math challenges; Turnstile WebViews are unreliable. */ + preferMath?: boolean; +}; + +export function createLoginCaptchaChallenge( + options?: CaptchaChallengeOptions +): CaptchaChallengePayload { + if (!options?.preferMath && getCaptchaProvider() === 'turnstile') { return { provider: 'turnstile', siteKey: getCaptchaSiteKey(), @@ -136,18 +143,10 @@ function verifyMathToken(token: string | undefined): void { } } -async function verifyTurnstileToken(token: string | undefined, remoteIp?: string): Promise { - if (!token?.trim()) { - throw captchaError('Captcha verification is required', 'CAPTCHA_REQUIRED'); - } - if (token.trim().startsWith('math:')) { - // Client sent math token while Turnstile is configured - throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID'); - } - +async function verifyTurnstileToken(token: string, remoteIp?: string): Promise { const body = new URLSearchParams({ secret: config.turnstile.secretKey, - response: token.trim(), + response: token, }); if (remoteIp) body.set('remoteip', remoteIp); @@ -167,24 +166,37 @@ async function verifyTurnstileToken(token: string | undefined, remoteIp?: string } } -/** Verifies login captcha using Turnstile or built-in math challenge. */ +/** + * Verifies login captcha. + * Signed math tokens are always accepted (mobile / fallback). Turnstile tokens + * are accepted when Turnstile is configured. + */ export async function verifyCaptchaToken( token: string | undefined, remoteIp?: string ): Promise { - if (getCaptchaProvider() === 'turnstile') { - await verifyTurnstileToken(token, remoteIp); + if (!token?.trim()) { + throw captchaError('Captcha verification is required', 'CAPTCHA_REQUIRED'); + } + const raw = token.trim(); + if (raw.startsWith('math:')) { + verifyMathToken(raw); return; } - verifyMathToken(token); + if (getCaptchaProvider() === 'turnstile') { + await verifyTurnstileToken(raw, remoteIp); + return; + } + throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID'); } /** Attach a fresh challenge to captcha errors for the client. */ export function withCaptchaChallenge( - err: T + err: T, + options?: CaptchaChallengeOptions ): T { if (err.code === 'CAPTCHA_REQUIRED' || err.code === 'CAPTCHA_INVALID') { - err.captcha = createLoginCaptchaChallenge(); + err.captcha = createLoginCaptchaChallenge(options); } return err; } diff --git a/prediqo_mobile/android/.kotlin/sessions/kotlin-compiler-3594783076671140387.salive b/prediqo_mobile/android/.kotlin/sessions/kotlin-compiler-3594783076671140387.salive deleted file mode 100644 index e69de29b..00000000 diff --git a/prediqo_mobile/lib/features/auth/presentation/login_screen.dart b/prediqo_mobile/lib/features/auth/presentation/login_screen.dart index 6d93dd0a..dd281442 100644 --- a/prediqo_mobile/lib/features/auth/presentation/login_screen.dart +++ b/prediqo_mobile/lib/features/auth/presentation/login_screen.dart @@ -5,6 +5,8 @@ import 'package:flutter/services.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; +import '../../../core/di/injection.dart'; +import '../../../core/network/api_client.dart'; import '../../../core/theme/app_colors.dart'; import '../../../l10n/app_strings.dart'; import '../../../shared/widgets/app_snackbar.dart'; @@ -13,7 +15,6 @@ import '../../../shared/widgets/pred_card.dart'; import '../../../shared/widgets/pred_text_field.dart'; import '../../../shared/widgets/prediqo_logo.dart'; import '../../../shared/widgets/tloto_gradient_app_bar.dart'; -import '../../../shared/widgets/turnstile_captcha.dart'; import '../../welcome/utils/welcome_navigation.dart'; import '../bloc/auth_bloc.dart'; @@ -38,13 +39,11 @@ class _LoginScreenState extends State { Timer? _bannerTimer; /// Local captcha UI state (survives AuthClearFeedback). + /// Mobile always uses the signed math challenge (Turnstile WebView is unreliable). bool _captchaRequired = false; - String? _captchaProvider; // 'math' | 'turnstile' String? _mathPrompt; String? _mathChallengeToken; - String? _turnstileSiteKey; - String? _turnstileToken; - int _turnstileRemountKey = 0; + bool _mathChallengeLoading = false; @override void initState() { @@ -71,51 +70,65 @@ class _LoginScreenState extends State { context.read().add(const AuthClearFeedback()); } - void _clearCaptchaUi({required bool remountTurnstile}) { + void _clearMathChallenge() { _mathPrompt = null; _mathChallengeToken = null; _mathAnswerController.clear(); - _turnstileToken = null; - if (remountTurnstile) { - _turnstileRemountKey++; - } } - void _applyCaptchaChallenge(Map? captcha) { + void _applyMathChallenge( + Map? captcha, { + bool allowRemoteFetch = true, + }) { final provider = captcha?['provider']?.toString(); final prompt = captcha?['prompt']?.toString(); final token = captcha?['challengeToken']?.toString(); - final siteKey = captcha?['siteKey']?.toString(); - setState(() { - _captchaRequired = true; - _clearCaptchaUi(remountTurnstile: provider == 'turnstile'); - if (provider == 'turnstile') { - _captchaProvider = 'turnstile'; - _turnstileSiteKey = - (siteKey != null && siteKey.isNotEmpty) ? siteKey : null; - return; - } - if (provider == 'math' && - prompt != null && - token != null && - token.isNotEmpty) { - _captchaProvider = 'math'; - _turnstileSiteKey = null; + if (provider == 'math' && + prompt != null && + prompt.isNotEmpty && + token != null && + token.isNotEmpty) { + setState(() { + _captchaRequired = true; + _mathChallengeLoading = false; _mathPrompt = prompt; _mathChallengeToken = token; - return; - } - // Keep any existing challenge when the error has no captcha payload. + _mathAnswerController.clear(); + }); + return; + } + // Turnstile (or empty) payload → fetch a signed math challenge for native. + setState(() { + _captchaRequired = true; + _clearMathChallenge(); + _mathChallengeLoading = allowRemoteFetch; }); + if (allowRemoteFetch) { + unawaited(_fetchMathChallenge()); + } + } + + Future _fetchMathChallenge() async { + try { + final res = await sl().dio.get>( + '/api/v1/auth/captcha-challenge', + queryParameters: const {'prefer': 'math'}, + ); + if (!mounted) return; + _applyMathChallenge(res.data, allowRemoteFetch: false); + if (_mathPrompt == null) { + setState(() => _mathChallengeLoading = false); + showErrorSnackBar(context, context.strings.captchaTurnstileUnavailable); + } + } catch (_) { + if (!mounted) return; + setState(() => _mathChallengeLoading = false); + showErrorSnackBar(context, context.strings.captchaTurnstileUnavailable); + } } String? _buildCaptchaToken() { if (!_captchaRequired) return null; - if (_captchaProvider == 'turnstile') { - final token = _turnstileToken?.trim(); - if (token == null || token.isEmpty) return null; - return token; - } final token = _mathChallengeToken; final answer = _mathAnswerController.text.trim(); if (token == null || token.isEmpty || answer.isEmpty) return null; @@ -132,9 +145,14 @@ class _LoginScreenState extends State { showErrorSnackBar(context, s.loginFieldsRequired); return; } + if (_captchaRequired && _mathChallengeLoading) { + showErrorSnackBar(context, s.captchaMathHelper); + return; + } final captchaToken = _buildCaptchaToken(); if (_captchaRequired && (captchaToken == null || captchaToken.isEmpty)) { - showErrorSnackBar(context, s.captchaTurnstileHelper); + showErrorSnackBar(context, s.captchaMathHelper); + if (_mathPrompt == null) unawaited(_fetchMathChallenge()); return; } setState(() => _verifyBanner = null); @@ -187,9 +205,8 @@ class _LoginScreenState extends State { setState(() { _verifyBanner = null; _captchaRequired = false; - _captchaProvider = null; - _turnstileSiteKey = null; - _clearCaptchaUi(remountTurnstile: false); + _mathChallengeLoading = false; + _clearMathChallenge(); }); _consumeFeedback(); context.go('/home'); @@ -218,10 +235,8 @@ class _LoginScreenState extends State { state.errorMessage != null) { final msg = state.errorMessage! .replaceFirst('Exception: ', ''); - if (state.isCaptchaChallenge) { - _applyCaptchaChallenge(state.captcha); - } else if (_captchaRequired) { - _applyCaptchaChallenge(state.captcha); + if (state.isCaptchaChallenge || _captchaRequired) { + _applyMathChallenge(state.captcha); } if (state.isEmailNotVerified) { setState(() => _verifyBanner = msg); @@ -396,43 +411,20 @@ class _LoginScreenState extends State { loading ? null : (_) => _submitLogin(), ), if (_captchaRequired && - _captchaProvider == 'turnstile') ...[ + _mathChallengeLoading) ...[ const SizedBox(height: 14), - Text( - s.captchaTurnstileHelper, - style: Theme.of(context) - .textTheme - .bodySmall, - ), - const SizedBox(height: 8), - if (_turnstileSiteKey != null) - TurnstileCaptcha( - key: ValueKey( - 'login_turnstile_$_turnstileRemountKey', + const Center( + child: SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2, ), - siteKey: _turnstileSiteKey!, - onToken: (token) { - if (!mounted) return; - setState( - () => _turnstileToken = token, - ); - }, - ) - else - Text( - s.captchaTurnstileUnavailable, - style: Theme.of(context) - .textTheme - .bodySmall - ?.copyWith( - color: Theme.of(context) - .colorScheme - .error, - ), ), + ), ], if (_captchaRequired && - _captchaProvider == 'math' && + !_mathChallengeLoading && _mathPrompt != null) ...[ const SizedBox(height: 14), PredTextField( diff --git a/prediqo_mobile/lib/shared/widgets/turnstile_captcha.dart b/prediqo_mobile/lib/shared/widgets/turnstile_captcha.dart index e2ce62cc..7dceac5d 100644 --- a/prediqo_mobile/lib/shared/widgets/turnstile_captcha.dart +++ b/prediqo_mobile/lib/shared/widgets/turnstile_captcha.dart @@ -1,3 +1,6 @@ +import 'dart:async'; +import 'dart:convert'; + import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; @@ -5,6 +8,9 @@ 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, @@ -20,36 +26,69 @@ class TurnstileCaptcha extends StatefulWidget { } class _TurnstileCaptchaState extends State { + 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(Colors.transparent) + ..setBackgroundColor(const Color(0x00000000)) ..addJavaScriptChannel( 'TurnstileBridge', - onMessageReceived: (message) { - final raw = message.message.trim(); - if (raw.isEmpty || raw == 'expired' || raw == 'error') { - widget.onToken(null); - return; - } - widget.onToken(raw); - }, + 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().apiBaseUrl); if (api != null && @@ -57,14 +96,49 @@ class _TurnstileCaptchaState extends State { api.host.isNotEmpty && api.host != 'localhost' && api.host != '127.0.0.1' && - !api.host.startsWith('10.0.2.2')) { + 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 = siteKey.replaceAll("'", r"\'"); + final escaped = const JsonEncoder().convert(siteKey); return ''' @@ -79,14 +153,26 @@ class _TurnstileCaptchaState extends State { background: transparent; overflow: hidden; } - #cf-turnstile { display: flex; justify-content: center; } + #cf-turnstile { display: flex; justify-content: center; width: 100%; }