After configuring captcha1

This commit is contained in:
Your Name 2026-11-15 20:25:13 +02:00
parent 7459263fb4
commit aea87f2dbb
6 changed files with 235 additions and 120 deletions

View File

@ -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<void> {
export async function getCaptchaConfig(req: Request, res: Response): Promise<void> {
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<vo
/**
* Issues a fresh captcha challenge (math prompt, or Turnstile site key hint).
*/
export async function getCaptchaChallenge(_req: Request, res: Response): Promise<void> {
export async function getCaptchaChallenge(req: Request, res: Response): Promise<void> {
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<void> {
res.status(400).json({ error: 'Email and password required' });
return;
}
const result = await authService.login(email, password, totpCode, {
const result = await authService.login(
email,
password,
totpCode,
{
ipAddress: req.ip || undefined,
userAgent: resolveClientUserAgent(req),
visitorSupportToken: readVisitorToken(req as AuthRequest),
}, captchaToken);
},
captchaToken,
{ preferMath: preferMathCaptcha(req) }
);
res.json(result);
} catch (e) {
const code = (e as { code?: string }).code;

View File

@ -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,
});
}
}

View File

@ -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<void> {
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<void> {
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<void> {
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<T extends Error & { code?: string; captcha?: CaptchaChallengePayload }>(
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;
}

View File

@ -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<LoginScreen> {
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<LoginScreen> {
context.read<AuthBloc>().add(const AuthClearFeedback());
}
void _clearCaptchaUi({required bool remountTurnstile}) {
void _clearMathChallenge() {
_mathPrompt = null;
_mathChallengeToken = null;
_mathAnswerController.clear();
_turnstileToken = null;
if (remountTurnstile) {
_turnstileRemountKey++;
}
}
void _applyCaptchaChallenge(Map<String, dynamic>? captcha) {
void _applyMathChallenge(
Map<String, dynamic>? 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 &&
prompt.isNotEmpty &&
token != null &&
token.isNotEmpty) {
_captchaProvider = 'math';
_turnstileSiteKey = null;
setState(() {
_captchaRequired = true;
_mathChallengeLoading = false;
_mathPrompt = prompt;
_mathChallengeToken = token;
_mathAnswerController.clear();
});
return;
}
// Keep any existing challenge when the error has no captcha payload.
// Turnstile (or empty) payload → fetch a signed math challenge for native.
setState(() {
_captchaRequired = true;
_clearMathChallenge();
_mathChallengeLoading = allowRemoteFetch;
});
if (allowRemoteFetch) {
unawaited(_fetchMathChallenge());
}
}
Future<void> _fetchMathChallenge() async {
try {
final res = await sl<ApiClient>().dio.get<Map<String, dynamic>>(
'/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<LoginScreen> {
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<LoginScreen> {
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<LoginScreen> {
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<LoginScreen> {
loading ? null : (_) => _submitLogin(),
),
if (_captchaRequired &&
_captchaProvider == 'turnstile') ...[
_mathChallengeLoading) ...[
const SizedBox(height: 14),
Text(
s.captchaTurnstileHelper,
style: Theme.of(context)
.textTheme
.bodySmall,
const Center(
child: SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
),
const SizedBox(height: 8),
if (_turnstileSiteKey != null)
TurnstileCaptcha(
key: ValueKey(
'login_turnstile_$_turnstileRemountKey',
),
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(

View File

@ -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<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(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<AppConfig>().apiBaseUrl);
if (api != null &&
@ -57,14 +96,49 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
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 '''
<!DOCTYPE html>
<html>
@ -79,14 +153,26 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
background: transparent;
overflow: hidden;
}
#cf-turnstile { display: flex; justify-content: center; }
#cf-turnstile { display: flex; justify-content: center; width: 100%; }
</style>
</head>
<body>
<div id="cf-turnstile"></div>
<script>
window.__cfTurnstileToken = '';
function notify(msg) {
try { TurnstileBridge.postMessage(String(msg)); } catch (e) {}
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) {
@ -94,7 +180,7 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
return;
}
window.turnstile.render('#cf-turnstile', {
sitekey: '$escaped',
sitekey: $escaped,
theme: 'auto',
callback: function (token) { notify(token); },
'expired-callback': function () { notify('expired'); },
@ -109,7 +195,10 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
}
Future<void> _load() async {
_pollTimer?.cancel();
_lastEmitted = null;
widget.onToken(null);
if (mounted) setState(() => _ready = false);
await _controller.loadHtmlString(_html(widget.siteKey), baseUrl: _baseUrl);
}
@ -117,7 +206,6 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
void didUpdateWidget(covariant TurnstileCaptcha oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.siteKey != widget.siteKey) {
setState(() => _ready = false);
_load();
}
}
@ -125,7 +213,7 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
@override
Widget build(BuildContext context) {
return SizedBox(
height: 72,
height: 80,
width: double.infinity,
child: Stack(
alignment: Alignment.center,