Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

fix(plugin): detect anti-crawler challenge in non-2xx responses (#2579)

PlasticCat241ec54ec6f7
diff --git a/lib/services/plugin/rule_engine.dart b/lib/services/plugin/rule_engine.dart
index 41e6235f..0eeea7bd 100644
--- a/lib/services/plugin/rule_engine.dart
+++ b/lib/services/plugin/rule_engine.dart
@@ -51,14 +51,22 @@ class RuleEngine {
throw SearchErrorException(config.pluginName, cause: error);
}
- final raw = await _executeRequest(
- request,
- config,
- phase: 'search request',
- wrapError: (error) =>
- SearchErrorException(config.pluginName, cause: error),
- cancelToken: cancelToken,
- );
+ late final String raw;
+ try {
+ raw = await _executeRequest(
+ request,
+ config,
+ phase: 'search request',
+ wrapError: (error) =>
+ SearchErrorException(config.pluginName, cause: error),
+ cancelToken: cancelToken,
+ );
+ } on SearchErrorException catch (error) {
+ if (_isCaptchaChallengeResponse(error, config)) {
+ throw CaptchaRequiredException(config.pluginName);
+ }
+ rethrow;
+ }
try {
final parsed = config.searchMode == RuleMode.api
? _apiStrategy.parseSearch(raw, config.searchApiConfig)
@@ -197,6 +205,62 @@ class RuleEngine {
error.type == NetworkExceptionType.cancel;
}
+ /// Checks whether a failed XPath search request actually returned an
+ /// anti-crawler challenge page.
+ ///
+ /// Dio rejects non-2xx responses before [XPathRuleStrategy.parseSearch]
+ /// gets a chance to inspect the response body. Protected sites commonly
+ /// return challenge HTML with HTTP 403/429/503, so reuse the configured
+ /// captcha detector against the preserved Dio response body and hand the
+ /// request over to the existing captcha flow when it matches.
+ bool _isCaptchaChallengeResponse(
+ SearchErrorException error,
+ RuleExecutionConfig config,
+ ) {
+ if (config.searchMode != RuleMode.xpath ||
+ !config.antiCrawlerConfig.enabled) {
+ return false;
+ }
+
+ final cause = error.cause;
+ if (cause is! NetworkException ||
+ cause.type != NetworkExceptionType.badResponse) {
+ return false;
+ }
+
+ final rawError = cause.rawError;
+ if (rawError is! DioException) return false;
+
+ final response = rawError.response;
+
+ // Cloudflare marks managed challenge responses with this header.
+ // This is useful when the body is empty, compressed unexpectedly, or
+ // otherwise unavailable to Dio on a specific platform.
+ final cfMitigated = response?.headers.value('cf-mitigated');
+ if (cfMitigated?.toLowerCase() == 'challenge') {
+ return true;
+ }
+
+ final data = response?.data;
+ final raw = data is String ? data : data?.toString() ?? '';
+ if (raw.trim().isEmpty) return false;
+
+ try {
+ return _xpathStrategy.detectsCaptchaChallenge(
+ raw,
+ config.antiCrawlerConfig,
+ );
+ } catch (detectError, stackTrace) {
+ _logFailure(
+ config,
+ 'failed response captcha detection',
+ detectError,
+ stackTrace,
+ );
+ return false;
+ }
+ }
+
/// Surfaces partially-skipped nodes so incomplete results are traceable
/// from logs even when the rule succeeds overall.
void _logDiagnostics(
diff --git a/test/rule_engine_test.dart b/test/rule_engine_test.dart
index 9c9a49a8..cfcef75c 100644
--- a/test/rule_engine_test.dart
+++ b/test/rule_engine_test.dart
@@ -199,6 +199,98 @@ void main() {
);
});
+ test('turns failed XPath challenge response into captcha flow', () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(
+ const [],
+ error: _badResponse('<html>captcha</html>'),
+ ),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(
+ searchMode: RuleMode.xpath,
+ chapterMode: RuleMode.xpath,
+ antiCrawler: _antiCrawler(),
+ ),
+ 'keyword',
+ ),
+ throwsA(isA<CaptchaRequiredException>()),
+ );
+ });
+
+ test('turns Cloudflare challenge header into captcha flow', () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(
+ const [],
+ error: _badResponse(
+ '',
+ headers: {'cf-mitigated': ['challenge']},
+ ),
+ ),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(
+ searchMode: RuleMode.xpath,
+ chapterMode: RuleMode.xpath,
+ antiCrawler: _antiCrawler(),
+ ),
+ 'keyword',
+ ),
+ throwsA(isA<CaptchaRequiredException>()),
+ );
+ });
+
+ test('keeps failed non-challenge XPath response as search error', () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(
+ const [],
+ error: _badResponse('<html>forbidden</html>'),
+ ),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(
+ searchMode: RuleMode.xpath,
+ chapterMode: RuleMode.xpath,
+ antiCrawler: _antiCrawler(),
+ ),
+ 'keyword',
+ ),
+ throwsA(isA<SearchErrorException>()),
+ );
+ });
+
+ test('API search does not turn failed challenge response into captcha flow',
+ () async {
+ final engine = RuleEngine(
+ requestExecutor: _FakeExecutor(
+ const [],
+ error: _badResponse('<html>captcha</html>'),
+ ),
+ logFailures: false,
+ );
+
+ await expectLater(
+ engine.search(
+ _config(
+ searchMode: RuleMode.api,
+ chapterMode: RuleMode.xpath,
+ antiCrawler: _antiCrawler(),
+ ),
+ 'keyword',
+ ),
+ throwsA(isA<SearchErrorException>()),
+ );
+ });
+
test('propagates cancellation without wrapping it', () async {
const cancellation = NetworkException(
type: NetworkExceptionType.cancel,
@@ -220,6 +312,31 @@ void main() {
});
}
+NetworkException _badResponse(
+ String body, {
+ int statusCode = 403,
+ Map<String, List<String>>? headers,
+}) {
+ final requestOptions = RequestOptions(
+ path: 'https://example.com/search?q=keyword',
+ );
+ return NetworkException(
+ type: NetworkExceptionType.badResponse,
+ message: 'server error',
+ statusCode: statusCode,
+ rawError: DioException(
+ requestOptions: requestOptions,
+ response: Response<String>(
+ requestOptions: requestOptions,
+ statusCode: statusCode,
+ data: body,
+ headers: headers == null ? null : Headers.fromMap(headers),
+ ),
+ type: DioExceptionType.badResponse,
+ ),
+ );
+}
+
class _FakeExecutor implements RuleRequestExecutor {
_FakeExecutor(List<String> responses, {this.error})
: _responses = List<String>.of(responses);