After configuring captcha1
This commit is contained in:
parent
7459263fb4
commit
aea87f2dbb
@ -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).
|
* 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 settings = await settingsRepository.getSettings();
|
||||||
const afterFailures = settings.login_captcha_after_failures;
|
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({
|
res.json({
|
||||||
enabled: captchaService.isCaptchaAvailable(afterFailures),
|
enabled: captchaService.isCaptchaAvailable(afterFailures),
|
||||||
provider,
|
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).
|
* 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();
|
const settings = await settingsRepository.getSettings();
|
||||||
if (!captchaService.isCaptchaAvailable(settings.login_captcha_after_failures)) {
|
if (!captchaService.isCaptchaAvailable(settings.login_captcha_after_failures)) {
|
||||||
res.status(404).json({ error: 'Captcha is disabled' });
|
res.status(404).json({ error: 'Captcha is disabled' });
|
||||||
return;
|
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' });
|
res.status(400).json({ error: 'Email and password required' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await authService.login(email, password, totpCode, {
|
const result = await authService.login(
|
||||||
ipAddress: req.ip || undefined,
|
email,
|
||||||
userAgent: resolveClientUserAgent(req),
|
password,
|
||||||
visitorSupportToken: readVisitorToken(req as AuthRequest),
|
totpCode,
|
||||||
}, captchaToken);
|
{
|
||||||
|
ipAddress: req.ip || undefined,
|
||||||
|
userAgent: resolveClientUserAgent(req),
|
||||||
|
visitorSupportToken: readVisitorToken(req as AuthRequest),
|
||||||
|
},
|
||||||
|
captchaToken,
|
||||||
|
{ preferMath: preferMathCaptcha(req) }
|
||||||
|
);
|
||||||
res.json(result);
|
res.json(result);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const code = (e as { code?: string }).code;
|
const code = (e as { code?: string }).code;
|
||||||
|
|||||||
@ -259,7 +259,8 @@ export async function login(
|
|||||||
password: string,
|
password: string,
|
||||||
totpCode?: string,
|
totpCode?: string,
|
||||||
auditContext?: { ipAddress?: string; userAgent?: string; visitorSupportToken?: string | null },
|
auditContext?: { ipAddress?: string; userAgent?: string; visitorSupportToken?: string | null },
|
||||||
captchaToken?: string
|
captchaToken?: string,
|
||||||
|
captchaOptions?: { preferMath?: boolean }
|
||||||
): Promise<{
|
): Promise<{
|
||||||
accessToken: string;
|
accessToken: string;
|
||||||
refreshToken: string;
|
refreshToken: string;
|
||||||
@ -316,7 +317,9 @@ export async function login(
|
|||||||
try {
|
try {
|
||||||
await captchaService.verifyCaptchaToken(captchaToken, auditIp);
|
await captchaService.verifyCaptchaToken(captchaToken, auditIp);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw captchaService.withCaptchaChallenge(e as Error & { code?: string });
|
throw captchaService.withCaptchaChallenge(e as Error & { code?: string }, {
|
||||||
|
preferMath: captchaOptions?.preferMath === true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -88,8 +88,15 @@ export function createMathChallenge(): CaptchaChallengePayload {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createLoginCaptchaChallenge(): CaptchaChallengePayload {
|
export type CaptchaChallengeOptions = {
|
||||||
if (getCaptchaProvider() === 'turnstile') {
|
/** Native apps use signed math challenges; Turnstile WebViews are unreliable. */
|
||||||
|
preferMath?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createLoginCaptchaChallenge(
|
||||||
|
options?: CaptchaChallengeOptions
|
||||||
|
): CaptchaChallengePayload {
|
||||||
|
if (!options?.preferMath && getCaptchaProvider() === 'turnstile') {
|
||||||
return {
|
return {
|
||||||
provider: 'turnstile',
|
provider: 'turnstile',
|
||||||
siteKey: getCaptchaSiteKey(),
|
siteKey: getCaptchaSiteKey(),
|
||||||
@ -136,18 +143,10 @@ function verifyMathToken(token: string | undefined): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function verifyTurnstileToken(token: string | undefined, remoteIp?: string): Promise<void> {
|
async function verifyTurnstileToken(token: string, 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');
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = new URLSearchParams({
|
const body = new URLSearchParams({
|
||||||
secret: config.turnstile.secretKey,
|
secret: config.turnstile.secretKey,
|
||||||
response: token.trim(),
|
response: token,
|
||||||
});
|
});
|
||||||
if (remoteIp) body.set('remoteip', remoteIp);
|
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(
|
export async function verifyCaptchaToken(
|
||||||
token: string | undefined,
|
token: string | undefined,
|
||||||
remoteIp?: string
|
remoteIp?: string
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (getCaptchaProvider() === 'turnstile') {
|
if (!token?.trim()) {
|
||||||
await verifyTurnstileToken(token, remoteIp);
|
throw captchaError('Captcha verification is required', 'CAPTCHA_REQUIRED');
|
||||||
|
}
|
||||||
|
const raw = token.trim();
|
||||||
|
if (raw.startsWith('math:')) {
|
||||||
|
verifyMathToken(raw);
|
||||||
return;
|
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. */
|
/** Attach a fresh challenge to captcha errors for the client. */
|
||||||
export function withCaptchaChallenge<T extends Error & { code?: string; captcha?: CaptchaChallengePayload }>(
|
export function withCaptchaChallenge<T extends Error & { code?: string; captcha?: CaptchaChallengePayload }>(
|
||||||
err: T
|
err: T,
|
||||||
|
options?: CaptchaChallengeOptions
|
||||||
): T {
|
): T {
|
||||||
if (err.code === 'CAPTCHA_REQUIRED' || err.code === 'CAPTCHA_INVALID') {
|
if (err.code === 'CAPTCHA_REQUIRED' || err.code === 'CAPTCHA_INVALID') {
|
||||||
err.captcha = createLoginCaptchaChallenge();
|
err.captcha = createLoginCaptchaChallenge(options);
|
||||||
}
|
}
|
||||||
return err;
|
return err;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,6 +5,8 @@ import 'package:flutter/services.dart';
|
|||||||
import 'package:flutter_animate/flutter_animate.dart';
|
import 'package:flutter_animate/flutter_animate.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:go_router/go_router.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 '../../../core/theme/app_colors.dart';
|
||||||
import '../../../l10n/app_strings.dart';
|
import '../../../l10n/app_strings.dart';
|
||||||
import '../../../shared/widgets/app_snackbar.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/pred_text_field.dart';
|
||||||
import '../../../shared/widgets/prediqo_logo.dart';
|
import '../../../shared/widgets/prediqo_logo.dart';
|
||||||
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||||
import '../../../shared/widgets/turnstile_captcha.dart';
|
|
||||||
import '../../welcome/utils/welcome_navigation.dart';
|
import '../../welcome/utils/welcome_navigation.dart';
|
||||||
import '../bloc/auth_bloc.dart';
|
import '../bloc/auth_bloc.dart';
|
||||||
|
|
||||||
@ -38,13 +39,11 @@ class _LoginScreenState extends State<LoginScreen> {
|
|||||||
Timer? _bannerTimer;
|
Timer? _bannerTimer;
|
||||||
|
|
||||||
/// Local captcha UI state (survives AuthClearFeedback).
|
/// Local captcha UI state (survives AuthClearFeedback).
|
||||||
|
/// Mobile always uses the signed math challenge (Turnstile WebView is unreliable).
|
||||||
bool _captchaRequired = false;
|
bool _captchaRequired = false;
|
||||||
String? _captchaProvider; // 'math' | 'turnstile'
|
|
||||||
String? _mathPrompt;
|
String? _mathPrompt;
|
||||||
String? _mathChallengeToken;
|
String? _mathChallengeToken;
|
||||||
String? _turnstileSiteKey;
|
bool _mathChallengeLoading = false;
|
||||||
String? _turnstileToken;
|
|
||||||
int _turnstileRemountKey = 0;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@ -71,51 +70,65 @@ class _LoginScreenState extends State<LoginScreen> {
|
|||||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||||
}
|
}
|
||||||
|
|
||||||
void _clearCaptchaUi({required bool remountTurnstile}) {
|
void _clearMathChallenge() {
|
||||||
_mathPrompt = null;
|
_mathPrompt = null;
|
||||||
_mathChallengeToken = null;
|
_mathChallengeToken = null;
|
||||||
_mathAnswerController.clear();
|
_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 provider = captcha?['provider']?.toString();
|
||||||
final prompt = captcha?['prompt']?.toString();
|
final prompt = captcha?['prompt']?.toString();
|
||||||
final token = captcha?['challengeToken']?.toString();
|
final token = captcha?['challengeToken']?.toString();
|
||||||
final siteKey = captcha?['siteKey']?.toString();
|
if (provider == 'math' &&
|
||||||
setState(() {
|
prompt != null &&
|
||||||
_captchaRequired = true;
|
prompt.isNotEmpty &&
|
||||||
_clearCaptchaUi(remountTurnstile: provider == 'turnstile');
|
token != null &&
|
||||||
if (provider == 'turnstile') {
|
token.isNotEmpty) {
|
||||||
_captchaProvider = 'turnstile';
|
setState(() {
|
||||||
_turnstileSiteKey =
|
_captchaRequired = true;
|
||||||
(siteKey != null && siteKey.isNotEmpty) ? siteKey : null;
|
_mathChallengeLoading = false;
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (provider == 'math' &&
|
|
||||||
prompt != null &&
|
|
||||||
token != null &&
|
|
||||||
token.isNotEmpty) {
|
|
||||||
_captchaProvider = 'math';
|
|
||||||
_turnstileSiteKey = null;
|
|
||||||
_mathPrompt = prompt;
|
_mathPrompt = prompt;
|
||||||
_mathChallengeToken = token;
|
_mathChallengeToken = token;
|
||||||
return;
|
_mathAnswerController.clear();
|
||||||
}
|
});
|
||||||
// Keep any existing challenge when the error has no captcha payload.
|
return;
|
||||||
|
}
|
||||||
|
// 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() {
|
String? _buildCaptchaToken() {
|
||||||
if (!_captchaRequired) return null;
|
if (!_captchaRequired) return null;
|
||||||
if (_captchaProvider == 'turnstile') {
|
|
||||||
final token = _turnstileToken?.trim();
|
|
||||||
if (token == null || token.isEmpty) return null;
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
final token = _mathChallengeToken;
|
final token = _mathChallengeToken;
|
||||||
final answer = _mathAnswerController.text.trim();
|
final answer = _mathAnswerController.text.trim();
|
||||||
if (token == null || token.isEmpty || answer.isEmpty) return null;
|
if (token == null || token.isEmpty || answer.isEmpty) return null;
|
||||||
@ -132,9 +145,14 @@ class _LoginScreenState extends State<LoginScreen> {
|
|||||||
showErrorSnackBar(context, s.loginFieldsRequired);
|
showErrorSnackBar(context, s.loginFieldsRequired);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (_captchaRequired && _mathChallengeLoading) {
|
||||||
|
showErrorSnackBar(context, s.captchaMathHelper);
|
||||||
|
return;
|
||||||
|
}
|
||||||
final captchaToken = _buildCaptchaToken();
|
final captchaToken = _buildCaptchaToken();
|
||||||
if (_captchaRequired && (captchaToken == null || captchaToken.isEmpty)) {
|
if (_captchaRequired && (captchaToken == null || captchaToken.isEmpty)) {
|
||||||
showErrorSnackBar(context, s.captchaTurnstileHelper);
|
showErrorSnackBar(context, s.captchaMathHelper);
|
||||||
|
if (_mathPrompt == null) unawaited(_fetchMathChallenge());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setState(() => _verifyBanner = null);
|
setState(() => _verifyBanner = null);
|
||||||
@ -187,9 +205,8 @@ class _LoginScreenState extends State<LoginScreen> {
|
|||||||
setState(() {
|
setState(() {
|
||||||
_verifyBanner = null;
|
_verifyBanner = null;
|
||||||
_captchaRequired = false;
|
_captchaRequired = false;
|
||||||
_captchaProvider = null;
|
_mathChallengeLoading = false;
|
||||||
_turnstileSiteKey = null;
|
_clearMathChallenge();
|
||||||
_clearCaptchaUi(remountTurnstile: false);
|
|
||||||
});
|
});
|
||||||
_consumeFeedback();
|
_consumeFeedback();
|
||||||
context.go('/home');
|
context.go('/home');
|
||||||
@ -218,10 +235,8 @@ class _LoginScreenState extends State<LoginScreen> {
|
|||||||
state.errorMessage != null) {
|
state.errorMessage != null) {
|
||||||
final msg = state.errorMessage!
|
final msg = state.errorMessage!
|
||||||
.replaceFirst('Exception: ', '');
|
.replaceFirst('Exception: ', '');
|
||||||
if (state.isCaptchaChallenge) {
|
if (state.isCaptchaChallenge || _captchaRequired) {
|
||||||
_applyCaptchaChallenge(state.captcha);
|
_applyMathChallenge(state.captcha);
|
||||||
} else if (_captchaRequired) {
|
|
||||||
_applyCaptchaChallenge(state.captcha);
|
|
||||||
}
|
}
|
||||||
if (state.isEmailNotVerified) {
|
if (state.isEmailNotVerified) {
|
||||||
setState(() => _verifyBanner = msg);
|
setState(() => _verifyBanner = msg);
|
||||||
@ -396,43 +411,20 @@ class _LoginScreenState extends State<LoginScreen> {
|
|||||||
loading ? null : (_) => _submitLogin(),
|
loading ? null : (_) => _submitLogin(),
|
||||||
),
|
),
|
||||||
if (_captchaRequired &&
|
if (_captchaRequired &&
|
||||||
_captchaProvider == 'turnstile') ...[
|
_mathChallengeLoading) ...[
|
||||||
const SizedBox(height: 14),
|
const SizedBox(height: 14),
|
||||||
Text(
|
const Center(
|
||||||
s.captchaTurnstileHelper,
|
child: SizedBox(
|
||||||
style: Theme.of(context)
|
width: 22,
|
||||||
.textTheme
|
height: 22,
|
||||||
.bodySmall,
|
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 &&
|
if (_captchaRequired &&
|
||||||
_captchaProvider == 'math' &&
|
!_mathChallengeLoading &&
|
||||||
_mathPrompt != null) ...[
|
_mathPrompt != null) ...[
|
||||||
const SizedBox(height: 14),
|
const SizedBox(height: 14),
|
||||||
PredTextField(
|
PredTextField(
|
||||||
|
|||||||
@ -1,3 +1,6 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:webview_flutter/webview_flutter.dart';
|
import 'package:webview_flutter/webview_flutter.dart';
|
||||||
|
|
||||||
@ -5,6 +8,9 @@ import '../../core/config/app_config.dart';
|
|||||||
import '../../core/di/injection.dart';
|
import '../../core/di/injection.dart';
|
||||||
|
|
||||||
/// Cloudflare Turnstile widget for native login (WebView + explicit render).
|
/// 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 {
|
class TurnstileCaptcha extends StatefulWidget {
|
||||||
const TurnstileCaptcha({
|
const TurnstileCaptcha({
|
||||||
super.key,
|
super.key,
|
||||||
@ -20,36 +26,69 @@ class TurnstileCaptcha extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
||||||
|
static const _bridgeHost = 'turnstile.bridge';
|
||||||
|
|
||||||
late final WebViewController _controller;
|
late final WebViewController _controller;
|
||||||
|
Timer? _pollTimer;
|
||||||
var _ready = false;
|
var _ready = false;
|
||||||
|
String? _lastEmitted;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_controller = WebViewController()
|
_controller = WebViewController()
|
||||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||||
..setBackgroundColor(Colors.transparent)
|
..setBackgroundColor(const Color(0x00000000))
|
||||||
..addJavaScriptChannel(
|
..addJavaScriptChannel(
|
||||||
'TurnstileBridge',
|
'TurnstileBridge',
|
||||||
onMessageReceived: (message) {
|
onMessageReceived: (message) => _emit(message.message),
|
||||||
final raw = message.message.trim();
|
|
||||||
if (raw.isEmpty || raw == 'expired' || raw == 'error') {
|
|
||||||
widget.onToken(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
widget.onToken(raw);
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
..setNavigationDelegate(
|
..setNavigationDelegate(
|
||||||
NavigationDelegate(
|
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: (_) {
|
onPageFinished: (_) {
|
||||||
if (mounted) setState(() => _ready = true);
|
if (mounted) setState(() => _ready = true);
|
||||||
|
_startPolling();
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
_load();
|
_load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_pollTimer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
String get _baseUrl {
|
String get _baseUrl {
|
||||||
final api = Uri.tryParse(sl<AppConfig>().apiBaseUrl);
|
final api = Uri.tryParse(sl<AppConfig>().apiBaseUrl);
|
||||||
if (api != null &&
|
if (api != null &&
|
||||||
@ -57,14 +96,49 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
|||||||
api.host.isNotEmpty &&
|
api.host.isNotEmpty &&
|
||||||
api.host != 'localhost' &&
|
api.host != 'localhost' &&
|
||||||
api.host != '127.0.0.1' &&
|
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 '${api.scheme}://${api.host}/';
|
||||||
}
|
}
|
||||||
return '${AppConfig.defaultProductionApiBaseUrl}/';
|
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) {
|
String _html(String siteKey) {
|
||||||
final escaped = siteKey.replaceAll("'", r"\'");
|
final escaped = const JsonEncoder().convert(siteKey);
|
||||||
return '''
|
return '''
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
@ -79,14 +153,26 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
|||||||
background: transparent;
|
background: transparent;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
#cf-turnstile { display: flex; justify-content: center; }
|
#cf-turnstile { display: flex; justify-content: center; width: 100%; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="cf-turnstile"></div>
|
<div id="cf-turnstile"></div>
|
||||||
<script>
|
<script>
|
||||||
|
window.__cfTurnstileToken = '';
|
||||||
function notify(msg) {
|
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() {
|
function renderWhenReady() {
|
||||||
if (!window.turnstile) {
|
if (!window.turnstile) {
|
||||||
@ -94,7 +180,7 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
window.turnstile.render('#cf-turnstile', {
|
window.turnstile.render('#cf-turnstile', {
|
||||||
sitekey: '$escaped',
|
sitekey: $escaped,
|
||||||
theme: 'auto',
|
theme: 'auto',
|
||||||
callback: function (token) { notify(token); },
|
callback: function (token) { notify(token); },
|
||||||
'expired-callback': function () { notify('expired'); },
|
'expired-callback': function () { notify('expired'); },
|
||||||
@ -109,7 +195,10 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _load() async {
|
Future<void> _load() async {
|
||||||
|
_pollTimer?.cancel();
|
||||||
|
_lastEmitted = null;
|
||||||
widget.onToken(null);
|
widget.onToken(null);
|
||||||
|
if (mounted) setState(() => _ready = false);
|
||||||
await _controller.loadHtmlString(_html(widget.siteKey), baseUrl: _baseUrl);
|
await _controller.loadHtmlString(_html(widget.siteKey), baseUrl: _baseUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -117,7 +206,6 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
|||||||
void didUpdateWidget(covariant TurnstileCaptcha oldWidget) {
|
void didUpdateWidget(covariant TurnstileCaptcha oldWidget) {
|
||||||
super.didUpdateWidget(oldWidget);
|
super.didUpdateWidget(oldWidget);
|
||||||
if (oldWidget.siteKey != widget.siteKey) {
|
if (oldWidget.siteKey != widget.siteKey) {
|
||||||
setState(() => _ready = false);
|
|
||||||
_load();
|
_load();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -125,7 +213,7 @@ class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return SizedBox(
|
return SizedBox(
|
||||||
height: 72,
|
height: 80,
|
||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
child: Stack(
|
child: Stack(
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user