novelcaptcha 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,54 @@
1
+ """NovelCaptcha Python SDK — verify tokens and classify emails.
2
+
3
+ Quick start:
4
+
5
+ from novelcaptcha import NovelCaptcha
6
+
7
+ client = NovelCaptcha(
8
+ secret_key="sec_...",
9
+ base_url="http://localhost:3020", # omit for SaaS
10
+ )
11
+
12
+ result = client.verify(token, remote_ip="203.0.113.5")
13
+ if result.score < 0.5:
14
+ # reject or step-up
15
+ ...
16
+ """
17
+ from .client import (
18
+ AsyncNovelCaptcha,
19
+ ErrorContext,
20
+ NovelCaptcha,
21
+ RequestContext,
22
+ RequestHooks,
23
+ ResponseContext,
24
+ RetryPolicy,
25
+ )
26
+ from .errors import (
27
+ InvalidSecretError,
28
+ InvalidTokenError,
29
+ NetworkError,
30
+ NovelCaptchaError,
31
+ TimeoutError,
32
+ )
33
+ from .types import ChallengeResult, EmailClassificationResult, VerifyResult
34
+
35
+ __version__ = "0.1.0"
36
+
37
+ __all__ = [
38
+ "AsyncNovelCaptcha",
39
+ "ChallengeResult",
40
+ "EmailClassificationResult",
41
+ "ErrorContext",
42
+ "InvalidSecretError",
43
+ "InvalidTokenError",
44
+ "NetworkError",
45
+ "NovelCaptcha",
46
+ "NovelCaptchaError",
47
+ "RequestContext",
48
+ "RequestHooks",
49
+ "ResponseContext",
50
+ "RetryPolicy",
51
+ "TimeoutError",
52
+ "VerifyResult",
53
+ "__version__",
54
+ ]
novelcaptcha/client.py ADDED
@@ -0,0 +1,623 @@
1
+ """Synchronous and async NovelCaptcha clients."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import random
6
+ import time
7
+ from dataclasses import dataclass, field
8
+ from email.utils import parsedate_to_datetime
9
+ from typing import Any, Awaitable, Callable, Dict, Mapping, Optional, Union, cast
10
+
11
+ import httpx
12
+
13
+ from .errors import (
14
+ InvalidSecretError,
15
+ InvalidTokenError,
16
+ NetworkError,
17
+ NovelCaptchaError,
18
+ TimeoutError as NovelCaptchaTimeoutError,
19
+ )
20
+ from .types import ChallengeResult, EmailClassificationResult, VerifyResult
21
+
22
+ _DEFAULT_BASE_URL = "https://api.novelcaptcha.com"
23
+ _DEFAULT_TIMEOUT = 10.0
24
+ _NORMAL_EMAIL_CLASSIFICATIONS = {"safe", "privacy/alias", "temp-mail"}
25
+
26
+
27
+ @dataclass
28
+ class RetryPolicy:
29
+ """Retry policy for transient failures.
30
+
31
+ Attributes:
32
+ attempts: Number of retries after the initial request. `2` means one
33
+ initial attempt plus up to two retries.
34
+ initial_delay: Seconds before the first retry. Grows exponentially
35
+ with jitter for subsequent retries.
36
+ max_delay: Ceiling for the retry delay.
37
+ """
38
+
39
+ attempts: int = 2
40
+ initial_delay: float = 0.1
41
+ max_delay: float = 2.0
42
+
43
+
44
+ @dataclass
45
+ class RequestContext:
46
+ method: str
47
+ url: str
48
+ attempt: int
49
+
50
+
51
+ @dataclass
52
+ class ResponseContext:
53
+ method: str
54
+ url: str
55
+ attempt: int
56
+ status: int
57
+ elapsed_ms: int
58
+
59
+
60
+ @dataclass
61
+ class ErrorContext:
62
+ method: str
63
+ url: str
64
+ attempt: int
65
+ elapsed_ms: int
66
+ error: BaseException
67
+
68
+
69
+ @dataclass
70
+ class RequestHooks:
71
+ """Observability hooks. All handler exceptions are caught and ignored so
72
+ a broken hook cannot break the underlying request.
73
+ """
74
+
75
+ on_request: Optional[Callable[[RequestContext], None]] = None
76
+ on_response: Optional[Callable[[ResponseContext], None]] = None
77
+ on_error: Optional[Callable[[ErrorContext], None]] = None
78
+
79
+
80
+ def _normalize_base_url(url: str) -> str:
81
+ return url.rstrip("/")
82
+
83
+
84
+ def _safe_invoke(handler: Optional[Callable[..., Any]], arg: Any, tag: str) -> None:
85
+ if handler is None:
86
+ return
87
+ try:
88
+ handler(arg)
89
+ except Exception as exc: # pragma: no cover — defensive
90
+ try:
91
+ import sys
92
+ print(f"[novelcaptcha] {tag} hook raised: {exc!r}", file=sys.stderr)
93
+ except Exception:
94
+ pass
95
+
96
+
97
+ def _parse_retry_after(header: Optional[str]) -> Optional[float]:
98
+ if not header:
99
+ return None
100
+ try:
101
+ seconds = float(header)
102
+ if seconds >= 0:
103
+ return min(seconds, 60.0)
104
+ except ValueError:
105
+ pass
106
+ try:
107
+ dt = parsedate_to_datetime(header)
108
+ if dt is not None:
109
+ delta = (dt.timestamp() - time.time())
110
+ return max(0.0, min(delta, 60.0))
111
+ except (TypeError, ValueError):
112
+ pass
113
+ return None
114
+
115
+
116
+ def _backoff_delay(attempt: int, policy: RetryPolicy) -> float:
117
+ base = policy.initial_delay * (2 ** (attempt - 1))
118
+ capped = min(base, policy.max_delay)
119
+ # Full jitter, matches the Node SDK.
120
+ return random.random() * capped
121
+
122
+
123
+ def _is_retryable(exc: BaseException) -> bool:
124
+ if isinstance(exc, (InvalidTokenError, InvalidSecretError)):
125
+ return False
126
+ if isinstance(exc, NovelCaptchaTimeoutError):
127
+ return True
128
+ if isinstance(exc, NetworkError):
129
+ if exc.status_code is None:
130
+ return True
131
+ if exc.status_code == 429 or (500 <= exc.status_code <= 599):
132
+ return True
133
+ return False
134
+ return False
135
+
136
+
137
+ def _verify_body(secret_key: str, token: str, remote_ip: Optional[str]) -> Dict[str, str]:
138
+ if not isinstance(token, str) or not token:
139
+ raise InvalidTokenError(["missing-input-response"])
140
+ body: Dict[str, str] = {"secret": secret_key, "response": token}
141
+ if remote_ip:
142
+ body["remoteip"] = remote_ip
143
+ return body
144
+
145
+
146
+ def _to_verify_result(raw: Mapping[str, Any]) -> VerifyResult:
147
+ score = float(raw.get("score", raw.get("trust_score", 0.0)))
148
+ return VerifyResult(
149
+ success=True,
150
+ score=score,
151
+ trust_score=float(raw.get("trust_score", score)),
152
+ challenge_ts=int(raw.get("challenge_ts", 0) or 0),
153
+ hostname=str(raw.get("hostname", "")),
154
+ action=str(raw.get("action", "")),
155
+ note=str(raw.get("note", "")),
156
+ context=str(raw.get("context", "")),
157
+ visitor_id=str(raw.get("visitor_id", "")),
158
+ visitor_confidence=float(raw.get("visitor_confidence", 0.0) or 0.0),
159
+ visitor_decision=str(raw.get("visitor_decision", "")),
160
+ override_applied=bool(raw.get("override_applied", False)),
161
+ )
162
+
163
+
164
+ def _handle_verify_response(status_code: int, payload: Any) -> VerifyResult:
165
+ if not isinstance(payload, Mapping):
166
+ raise NetworkError(
167
+ f"NovelCaptcha returned a malformed response (status {status_code}).",
168
+ status_code,
169
+ )
170
+ body = cast(Mapping[str, Any], payload)
171
+ if status_code >= 400:
172
+ raise NetworkError(
173
+ f"NovelCaptcha /api/siteverify returned HTTP {status_code}.",
174
+ status_code,
175
+ )
176
+ if body.get("success") is False:
177
+ codes_raw = body.get("error-codes", [])
178
+ codes = [str(c) for c in codes_raw] if isinstance(codes_raw, list) else []
179
+ if "invalid-input-secret" in codes:
180
+ raise InvalidSecretError()
181
+ raise InvalidTokenError(codes or ["unknown"])
182
+ return _to_verify_result(body)
183
+
184
+
185
+ def _classify_body(
186
+ secret_key: str,
187
+ email: str,
188
+ sitekey: Optional[str],
189
+ ) -> Dict[str, str]:
190
+ if not isinstance(email, str) or not email:
191
+ raise NovelCaptchaError("invalid_email", "Email is required.")
192
+ body: Dict[str, str] = {"email": email, "secret": secret_key}
193
+ if sitekey:
194
+ body["sitekey"] = sitekey
195
+ return body
196
+
197
+
198
+ def _handle_classify_response(
199
+ status_code: int, payload: Any
200
+ ) -> EmailClassificationResult:
201
+ if status_code in (401, 403):
202
+ raise InvalidSecretError()
203
+ if status_code >= 400:
204
+ raise NetworkError(
205
+ f"NovelCaptcha /api/email/classify returned HTTP {status_code}.",
206
+ status_code,
207
+ )
208
+ if not isinstance(payload, Mapping):
209
+ raise NetworkError("NovelCaptcha returned a malformed response.", status_code)
210
+ body = cast(Mapping[str, Any], payload)
211
+ classification = str(body.get("classification", "safe"))
212
+ if classification not in _NORMAL_EMAIL_CLASSIFICATIONS:
213
+ raise NetworkError(
214
+ f"Unexpected email classification: {classification}", status_code
215
+ )
216
+ reasons_raw = body.get("reasons", [])
217
+ reasons = [str(r) for r in reasons_raw] if isinstance(reasons_raw, list) else []
218
+ return EmailClassificationResult(
219
+ classification=classification,
220
+ reasons=reasons,
221
+ risk_score=float(body.get("risk_score", 0.0) or 0.0),
222
+ )
223
+
224
+
225
+ def _challenge_body(
226
+ secret_key: str,
227
+ *,
228
+ sitekey: str,
229
+ type: str,
230
+ context: str,
231
+ custom_signals: Optional[Mapping[str, Any]] = None,
232
+ custom_metrics: Optional[Mapping[str, Any]] = None,
233
+ ) -> Dict[str, Any]:
234
+ if not isinstance(sitekey, str) or not sitekey:
235
+ raise NovelCaptchaError("invalid_sitekey", "sitekey is required.")
236
+ if type not in {"visual", "invisible"}:
237
+ raise NovelCaptchaError(
238
+ "invalid_challenge_type", "type must be 'visual' or 'invisible'."
239
+ )
240
+ if not isinstance(context, str) or not context:
241
+ raise NovelCaptchaError("invalid_context", "context is required.")
242
+ return {
243
+ "secret": secret_key,
244
+ "sitekey": sitekey,
245
+ "type": type,
246
+ "context": context,
247
+ "custom_signals": dict(custom_signals or {}),
248
+ "custom_metrics": dict(custom_metrics or {}),
249
+ }
250
+
251
+
252
+ def _handle_challenge_response(status_code: int, payload: Any) -> ChallengeResult:
253
+ if not isinstance(payload, Mapping):
254
+ raise NetworkError(
255
+ f"NovelCaptcha returned a malformed challenge response (status {status_code}).",
256
+ status_code,
257
+ )
258
+ body = cast(Mapping[str, Any], payload)
259
+ if status_code >= 400:
260
+ raise NetworkError(
261
+ f"NovelCaptcha /challenge/issue returned HTTP {status_code}.",
262
+ status_code,
263
+ )
264
+ if body.get("success") is False:
265
+ codes_raw = body.get("error-codes", [])
266
+ codes = [str(c) for c in codes_raw] if isinstance(codes_raw, list) else []
267
+ if "invalid-input-secret" in codes or body.get("error") == "invalid_secret":
268
+ raise InvalidSecretError()
269
+ raise NetworkError(
270
+ f"NovelCaptcha rejected challenge issue request: {body.get('error', 'unknown')}.",
271
+ status_code,
272
+ )
273
+ challenge_key = str(body.get("challenge_key", ""))
274
+ if not challenge_key:
275
+ raise NetworkError("NovelCaptcha returned no challenge_key.", status_code)
276
+ return ChallengeResult(
277
+ challenge_key=challenge_key,
278
+ expires_at=int(body.get("expires_at", 0) or 0),
279
+ )
280
+
281
+
282
+ def _do_request_once_sync(
283
+ client: httpx.Client, url: str, body: Dict[str, Any], timeout: float,
284
+ ) -> httpx.Response:
285
+ try:
286
+ return client.post(url, json=body)
287
+ except httpx.TimeoutException as exc:
288
+ raise NovelCaptchaTimeoutError(timeout) from exc
289
+ except httpx.HTTPError as exc:
290
+ raise NetworkError(str(exc), cause=exc) from exc
291
+
292
+
293
+ async def _do_request_once_async(
294
+ client: httpx.AsyncClient, url: str, body: Dict[str, Any], timeout: float,
295
+ ) -> httpx.Response:
296
+ try:
297
+ return await client.post(url, json=body)
298
+ except httpx.TimeoutException as exc:
299
+ raise NovelCaptchaTimeoutError(timeout) from exc
300
+ except httpx.HTTPError as exc:
301
+ raise NetworkError(str(exc), cause=exc) from exc
302
+
303
+
304
+ def _parse_json(response: httpx.Response) -> Any:
305
+ try:
306
+ return response.json() if response.content else {}
307
+ except ValueError as exc:
308
+ raise NetworkError(
309
+ f"NovelCaptcha returned non-JSON response (status {response.status_code}).",
310
+ response.status_code,
311
+ exc,
312
+ ) from exc
313
+
314
+
315
+ def _debug_log(debug: bool, msg: str) -> None:
316
+ if not debug:
317
+ return
318
+ try:
319
+ import sys
320
+ print(f"[novelcaptcha] {msg}", file=sys.stderr)
321
+ except Exception:
322
+ pass
323
+
324
+
325
+ class _ClientCommon:
326
+ """Fields shared by sync + async clients."""
327
+
328
+ def __init__(
329
+ self,
330
+ secret_key: str,
331
+ *,
332
+ base_url: str,
333
+ timeout: float,
334
+ retry: Union[RetryPolicy, bool] = True,
335
+ hooks: Optional[RequestHooks] = None,
336
+ debug: bool = False,
337
+ ) -> None:
338
+ if not isinstance(secret_key, str) or not secret_key:
339
+ raise NovelCaptchaError(
340
+ "invalid_config", "`secret_key` is required."
341
+ )
342
+ self._secret_key = secret_key
343
+ self._base_url = _normalize_base_url(base_url)
344
+ self._timeout = timeout
345
+ if retry is False:
346
+ self._retry = RetryPolicy(attempts=0)
347
+ elif retry is True:
348
+ self._retry = RetryPolicy()
349
+ else:
350
+ self._retry = retry
351
+ self._hooks = hooks or RequestHooks()
352
+ self._debug = debug or os.environ.get("NC_DEBUG") == "1"
353
+
354
+
355
+ class NovelCaptcha(_ClientCommon):
356
+ """Synchronous NovelCaptcha server client.
357
+
358
+ Instantiate once and share across your application. Thread-safe.
359
+
360
+ Example:
361
+ >>> from novelcaptcha import NovelCaptcha
362
+ >>> client = NovelCaptcha(secret_key="sec_...", base_url="http://localhost:3020")
363
+ >>> result = client.verify(token, remote_ip="203.0.113.5")
364
+ >>> if result.score < 0.5:
365
+ ... pass # reject
366
+ """
367
+
368
+ def __init__(
369
+ self,
370
+ secret_key: str,
371
+ *,
372
+ base_url: str = _DEFAULT_BASE_URL,
373
+ timeout: float = _DEFAULT_TIMEOUT,
374
+ transport: Optional[httpx.BaseTransport] = None,
375
+ retry: Union[RetryPolicy, bool] = True,
376
+ hooks: Optional[RequestHooks] = None,
377
+ debug: bool = False,
378
+ ) -> None:
379
+ super().__init__(
380
+ secret_key,
381
+ base_url=base_url,
382
+ timeout=timeout,
383
+ retry=retry,
384
+ hooks=hooks,
385
+ debug=debug,
386
+ )
387
+ self._client = httpx.Client(
388
+ timeout=timeout,
389
+ transport=transport,
390
+ headers={"User-Agent": "novelcaptcha-python/0.1.0"},
391
+ )
392
+
393
+ def _request(self, path: str, body: Dict[str, Any]) -> tuple[int, Any]:
394
+ url = f"{self._base_url}{path}"
395
+ max_attempts = max(1, self._retry.attempts + 1)
396
+ last_exc: Optional[BaseException] = None
397
+
398
+ for attempt in range(1, max_attempts + 1):
399
+ started = time.monotonic()
400
+ req_ctx = RequestContext(method="POST", url=url, attempt=attempt)
401
+ _safe_invoke(self._hooks.on_request, req_ctx, "on_request")
402
+ _debug_log(self._debug, f"-> POST {path} (attempt {attempt})")
403
+
404
+ try:
405
+ response = _do_request_once_sync(self._client, url, body, self._timeout)
406
+ elapsed_ms = int((time.monotonic() - started) * 1000)
407
+ payload = _parse_json(response)
408
+ _safe_invoke(
409
+ self._hooks.on_response,
410
+ ResponseContext(method="POST", url=url, attempt=attempt, status=response.status_code, elapsed_ms=elapsed_ms),
411
+ "on_response",
412
+ )
413
+ _debug_log(self._debug, f"<- {response.status_code} {path} ({elapsed_ms}ms)")
414
+
415
+ if response.status_code == 429 and attempt < max_attempts:
416
+ wait = _parse_retry_after(response.headers.get("retry-after")) or _backoff_delay(attempt, self._retry)
417
+ time.sleep(wait)
418
+ last_exc = NetworkError(f"Rate limited (HTTP 429), retrying in {wait:.2f}s.", 429)
419
+ continue
420
+
421
+ if 500 <= response.status_code <= 599 and attempt < max_attempts:
422
+ time.sleep(_backoff_delay(attempt, self._retry))
423
+ last_exc = NetworkError(f"NovelCaptcha returned HTTP {response.status_code}.", response.status_code)
424
+ continue
425
+
426
+ return response.status_code, payload
427
+
428
+ except BaseException as exc:
429
+ elapsed_ms = int((time.monotonic() - started) * 1000)
430
+ _safe_invoke(
431
+ self._hooks.on_error,
432
+ ErrorContext(method="POST", url=url, attempt=attempt, elapsed_ms=elapsed_ms, error=exc),
433
+ "on_error",
434
+ )
435
+ last_exc = exc
436
+ if not _is_retryable(exc) or attempt >= max_attempts:
437
+ raise
438
+ time.sleep(_backoff_delay(attempt, self._retry))
439
+
440
+ # unreachable in practice; keep the type checker happy
441
+ if last_exc:
442
+ raise last_exc
443
+ raise NetworkError("Retries exhausted.", None)
444
+
445
+ def verify(self, token: str, *, remote_ip: Optional[str] = None) -> VerifyResult:
446
+ """Verify a token minted by the browser SDK.
447
+
448
+ Raises:
449
+ InvalidTokenError: server rejected the token.
450
+ InvalidSecretError: secret key mismatch.
451
+ NetworkError: HTTP / JSON / transport failure (after retries).
452
+ TimeoutError: request exceeded ``timeout`` seconds (after retries).
453
+ """
454
+ body = _verify_body(self._secret_key, token, remote_ip)
455
+ status, payload = self._request("/api/siteverify", body)
456
+ return _handle_verify_response(status, payload)
457
+
458
+ def create_challenge(
459
+ self,
460
+ *,
461
+ sitekey: str,
462
+ type: str,
463
+ context: str,
464
+ custom_signals: Optional[Mapping[str, Any]] = None,
465
+ custom_metrics: Optional[Mapping[str, Any]] = None,
466
+ ) -> ChallengeResult:
467
+ """Issue a one-time challenge key for the browser SDK."""
468
+ body = _challenge_body(
469
+ self._secret_key,
470
+ sitekey=sitekey,
471
+ type=type,
472
+ context=context,
473
+ custom_signals=custom_signals,
474
+ custom_metrics=custom_metrics,
475
+ )
476
+ status, payload = self._request("/challenge/issue", body)
477
+ return _handle_challenge_response(status, payload)
478
+
479
+ def classify_email(
480
+ self, email: str, *, sitekey: Optional[str] = None
481
+ ) -> EmailClassificationResult:
482
+ """Classify an email into ``safe`` / ``privacy/alias`` / ``temp-mail``."""
483
+ body = _classify_body(self._secret_key, email, sitekey)
484
+ status, payload = self._request("/api/email/classify", body)
485
+ return _handle_classify_response(status, payload)
486
+
487
+ def close(self) -> None:
488
+ self._client.close()
489
+
490
+ def __enter__(self) -> "NovelCaptcha":
491
+ return self
492
+
493
+ def __exit__(self, *_: Any) -> None:
494
+ self.close()
495
+
496
+
497
+ class AsyncNovelCaptcha(_ClientCommon):
498
+ """Async NovelCaptcha server client.
499
+
500
+ Example:
501
+ >>> async with AsyncNovelCaptcha(secret_key="sec_...") as client:
502
+ ... result = await client.verify(token)
503
+ """
504
+
505
+ def __init__(
506
+ self,
507
+ secret_key: str,
508
+ *,
509
+ base_url: str = _DEFAULT_BASE_URL,
510
+ timeout: float = _DEFAULT_TIMEOUT,
511
+ transport: Optional[httpx.AsyncBaseTransport] = None,
512
+ retry: Union[RetryPolicy, bool] = True,
513
+ hooks: Optional[RequestHooks] = None,
514
+ debug: bool = False,
515
+ ) -> None:
516
+ super().__init__(
517
+ secret_key,
518
+ base_url=base_url,
519
+ timeout=timeout,
520
+ retry=retry,
521
+ hooks=hooks,
522
+ debug=debug,
523
+ )
524
+ self._client = httpx.AsyncClient(
525
+ timeout=timeout,
526
+ transport=transport,
527
+ headers={"User-Agent": "novelcaptcha-python/0.1.0"},
528
+ )
529
+
530
+ async def _request(self, path: str, body: Dict[str, Any]) -> tuple[int, Any]:
531
+ import asyncio
532
+ url = f"{self._base_url}{path}"
533
+ max_attempts = max(1, self._retry.attempts + 1)
534
+ last_exc: Optional[BaseException] = None
535
+
536
+ for attempt in range(1, max_attempts + 1):
537
+ started = time.monotonic()
538
+ req_ctx = RequestContext(method="POST", url=url, attempt=attempt)
539
+ _safe_invoke(self._hooks.on_request, req_ctx, "on_request")
540
+ _debug_log(self._debug, f"-> POST {path} (attempt {attempt})")
541
+
542
+ try:
543
+ response = await _do_request_once_async(self._client, url, body, self._timeout)
544
+ elapsed_ms = int((time.monotonic() - started) * 1000)
545
+ payload = _parse_json(response)
546
+ _safe_invoke(
547
+ self._hooks.on_response,
548
+ ResponseContext(method="POST", url=url, attempt=attempt, status=response.status_code, elapsed_ms=elapsed_ms),
549
+ "on_response",
550
+ )
551
+ _debug_log(self._debug, f"<- {response.status_code} {path} ({elapsed_ms}ms)")
552
+
553
+ if response.status_code == 429 and attempt < max_attempts:
554
+ wait = _parse_retry_after(response.headers.get("retry-after")) or _backoff_delay(attempt, self._retry)
555
+ await asyncio.sleep(wait)
556
+ last_exc = NetworkError(f"Rate limited (HTTP 429), retrying in {wait:.2f}s.", 429)
557
+ continue
558
+
559
+ if 500 <= response.status_code <= 599 and attempt < max_attempts:
560
+ await asyncio.sleep(_backoff_delay(attempt, self._retry))
561
+ last_exc = NetworkError(f"NovelCaptcha returned HTTP {response.status_code}.", response.status_code)
562
+ continue
563
+
564
+ return response.status_code, payload
565
+
566
+ except BaseException as exc:
567
+ elapsed_ms = int((time.monotonic() - started) * 1000)
568
+ _safe_invoke(
569
+ self._hooks.on_error,
570
+ ErrorContext(method="POST", url=url, attempt=attempt, elapsed_ms=elapsed_ms, error=exc),
571
+ "on_error",
572
+ )
573
+ last_exc = exc
574
+ if not _is_retryable(exc) or attempt >= max_attempts:
575
+ raise
576
+ await asyncio.sleep(_backoff_delay(attempt, self._retry))
577
+
578
+ if last_exc:
579
+ raise last_exc
580
+ raise NetworkError("Retries exhausted.", None)
581
+
582
+ async def verify(
583
+ self, token: str, *, remote_ip: Optional[str] = None
584
+ ) -> VerifyResult:
585
+ body = _verify_body(self._secret_key, token, remote_ip)
586
+ status, payload = await self._request("/api/siteverify", body)
587
+ return _handle_verify_response(status, payload)
588
+
589
+ async def create_challenge(
590
+ self,
591
+ *,
592
+ sitekey: str,
593
+ type: str,
594
+ context: str,
595
+ custom_signals: Optional[Mapping[str, Any]] = None,
596
+ custom_metrics: Optional[Mapping[str, Any]] = None,
597
+ ) -> ChallengeResult:
598
+ body = _challenge_body(
599
+ self._secret_key,
600
+ sitekey=sitekey,
601
+ type=type,
602
+ context=context,
603
+ custom_signals=custom_signals,
604
+ custom_metrics=custom_metrics,
605
+ )
606
+ status, payload = await self._request("/challenge/issue", body)
607
+ return _handle_challenge_response(status, payload)
608
+
609
+ async def classify_email(
610
+ self, email: str, *, sitekey: Optional[str] = None
611
+ ) -> EmailClassificationResult:
612
+ body = _classify_body(self._secret_key, email, sitekey)
613
+ status, payload = await self._request("/api/email/classify", body)
614
+ return _handle_classify_response(status, payload)
615
+
616
+ async def aclose(self) -> None:
617
+ await self._client.aclose()
618
+
619
+ async def __aenter__(self) -> "AsyncNovelCaptcha":
620
+ return self
621
+
622
+ async def __aexit__(self, *_: Any) -> None:
623
+ await self.aclose()
novelcaptcha/errors.py ADDED
@@ -0,0 +1,60 @@
1
+ """Error hierarchy for the NovelCaptcha Python SDK."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional, Sequence
5
+
6
+
7
+ class NovelCaptchaError(Exception):
8
+ """Base class for all SDK errors.
9
+
10
+ Catch this to handle every failure mode the SDK can raise.
11
+ """
12
+
13
+ def __init__(self, code: str, message: str) -> None:
14
+ super().__init__(message)
15
+ self.code = code
16
+
17
+ def __str__(self) -> str:
18
+ return f"[{self.code}] {super().__str__()}"
19
+
20
+
21
+ class InvalidTokenError(NovelCaptchaError):
22
+ """The server rejected the token (expired, replayed, malformed, or wrong site)."""
23
+
24
+ def __init__(self, error_codes: Sequence[str]) -> None:
25
+ self.error_codes = list(error_codes)
26
+ codes_str = ", ".join(self.error_codes) or "unknown"
27
+ super().__init__("invalid_token", f"NovelCaptcha rejected the token: {codes_str}")
28
+
29
+
30
+ class InvalidSecretError(NovelCaptchaError):
31
+ """The configured ``secret_key`` does not match the site key used on the browser."""
32
+
33
+ def __init__(self) -> None:
34
+ super().__init__(
35
+ "invalid_secret",
36
+ "NovelCaptcha rejected the secret key. Check your server-side configuration.",
37
+ )
38
+
39
+
40
+ class NetworkError(NovelCaptchaError):
41
+ """The SDK got a non-2xx HTTP response or could not parse the JSON body."""
42
+
43
+ def __init__(
44
+ self,
45
+ message: str,
46
+ status_code: Optional[int] = None,
47
+ cause: Optional[BaseException] = None,
48
+ ) -> None:
49
+ super().__init__("network_error", message)
50
+ self.status_code = status_code
51
+ if cause is not None:
52
+ self.__cause__ = cause
53
+
54
+
55
+ class TimeoutError(NetworkError): # noqa: A001 - shadowing is intentional for the SDK namespace
56
+ """The request exceeded the configured ``timeout`` before the server responded."""
57
+
58
+ def __init__(self, timeout_seconds: float) -> None:
59
+ super().__init__(f"NovelCaptcha did not respond within {timeout_seconds}s")
60
+ self.code = "timeout"
@@ -0,0 +1,95 @@
1
+ """FastAPI dependency for verifying NovelCaptcha tokens on every request.
2
+
3
+ Example::
4
+
5
+ from fastapi import FastAPI, Depends
6
+ from novelcaptcha import AsyncNovelCaptcha
7
+ from novelcaptcha.fastapi import verify_captcha
8
+
9
+ app = FastAPI()
10
+ app.state.novelcaptcha = AsyncNovelCaptcha(secret_key="sec_...")
11
+
12
+ @app.post("/login")
13
+ async def login(result = Depends(verify_captcha(token_field="captcha_token"))):
14
+ # result is a VerifyResult — only reached when score >= threshold
15
+ ...
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Awaitable, Callable, Optional
20
+
21
+ try:
22
+ from fastapi import Depends, HTTPException, Request
23
+ except ImportError as exc: # pragma: no cover - optional dependency
24
+ raise ImportError(
25
+ "FastAPI is required for novelcaptcha.fastapi. "
26
+ "Install with: pip install 'novelcaptcha[fastapi]'"
27
+ ) from exc
28
+
29
+ from .client import AsyncNovelCaptcha
30
+ from .errors import InvalidTokenError, NetworkError
31
+ from .types import VerifyResult
32
+
33
+
34
+ def _client_from_app(request: Request) -> AsyncNovelCaptcha:
35
+ client = getattr(request.app.state, "novelcaptcha", None)
36
+ if client is None:
37
+ raise RuntimeError(
38
+ "No NovelCaptcha client on app.state — "
39
+ "set app.state.novelcaptcha = AsyncNovelCaptcha(...) at startup."
40
+ )
41
+ return client
42
+
43
+
44
+ def _default_extract_ip(request: Request) -> Optional[str]:
45
+ forwarded = request.headers.get("x-forwarded-for")
46
+ if forwarded:
47
+ return forwarded.split(",")[0].strip() or None
48
+ real = request.headers.get("x-real-ip")
49
+ if real:
50
+ return real.strip() or None
51
+ client = request.client
52
+ return client.host if client else None
53
+
54
+
55
+ def verify_captcha(
56
+ *,
57
+ token_field: str = "captcha_token",
58
+ min_score: float = 0.5,
59
+ extract_ip: Callable[[Request], Optional[str]] = _default_extract_ip,
60
+ ) -> Callable[..., Awaitable[VerifyResult]]:
61
+ """Build a FastAPI dependency that verifies ``token_field`` in the JSON body.
62
+
63
+ Args:
64
+ token_field: JSON body key containing the token.
65
+ min_score: Reject requests with ``score < min_score`` (default 0.5).
66
+ extract_ip: How to derive the client IP from the request.
67
+ """
68
+
69
+ async def dependency(request: Request) -> VerifyResult:
70
+ try:
71
+ body: Any = await request.json()
72
+ except Exception:
73
+ body = {}
74
+ token = body.get(token_field) if isinstance(body, dict) else None
75
+ if not isinstance(token, str) or not token:
76
+ raise HTTPException(status_code=400, detail="missing_captcha_token")
77
+
78
+ client = _client_from_app(request)
79
+ try:
80
+ result = await client.verify(token, remote_ip=extract_ip(request))
81
+ except InvalidTokenError as exc:
82
+ raise HTTPException(
83
+ status_code=400, detail={"error": "invalid_captcha_token", "codes": exc.error_codes}
84
+ ) from exc
85
+ except NetworkError as exc:
86
+ raise HTTPException(status_code=503, detail="captcha_unavailable") from exc
87
+
88
+ if result.score < min_score:
89
+ raise HTTPException(
90
+ status_code=403,
91
+ detail={"error": "captcha_score_too_low", "score": result.score},
92
+ )
93
+ return result
94
+
95
+ return Depends(dependency)
novelcaptcha/flask.py ADDED
@@ -0,0 +1,100 @@
1
+ """Flask extension for verifying NovelCaptcha tokens.
2
+
3
+ Example::
4
+
5
+ from flask import Flask, request
6
+ from novelcaptcha import NovelCaptcha
7
+ from novelcaptcha.flask import novelcaptcha_required
8
+
9
+ app = Flask(__name__)
10
+ app.extensions["novelcaptcha"] = NovelCaptcha(secret_key="sec_...")
11
+
12
+ @app.post("/login")
13
+ @novelcaptcha_required(token_field="captcha_token", min_score=0.5)
14
+ def login():
15
+ # request.novelcaptcha is the VerifyResult when the decorator passes.
16
+ ...
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import functools
21
+ from typing import Any, Callable, Optional
22
+
23
+ try:
24
+ from flask import abort, current_app, jsonify, request
25
+ except ImportError as exc: # pragma: no cover - optional dependency
26
+ raise ImportError(
27
+ "Flask is required for novelcaptcha.flask. "
28
+ "Install with: pip install 'novelcaptcha[flask]'"
29
+ ) from exc
30
+
31
+ from .client import NovelCaptcha
32
+ from .errors import InvalidTokenError, NetworkError
33
+
34
+
35
+ def _client_from_app() -> NovelCaptcha:
36
+ client = current_app.extensions.get("novelcaptcha")
37
+ if client is None:
38
+ raise RuntimeError(
39
+ "No NovelCaptcha client on app.extensions — "
40
+ "set app.extensions['novelcaptcha'] = NovelCaptcha(...) at startup."
41
+ )
42
+ return client
43
+
44
+
45
+ def _default_extract_ip() -> Optional[str]:
46
+ forwarded = request.headers.get("X-Forwarded-For")
47
+ if forwarded:
48
+ return forwarded.split(",")[0].strip() or None
49
+ real = request.headers.get("X-Real-IP")
50
+ if real:
51
+ return real.strip() or None
52
+ return request.remote_addr
53
+
54
+
55
+ def novelcaptcha_required(
56
+ *,
57
+ token_field: str = "captcha_token",
58
+ min_score: float = 0.5,
59
+ extract_ip: Callable[[], Optional[str]] = _default_extract_ip,
60
+ ) -> Callable[..., Any]:
61
+ """Decorate a Flask view to require a valid NovelCaptcha token.
62
+
63
+ On success the ``VerifyResult`` is attached to ``request.novelcaptcha``.
64
+ On failure the decorator aborts with 400/403/503 JSON responses.
65
+ """
66
+
67
+ def decorator(view: Callable[..., Any]) -> Callable[..., Any]:
68
+ @functools.wraps(view)
69
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
70
+ body = request.get_json(silent=True) or {}
71
+ token = body.get(token_field) if isinstance(body, dict) else None
72
+ if not isinstance(token, str) or not token:
73
+ return jsonify({"error": "missing_captcha_token"}), 400
74
+
75
+ client = _client_from_app()
76
+ try:
77
+ result = client.verify(token, remote_ip=extract_ip())
78
+ except InvalidTokenError as exc:
79
+ return (
80
+ jsonify({"error": "invalid_captcha_token", "codes": exc.error_codes}),
81
+ 400,
82
+ )
83
+ except NetworkError:
84
+ return jsonify({"error": "captcha_unavailable"}), 503
85
+
86
+ if result.score < min_score:
87
+ return (
88
+ jsonify({"error": "captcha_score_too_low", "score": result.score}),
89
+ 403,
90
+ )
91
+
92
+ request.novelcaptcha = result # type: ignore[attr-defined]
93
+ return view(*args, **kwargs)
94
+
95
+ return wrapper
96
+
97
+ return decorator
98
+
99
+
100
+ __all__ = ["novelcaptcha_required", "abort"]
novelcaptcha/types.py ADDED
@@ -0,0 +1,75 @@
1
+ """Type definitions (dataclasses) for the NovelCaptcha Python SDK."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import List
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class VerifyResult:
10
+ """Result of a successful :meth:`NovelCaptcha.verify` call.
11
+
12
+ Mirrors NovelCaptcha's ``/api/siteverify`` response with snake_case field
13
+ names.
14
+ """
15
+
16
+ success: bool
17
+ """Always ``True`` when ``verify`` returns (it raises otherwise)."""
18
+
19
+ score: float
20
+ """Trust score in ``[0.0, 1.0]``. Higher is safer."""
21
+
22
+ trust_score: float
23
+ """Alias for ``score`` — both fields carry the same value."""
24
+
25
+ challenge_ts: int
26
+ """Unix epoch (seconds) when the token was minted."""
27
+
28
+ hostname: str
29
+ """Hostname the token was minted for."""
30
+
31
+ action: str
32
+ """Action label captured at token mint time."""
33
+
34
+ note: str
35
+ """Free-form note attached by the rule engine, if any."""
36
+
37
+ context: str
38
+ """Context label bound when the backend issued the challenge key."""
39
+
40
+ visitor_id: str
41
+ """Stable per-visitor identifier."""
42
+
43
+ visitor_confidence: float
44
+ """Visitor identification confidence in ``[0.8, 0.99]``."""
45
+
46
+ visitor_decision: str
47
+ """``known_match`` / ``new_isolated`` / ``low_quality``."""
48
+
49
+ override_applied: bool
50
+ """``True`` when a dashboard rule forced the score."""
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class EmailClassificationResult:
55
+ """Result of :meth:`NovelCaptcha.classify_email`."""
56
+
57
+ classification: str
58
+ """One of ``"safe"``, ``"privacy/alias"``, ``"temp-mail"``."""
59
+
60
+ reasons: List[str] = field(default_factory=list)
61
+ """Human-readable reasons behind the classification."""
62
+
63
+ risk_score: float = 0.0
64
+ """Risk score in ``[0.0, 1.0]``. Higher means riskier."""
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class ChallengeResult:
69
+ """Result of :meth:`NovelCaptcha.create_challenge`."""
70
+
71
+ challenge_key: str
72
+ """One-time key passed to the browser SDK's ``execute(challengeKey)``."""
73
+
74
+ expires_at: int
75
+ """Unix epoch timestamp (seconds) when the challenge key expires."""
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: novelcaptcha
3
+ Version: 0.1.0
4
+ Summary: Python server SDK for NovelCaptcha. Verify tokens and classify emails.
5
+ Project-URL: Homepage, https://github.com/novelfoss/captcha
6
+ Project-URL: Repository, https://github.com/novelfoss/captcha
7
+ Project-URL: Issues, https://github.com/novelfoss/captcha/issues
8
+ Author: NovelCaptcha
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: bot-detection,captcha,fraud,novelcaptcha,server-sdk
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: Security
22
+ Requires-Python: >=3.9
23
+ Requires-Dist: httpx>=0.24
24
+ Provides-Extra: dev
25
+ Requires-Dist: mypy>=1.7; extra == 'dev'
26
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
27
+ Requires-Dist: pytest-httpx>=0.26; extra == 'dev'
28
+ Requires-Dist: pytest>=7.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.4; extra == 'dev'
30
+ Provides-Extra: fastapi
31
+ Requires-Dist: fastapi>=0.100; extra == 'fastapi'
32
+ Provides-Extra: flask
33
+ Requires-Dist: flask>=2.3; extra == 'flask'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # novelcaptcha
37
+
38
+ Python server SDK for [NovelCaptcha](https://github.com/novelfoss/captcha). Sync + async clients, plus drop-in FastAPI and Flask middleware.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install novelcaptcha
44
+ # with framework helpers:
45
+ pip install 'novelcaptcha[fastapi]'
46
+ pip install 'novelcaptcha[flask]'
47
+ ```
48
+
49
+ ## Quick start
50
+
51
+ ```python
52
+ from novelcaptcha import NovelCaptcha
53
+
54
+ client = NovelCaptcha(
55
+ secret_key="sec_...",
56
+ base_url="http://localhost:3020", # omit for SaaS
57
+ )
58
+
59
+ result = client.verify(token, remote_ip="203.0.113.5")
60
+ if result.score < 0.5:
61
+ raise PermissionError("score too low")
62
+ ```
63
+
64
+ ## Async
65
+
66
+ ```python
67
+ from novelcaptcha import AsyncNovelCaptcha
68
+
69
+ async with AsyncNovelCaptcha(secret_key="sec_...") as client:
70
+ result = await client.verify(token)
71
+ ```
72
+
73
+ ## FastAPI
74
+
75
+ ```python
76
+ from fastapi import FastAPI, Depends
77
+ from novelcaptcha import AsyncNovelCaptcha
78
+ from novelcaptcha.fastapi import verify_captcha
79
+
80
+ app = FastAPI()
81
+
82
+ @app.on_event("startup")
83
+ async def on_startup():
84
+ app.state.novelcaptcha = AsyncNovelCaptcha(secret_key="sec_...")
85
+
86
+ @app.post("/login")
87
+ async def login(captcha = verify_captcha(token_field="captcha_token", min_score=0.5)):
88
+ # captcha is the VerifyResult — only reached when score >= 0.5
89
+ return {"visitor_id": captcha.visitor_id}
90
+ ```
91
+
92
+ ## Flask
93
+
94
+ ```python
95
+ from flask import Flask, request
96
+ from novelcaptcha import NovelCaptcha
97
+ from novelcaptcha.flask import novelcaptcha_required
98
+
99
+ app = Flask(__name__)
100
+ app.extensions["novelcaptcha"] = NovelCaptcha(secret_key="sec_...")
101
+
102
+ @app.post("/login")
103
+ @novelcaptcha_required(token_field="captcha_token", min_score=0.5)
104
+ def login():
105
+ result = request.novelcaptcha
106
+ return {"visitor_id": result.visitor_id}
107
+ ```
108
+
109
+ ## API
110
+
111
+ ### `NovelCaptcha(secret_key, *, base_url=..., timeout=10.0)`
112
+
113
+ Sync client. `AsyncNovelCaptcha` has the same constructor signature.
114
+
115
+ ### `client.verify(token, *, remote_ip=None) -> VerifyResult`
116
+
117
+ Fields: `score`, `trust_score`, `challenge_ts`, `hostname`, `action`, `note`, `context`, `visitor_id`, `visitor_confidence`, `visitor_decision`, `override_applied`.
118
+
119
+ ### `client.classify_email(email, *, sitekey=None) -> EmailClassificationResult`
120
+
121
+ Fields: `classification` (`safe` / `privacy/alias` / `temp-mail`), `reasons`, `risk_score`.
122
+
123
+ ## Errors
124
+
125
+ ```python
126
+ from novelcaptcha import (
127
+ NovelCaptchaError,
128
+ InvalidTokenError,
129
+ InvalidSecretError,
130
+ NetworkError,
131
+ TimeoutError,
132
+ )
133
+ ```
134
+
135
+ All errors subclass `NovelCaptchaError`.
136
+
137
+ ## License
138
+
139
+ MIT
@@ -0,0 +1,10 @@
1
+ novelcaptcha/__init__.py,sha256=MbSnGeEshGzQxKzVVSiAnjLyP_Y-vWGXAHHuQZoWtbo,1194
2
+ novelcaptcha/client.py,sha256=NroCE7GbpXQPkgkmWbljwAmp6m8NYFqddOpYBRN7HFg,22331
3
+ novelcaptcha/errors.py,sha256=kivb_o6RDKhxrYirITzMc5_gMcel3f8074mgi8sSXR0,2047
4
+ novelcaptcha/fastapi.py,sha256=TPbkPt7HDeO9xYR2-sn08ML1CxarKXUh6dBltIIdJZg,3405
5
+ novelcaptcha/flask.py,sha256=CuCGCrDKJ7HpYnTl4FBd76v4-GiX6qy13fdAH_v8qxo,3363
6
+ novelcaptcha/types.py,sha256=UpTcq0EMgTaM-xSUEgesgkZbgn--2-ghE-YBxyMMGZ0,2148
7
+ novelcaptcha-0.1.0.dist-info/METADATA,sha256=HBAQl-h1cY6c9U4KaK-QCIuyCsQtQmA-T80JFSbvzyk,3852
8
+ novelcaptcha-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
9
+ novelcaptcha-0.1.0.dist-info/licenses/LICENSE,sha256=4W2RW3-qz4WTXTVa0EAfqGVe1qvhBHYSagDRd2BTrHU,1098
10
+ novelcaptcha-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) NovelCaptcha contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.