captchakit 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.
- captchakit/__init__.py +47 -0
- captchakit/_clock.py +23 -0
- captchakit/adapters/__init__.py +1 -0
- captchakit/adapters/fastapi.py +143 -0
- captchakit/challenges/__init__.py +15 -0
- captchakit/challenges/base.py +52 -0
- captchakit/challenges/math.py +50 -0
- captchakit/challenges/text.py +37 -0
- captchakit/errors.py +43 -0
- captchakit/manager.py +91 -0
- captchakit/py.typed +0 -0
- captchakit/renderers/__init__.py +8 -0
- captchakit/renderers/base.py +17 -0
- captchakit/renderers/image.py +91 -0
- captchakit/storage/__init__.py +8 -0
- captchakit/storage/base.py +29 -0
- captchakit/storage/memory.py +63 -0
- captchakit-0.1.0.dist-info/METADATA +199 -0
- captchakit-0.1.0.dist-info/RECORD +21 -0
- captchakit-0.1.0.dist-info/WHEEL +4 -0
- captchakit-0.1.0.dist-info/licenses/LICENSE +21 -0
captchakit/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""captchakit — async-first, typed captcha library."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from captchakit._clock import Clock, MonotonicClock
|
|
6
|
+
from captchakit.challenges import (
|
|
7
|
+
Challenge,
|
|
8
|
+
ChallengeFactory,
|
|
9
|
+
ChallengeSpec,
|
|
10
|
+
MathChallengeFactory,
|
|
11
|
+
TextChallengeFactory,
|
|
12
|
+
)
|
|
13
|
+
from captchakit.errors import (
|
|
14
|
+
CaptchaKitError,
|
|
15
|
+
ChallengeError,
|
|
16
|
+
ChallengeExpired,
|
|
17
|
+
ChallengeNotFound,
|
|
18
|
+
StorageError,
|
|
19
|
+
TooManyAttempts,
|
|
20
|
+
)
|
|
21
|
+
from captchakit.manager import CaptchaManager
|
|
22
|
+
from captchakit.renderers import ImageRenderer, Renderer
|
|
23
|
+
from captchakit.storage import MemoryStorage, Storage
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"CaptchaKitError",
|
|
29
|
+
"CaptchaManager",
|
|
30
|
+
"Challenge",
|
|
31
|
+
"ChallengeError",
|
|
32
|
+
"ChallengeExpired",
|
|
33
|
+
"ChallengeFactory",
|
|
34
|
+
"ChallengeNotFound",
|
|
35
|
+
"ChallengeSpec",
|
|
36
|
+
"Clock",
|
|
37
|
+
"ImageRenderer",
|
|
38
|
+
"MathChallengeFactory",
|
|
39
|
+
"MemoryStorage",
|
|
40
|
+
"MonotonicClock",
|
|
41
|
+
"Renderer",
|
|
42
|
+
"Storage",
|
|
43
|
+
"StorageError",
|
|
44
|
+
"TextChallengeFactory",
|
|
45
|
+
"TooManyAttempts",
|
|
46
|
+
"__version__",
|
|
47
|
+
]
|
captchakit/_clock.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Time abstraction so tests can inject deterministic clocks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Protocol, runtime_checkable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@runtime_checkable
|
|
10
|
+
class Clock(Protocol):
|
|
11
|
+
"""Minimal monotonic-time interface."""
|
|
12
|
+
|
|
13
|
+
def now(self) -> float: # pragma: no cover - protocol
|
|
14
|
+
...
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MonotonicClock:
|
|
18
|
+
"""Default clock backed by :func:`time.monotonic`."""
|
|
19
|
+
|
|
20
|
+
__slots__ = ()
|
|
21
|
+
|
|
22
|
+
def now(self) -> float:
|
|
23
|
+
return time.monotonic()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Framework adapters (opt-in via extras)."""
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""FastAPI adapter.
|
|
2
|
+
|
|
3
|
+
Install with ``pip install "captchakit[fastapi]"``.
|
|
4
|
+
|
|
5
|
+
Usage::
|
|
6
|
+
|
|
7
|
+
from fastapi import FastAPI
|
|
8
|
+
from captchakit import CaptchaManager, TextChallengeFactory, ImageRenderer, MemoryStorage
|
|
9
|
+
from captchakit.adapters.fastapi import captcha_router, verify_captcha
|
|
10
|
+
|
|
11
|
+
manager = CaptchaManager(
|
|
12
|
+
factory=TextChallengeFactory(),
|
|
13
|
+
renderer=ImageRenderer(),
|
|
14
|
+
storage=MemoryStorage(),
|
|
15
|
+
)
|
|
16
|
+
app = FastAPI()
|
|
17
|
+
app.include_router(captcha_router(manager, prefix="/captcha"))
|
|
18
|
+
|
|
19
|
+
@app.post("/register")
|
|
20
|
+
async def register(_: None = Depends(verify_captcha(manager))):
|
|
21
|
+
return {"ok": True}
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from enum import Enum
|
|
27
|
+
from typing import TYPE_CHECKING, Annotated, Any
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
from fastapi import APIRouter, Depends, Form, HTTPException, Response, status
|
|
31
|
+
except ImportError as exc: # pragma: no cover
|
|
32
|
+
raise ImportError(
|
|
33
|
+
"FastAPI adapter requires the `fastapi` extra: pip install 'captchakit[fastapi]'"
|
|
34
|
+
) from exc
|
|
35
|
+
|
|
36
|
+
from captchakit.errors import (
|
|
37
|
+
ChallengeExpired,
|
|
38
|
+
ChallengeNotFound,
|
|
39
|
+
TooManyAttempts,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
if TYPE_CHECKING:
|
|
43
|
+
from collections.abc import Callable, Coroutine
|
|
44
|
+
|
|
45
|
+
from captchakit.manager import CaptchaManager
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def captcha_router(
|
|
49
|
+
manager: CaptchaManager,
|
|
50
|
+
*,
|
|
51
|
+
prefix: str = "/captcha",
|
|
52
|
+
tags: list[str] | None = None,
|
|
53
|
+
) -> APIRouter:
|
|
54
|
+
"""Build an :class:`APIRouter` that exposes ``/new`` and ``/{id}.png``.
|
|
55
|
+
|
|
56
|
+
Routes
|
|
57
|
+
------
|
|
58
|
+
``POST {prefix}/new`` → ``{"id": str}``. The client then fetches the image.
|
|
59
|
+
``GET {prefix}/{id}.png`` → PNG bytes (``image/png``).
|
|
60
|
+
``POST {prefix}/verify`` (form: ``id``, ``answer``) → ``{"ok": bool}``.
|
|
61
|
+
"""
|
|
62
|
+
_tags: list[str | Enum] = [*(tags or ["captcha"])]
|
|
63
|
+
router = APIRouter(prefix=prefix, tags=_tags)
|
|
64
|
+
images: dict[str, bytes] = {}
|
|
65
|
+
|
|
66
|
+
@router.post("/new")
|
|
67
|
+
async def new_challenge() -> dict[str, str]:
|
|
68
|
+
cid, png = await manager.issue()
|
|
69
|
+
images[cid] = png
|
|
70
|
+
return {"id": cid, "image_url": f"{prefix}/{cid}.png"}
|
|
71
|
+
|
|
72
|
+
@router.get("/{challenge_id}.png")
|
|
73
|
+
async def get_image(challenge_id: str) -> Response:
|
|
74
|
+
png = images.pop(challenge_id, None)
|
|
75
|
+
if png is None:
|
|
76
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found")
|
|
77
|
+
return Response(content=png, media_type=manager.renderer.content_type)
|
|
78
|
+
|
|
79
|
+
@router.post("/verify")
|
|
80
|
+
async def do_verify(
|
|
81
|
+
challenge_id: Annotated[str, Form(alias="id")],
|
|
82
|
+
answer: Annotated[str, Form()],
|
|
83
|
+
) -> dict[str, bool]:
|
|
84
|
+
try:
|
|
85
|
+
ok = await manager.verify(challenge_id, answer)
|
|
86
|
+
except ChallengeNotFound as exc:
|
|
87
|
+
raise HTTPException(
|
|
88
|
+
status_code=status.HTTP_404_NOT_FOUND, detail="challenge not found"
|
|
89
|
+
) from exc
|
|
90
|
+
except ChallengeExpired as exc:
|
|
91
|
+
raise HTTPException(
|
|
92
|
+
status_code=status.HTTP_410_GONE, detail="challenge expired"
|
|
93
|
+
) from exc
|
|
94
|
+
except TooManyAttempts as exc:
|
|
95
|
+
raise HTTPException(
|
|
96
|
+
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
97
|
+
detail="too many attempts",
|
|
98
|
+
) from exc
|
|
99
|
+
return {"ok": ok}
|
|
100
|
+
|
|
101
|
+
return router
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def verify_captcha(
|
|
105
|
+
manager: CaptchaManager,
|
|
106
|
+
) -> Callable[..., Coroutine[Any, Any, None]]:
|
|
107
|
+
"""Dependency that verifies a captcha submitted as form fields.
|
|
108
|
+
|
|
109
|
+
Expected fields (``application/x-www-form-urlencoded`` or multipart):
|
|
110
|
+
|
|
111
|
+
* ``captcha_id`` — id returned by ``POST /captcha/new``
|
|
112
|
+
* ``captcha_answer`` — the user's answer
|
|
113
|
+
|
|
114
|
+
On success, returns ``None`` so the wrapped route body runs. On failure,
|
|
115
|
+
raises the appropriate :class:`HTTPException` (404 / 410 / 429 / 403).
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
async def _dep(
|
|
119
|
+
captcha_id: Annotated[str, Form()],
|
|
120
|
+
captcha_answer: Annotated[str, Form()],
|
|
121
|
+
) -> None:
|
|
122
|
+
try:
|
|
123
|
+
ok = await manager.verify(captcha_id, captcha_answer)
|
|
124
|
+
except ChallengeNotFound as exc:
|
|
125
|
+
raise HTTPException(
|
|
126
|
+
status_code=status.HTTP_404_NOT_FOUND, detail="challenge not found"
|
|
127
|
+
) from exc
|
|
128
|
+
except ChallengeExpired as exc:
|
|
129
|
+
raise HTTPException(
|
|
130
|
+
status_code=status.HTTP_410_GONE, detail="challenge expired"
|
|
131
|
+
) from exc
|
|
132
|
+
except TooManyAttempts as exc:
|
|
133
|
+
raise HTTPException(
|
|
134
|
+
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
135
|
+
detail="too many attempts",
|
|
136
|
+
) from exc
|
|
137
|
+
if not ok:
|
|
138
|
+
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="wrong answer")
|
|
139
|
+
|
|
140
|
+
return _dep
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
__all__ = ["Depends", "captcha_router", "verify_captcha"]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Challenge types and factories."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from captchakit.challenges.base import Challenge, ChallengeFactory, ChallengeSpec
|
|
6
|
+
from captchakit.challenges.math import MathChallengeFactory
|
|
7
|
+
from captchakit.challenges.text import TextChallengeFactory
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Challenge",
|
|
11
|
+
"ChallengeFactory",
|
|
12
|
+
"ChallengeSpec",
|
|
13
|
+
"MathChallengeFactory",
|
|
14
|
+
"TextChallengeFactory",
|
|
15
|
+
]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Core challenge protocol and dataclasses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Protocol, runtime_checkable
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class ChallengeSpec:
|
|
12
|
+
"""A challenge's raw content before an id/TTL is attached.
|
|
13
|
+
|
|
14
|
+
Produced by a :class:`ChallengeFactory`; the :class:`~captchakit.CaptchaManager`
|
|
15
|
+
wraps it into a :class:`Challenge` with identifier and timestamps.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
prompt: str
|
|
19
|
+
solution: str
|
|
20
|
+
case_sensitive: bool = False
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class Challenge:
|
|
25
|
+
"""A complete captcha challenge stored by the manager."""
|
|
26
|
+
|
|
27
|
+
id: str
|
|
28
|
+
prompt: str
|
|
29
|
+
solution: str
|
|
30
|
+
created_at: float
|
|
31
|
+
expires_at: float
|
|
32
|
+
case_sensitive: bool = False
|
|
33
|
+
|
|
34
|
+
def is_expired(self, now: float) -> bool:
|
|
35
|
+
return now > self.expires_at
|
|
36
|
+
|
|
37
|
+
def check(self, user_input: str) -> bool:
|
|
38
|
+
"""Constant-time comparison against the expected solution."""
|
|
39
|
+
expected = self.solution
|
|
40
|
+
got = user_input.strip()
|
|
41
|
+
if not self.case_sensitive:
|
|
42
|
+
expected = expected.casefold()
|
|
43
|
+
got = got.casefold()
|
|
44
|
+
return hmac.compare_digest(expected.encode("utf-8"), got.encode("utf-8"))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@runtime_checkable
|
|
48
|
+
class ChallengeFactory(Protocol):
|
|
49
|
+
"""Produces fresh :class:`ChallengeSpec` instances on demand."""
|
|
50
|
+
|
|
51
|
+
async def create(self) -> ChallengeSpec: # pragma: no cover - protocol
|
|
52
|
+
...
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Simple arithmetic challenges."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from captchakit.challenges.base import ChallengeSpec
|
|
10
|
+
|
|
11
|
+
Operator = Literal["+", "-", "*"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(slots=True)
|
|
15
|
+
class MathChallengeFactory:
|
|
16
|
+
"""Produces easy arithmetic puzzles such as ``"7 + 3 = ?"``.
|
|
17
|
+
|
|
18
|
+
Results of subtractions are always non-negative: operands are swapped when
|
|
19
|
+
needed so the user never has to deal with negative numbers.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
min_operand: int = 1
|
|
23
|
+
max_operand: int = 9
|
|
24
|
+
operators: tuple[Operator, ...] = field(default_factory=lambda: ("+", "-"))
|
|
25
|
+
|
|
26
|
+
def __post_init__(self) -> None:
|
|
27
|
+
if self.min_operand < 0:
|
|
28
|
+
raise ValueError("min_operand must be >= 0")
|
|
29
|
+
if self.max_operand < self.min_operand:
|
|
30
|
+
raise ValueError("max_operand must be >= min_operand")
|
|
31
|
+
if not self.operators:
|
|
32
|
+
raise ValueError("operators must be non-empty")
|
|
33
|
+
|
|
34
|
+
def _rand(self) -> int:
|
|
35
|
+
return secrets.randbelow(self.max_operand - self.min_operand + 1) + self.min_operand
|
|
36
|
+
|
|
37
|
+
async def create(self) -> ChallengeSpec:
|
|
38
|
+
a = self._rand()
|
|
39
|
+
b = self._rand()
|
|
40
|
+
op: Operator = secrets.choice(self.operators)
|
|
41
|
+
if op == "-" and b > a:
|
|
42
|
+
a, b = b, a
|
|
43
|
+
if op == "+":
|
|
44
|
+
result = a + b
|
|
45
|
+
elif op == "-":
|
|
46
|
+
result = a - b
|
|
47
|
+
else:
|
|
48
|
+
result = a * b
|
|
49
|
+
prompt = f"{a} {op} {b} = ?"
|
|
50
|
+
return ChallengeSpec(prompt=prompt, solution=str(result), case_sensitive=False)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Alphanumeric text challenges."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from captchakit.challenges.base import ChallengeSpec
|
|
9
|
+
|
|
10
|
+
DEFAULT_CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(slots=True)
|
|
14
|
+
class TextChallengeFactory:
|
|
15
|
+
"""Produces random alphanumeric strings.
|
|
16
|
+
|
|
17
|
+
The default charset omits visually ambiguous characters
|
|
18
|
+
(``I``, ``O``, ``0``, ``1``) so a user isn't penalised for font choice.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
length: int = 5
|
|
22
|
+
charset: str = DEFAULT_CHARSET
|
|
23
|
+
case_sensitive: bool = False
|
|
24
|
+
|
|
25
|
+
def __post_init__(self) -> None:
|
|
26
|
+
if self.length < 1:
|
|
27
|
+
raise ValueError("length must be >= 1")
|
|
28
|
+
if not self.charset:
|
|
29
|
+
raise ValueError("charset must be non-empty")
|
|
30
|
+
|
|
31
|
+
async def create(self) -> ChallengeSpec:
|
|
32
|
+
solution = "".join(secrets.choice(self.charset) for _ in range(self.length))
|
|
33
|
+
return ChallengeSpec(
|
|
34
|
+
prompt=solution,
|
|
35
|
+
solution=solution,
|
|
36
|
+
case_sensitive=self.case_sensitive,
|
|
37
|
+
)
|
captchakit/errors.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Exception hierarchy for captchakit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CaptchaKitError(Exception):
|
|
7
|
+
"""Base class for all captchakit exceptions."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ChallengeError(CaptchaKitError):
|
|
11
|
+
"""Base for errors that reference a specific challenge id.
|
|
12
|
+
|
|
13
|
+
Catch this to handle :class:`ChallengeNotFound`, :class:`ChallengeExpired`
|
|
14
|
+
and :class:`TooManyAttempts` uniformly.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
_template: str = "challenge error: {id!r}"
|
|
18
|
+
|
|
19
|
+
def __init__(self, challenge_id: str) -> None:
|
|
20
|
+
super().__init__(self._template.format(id=challenge_id))
|
|
21
|
+
self.challenge_id: str = challenge_id
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ChallengeNotFound(ChallengeError):
|
|
25
|
+
"""The referenced challenge id does not exist in storage."""
|
|
26
|
+
|
|
27
|
+
_template = "challenge not found: {id!r}"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ChallengeExpired(ChallengeError):
|
|
31
|
+
"""The challenge has passed its expiration time."""
|
|
32
|
+
|
|
33
|
+
_template = "challenge expired: {id!r}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TooManyAttempts(ChallengeError):
|
|
37
|
+
"""The allowed number of verification attempts has been exceeded."""
|
|
38
|
+
|
|
39
|
+
_template = "too many attempts for challenge: {id!r}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class StorageError(CaptchaKitError):
|
|
43
|
+
"""Underlying storage backend failed."""
|
captchakit/manager.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""High-level orchestrator: issue, verify, cleanup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
from captchakit._clock import Clock, MonotonicClock
|
|
9
|
+
from captchakit.challenges.base import Challenge, ChallengeFactory
|
|
10
|
+
from captchakit.errors import ChallengeExpired, ChallengeNotFound, TooManyAttempts
|
|
11
|
+
from captchakit.renderers.base import Renderer
|
|
12
|
+
from captchakit.storage.base import Storage
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True)
|
|
16
|
+
class CaptchaManager:
|
|
17
|
+
"""Coordinates a :class:`ChallengeFactory`, :class:`Renderer` and :class:`Storage`.
|
|
18
|
+
|
|
19
|
+
Typical usage::
|
|
20
|
+
|
|
21
|
+
manager = CaptchaManager(
|
|
22
|
+
factory=TextChallengeFactory(),
|
|
23
|
+
renderer=ImageRenderer(),
|
|
24
|
+
storage=MemoryStorage(),
|
|
25
|
+
ttl=120.0,
|
|
26
|
+
)
|
|
27
|
+
challenge_id, png = await manager.issue()
|
|
28
|
+
...
|
|
29
|
+
ok = await manager.verify(challenge_id, user_input)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
factory: ChallengeFactory
|
|
33
|
+
renderer: Renderer
|
|
34
|
+
storage: Storage
|
|
35
|
+
ttl: float = 120.0
|
|
36
|
+
max_attempts: int = 3
|
|
37
|
+
clock: Clock = field(default_factory=MonotonicClock)
|
|
38
|
+
|
|
39
|
+
def __post_init__(self) -> None:
|
|
40
|
+
if self.ttl <= 0:
|
|
41
|
+
raise ValueError("ttl must be > 0")
|
|
42
|
+
if self.max_attempts < 1:
|
|
43
|
+
raise ValueError("max_attempts must be >= 1")
|
|
44
|
+
|
|
45
|
+
async def issue(self) -> tuple[str, bytes]:
|
|
46
|
+
"""Create and persist a fresh challenge, return ``(id, image_bytes)``."""
|
|
47
|
+
spec = await self.factory.create()
|
|
48
|
+
now = self.clock.now()
|
|
49
|
+
challenge = Challenge(
|
|
50
|
+
id=uuid4().hex,
|
|
51
|
+
prompt=spec.prompt,
|
|
52
|
+
solution=spec.solution,
|
|
53
|
+
case_sensitive=spec.case_sensitive,
|
|
54
|
+
created_at=now,
|
|
55
|
+
expires_at=now + self.ttl,
|
|
56
|
+
)
|
|
57
|
+
image = await self.renderer.render(challenge)
|
|
58
|
+
await self.storage.put(challenge)
|
|
59
|
+
return challenge.id, image
|
|
60
|
+
|
|
61
|
+
async def verify(self, challenge_id: str, user_input: str) -> bool:
|
|
62
|
+
"""Check a user's answer.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
``True`` if the answer matches (the challenge is then deleted),
|
|
66
|
+
``False`` if the answer is wrong but the user still has attempts left.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
ChallengeNotFound: No such challenge (already consumed, never issued,
|
|
70
|
+
or evicted by TTL).
|
|
71
|
+
ChallengeExpired: The challenge passed its expiration time.
|
|
72
|
+
TooManyAttempts: This was the final attempt and it was wrong.
|
|
73
|
+
"""
|
|
74
|
+
challenge = await self.storage.get(challenge_id)
|
|
75
|
+
if challenge is None:
|
|
76
|
+
raise ChallengeNotFound(challenge_id)
|
|
77
|
+
if challenge.is_expired(self.clock.now()):
|
|
78
|
+
await self.storage.delete(challenge_id)
|
|
79
|
+
raise ChallengeExpired(challenge_id)
|
|
80
|
+
attempts = await self.storage.incr_attempts(challenge_id)
|
|
81
|
+
if challenge.check(user_input):
|
|
82
|
+
await self.storage.delete(challenge_id)
|
|
83
|
+
return True
|
|
84
|
+
if attempts >= self.max_attempts:
|
|
85
|
+
await self.storage.delete(challenge_id)
|
|
86
|
+
raise TooManyAttempts(challenge_id)
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
async def discard(self, challenge_id: str) -> None:
|
|
90
|
+
"""Remove a challenge without checking it (e.g. on user cancel)."""
|
|
91
|
+
await self.storage.delete(challenge_id)
|
captchakit/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Renderer protocol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol, runtime_checkable
|
|
6
|
+
|
|
7
|
+
from captchakit.challenges.base import Challenge
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@runtime_checkable
|
|
11
|
+
class Renderer(Protocol):
|
|
12
|
+
"""Turns a :class:`Challenge` into bytes (typically an image)."""
|
|
13
|
+
|
|
14
|
+
content_type: str
|
|
15
|
+
|
|
16
|
+
async def render(self, challenge: Challenge) -> bytes: # pragma: no cover - protocol
|
|
17
|
+
...
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Pillow-backed image renderer.
|
|
2
|
+
|
|
3
|
+
CPU-bound drawing is offloaded to a worker thread via :func:`asyncio.to_thread`
|
|
4
|
+
so callers can treat the renderer as fully async.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import random
|
|
11
|
+
import secrets
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from io import BytesIO
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from captchakit.challenges.base import Challenge
|
|
21
|
+
|
|
22
|
+
RGB = tuple[int, int, int]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _default_palette() -> tuple[RGB, ...]:
|
|
26
|
+
return (
|
|
27
|
+
(30, 30, 30),
|
|
28
|
+
(60, 20, 120),
|
|
29
|
+
(20, 80, 40),
|
|
30
|
+
(140, 30, 40),
|
|
31
|
+
(10, 60, 100),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(slots=True)
|
|
36
|
+
class ImageRenderer:
|
|
37
|
+
"""Renders a challenge's prompt into a PNG.
|
|
38
|
+
|
|
39
|
+
The renderer is intentionally simple: it draws the prompt glyph-by-glyph
|
|
40
|
+
with small random rotations / offsets and a few decorative lines. It is
|
|
41
|
+
*not* meant to defeat OCR — it's a light human-check layer (see SECURITY
|
|
42
|
+
notes in the README).
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
width: int = 220
|
|
46
|
+
height: int = 80
|
|
47
|
+
padding: int = 10
|
|
48
|
+
font_size: int = 40
|
|
49
|
+
font_path: str | Path | None = None
|
|
50
|
+
bg_color: RGB = (245, 245, 245)
|
|
51
|
+
palette: tuple[RGB, ...] = field(default_factory=_default_palette)
|
|
52
|
+
noise_lines: int = 4
|
|
53
|
+
content_type: str = "image/png"
|
|
54
|
+
|
|
55
|
+
def _load_font(self) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
|
|
56
|
+
if self.font_path is not None:
|
|
57
|
+
return ImageFont.truetype(str(self.font_path), self.font_size)
|
|
58
|
+
return ImageFont.load_default(size=self.font_size)
|
|
59
|
+
|
|
60
|
+
def _render_sync(self, text: str) -> bytes:
|
|
61
|
+
rng = random.Random(secrets.randbits(64))
|
|
62
|
+
img = Image.new("RGB", (self.width, self.height), self.bg_color)
|
|
63
|
+
draw = ImageDraw.Draw(img)
|
|
64
|
+
font = self._load_font()
|
|
65
|
+
|
|
66
|
+
for _ in range(self.noise_lines):
|
|
67
|
+
x1 = rng.randint(0, self.width)
|
|
68
|
+
y1 = rng.randint(0, self.height)
|
|
69
|
+
x2 = rng.randint(0, self.width)
|
|
70
|
+
y2 = rng.randint(0, self.height)
|
|
71
|
+
draw.line((x1, y1, x2, y2), fill=rng.choice(self.palette), width=1)
|
|
72
|
+
|
|
73
|
+
inner_w = self.width - 2 * self.padding
|
|
74
|
+
n = max(len(text), 1)
|
|
75
|
+
step = inner_w / n
|
|
76
|
+
for idx, ch in enumerate(text):
|
|
77
|
+
glyph = Image.new("RGBA", (self.font_size + 16, self.font_size + 16), (0, 0, 0, 0))
|
|
78
|
+
gdraw = ImageDraw.Draw(glyph)
|
|
79
|
+
gdraw.text((8, 4), ch, font=font, fill=rng.choice(self.palette))
|
|
80
|
+
angle = rng.uniform(-25, 25)
|
|
81
|
+
rotated = glyph.rotate(angle, resample=Image.Resampling.BICUBIC, expand=False)
|
|
82
|
+
x = int(self.padding + idx * step + rng.uniform(-2, 2))
|
|
83
|
+
y = int((self.height - rotated.height) / 2 + rng.uniform(-4, 4))
|
|
84
|
+
img.paste(rotated, (x, y), rotated)
|
|
85
|
+
|
|
86
|
+
buf = BytesIO()
|
|
87
|
+
img.save(buf, format="PNG", optimize=True)
|
|
88
|
+
return buf.getvalue()
|
|
89
|
+
|
|
90
|
+
async def render(self, challenge: Challenge) -> bytes:
|
|
91
|
+
return await asyncio.to_thread(self._render_sync, challenge.prompt)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Storage protocol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol, runtime_checkable
|
|
6
|
+
|
|
7
|
+
from captchakit.challenges.base import Challenge
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@runtime_checkable
|
|
11
|
+
class Storage(Protocol):
|
|
12
|
+
"""Persists challenges while they are live.
|
|
13
|
+
|
|
14
|
+
Implementations MUST be safe under concurrent async access from a single
|
|
15
|
+
event loop. Multi-process safety is the backend's own responsibility
|
|
16
|
+
(e.g. Redis is multi-process-safe; in-memory is not).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
async def put(self, challenge: Challenge) -> None: # pragma: no cover - protocol
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
async def get(self, challenge_id: str) -> Challenge | None: # pragma: no cover - protocol
|
|
23
|
+
...
|
|
24
|
+
|
|
25
|
+
async def delete(self, challenge_id: str) -> None: # pragma: no cover - protocol
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
async def incr_attempts(self, challenge_id: str) -> int: # pragma: no cover - protocol
|
|
29
|
+
...
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""In-process storage backed by a dict and an asyncio lock."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
from captchakit._clock import Clock, MonotonicClock
|
|
9
|
+
from captchakit.challenges.base import Challenge
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(slots=True)
|
|
13
|
+
class MemoryStorage:
|
|
14
|
+
"""Dict-based storage with a single :class:`asyncio.Lock`.
|
|
15
|
+
|
|
16
|
+
Suitable for single-process deployments and tests. For multi-process
|
|
17
|
+
setups (e.g. gunicorn with multiple workers) use a shared backend such as
|
|
18
|
+
:class:`~captchakit.storage.redis.RedisStorage` (optional extra).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
clock: Clock = field(default_factory=MonotonicClock)
|
|
22
|
+
_data: dict[str, Challenge] = field(default_factory=dict, init=False)
|
|
23
|
+
_attempts: dict[str, int] = field(default_factory=dict, init=False)
|
|
24
|
+
_lock: asyncio.Lock = field(default_factory=asyncio.Lock, init=False)
|
|
25
|
+
|
|
26
|
+
async def put(self, challenge: Challenge) -> None:
|
|
27
|
+
async with self._lock:
|
|
28
|
+
self._data[challenge.id] = challenge
|
|
29
|
+
self._attempts[challenge.id] = 0
|
|
30
|
+
|
|
31
|
+
async def get(self, challenge_id: str) -> Challenge | None:
|
|
32
|
+
async with self._lock:
|
|
33
|
+
return self._data.get(challenge_id)
|
|
34
|
+
|
|
35
|
+
async def delete(self, challenge_id: str) -> None:
|
|
36
|
+
async with self._lock:
|
|
37
|
+
self._data.pop(challenge_id, None)
|
|
38
|
+
self._attempts.pop(challenge_id, None)
|
|
39
|
+
|
|
40
|
+
async def incr_attempts(self, challenge_id: str) -> int:
|
|
41
|
+
async with self._lock:
|
|
42
|
+
if challenge_id not in self._data:
|
|
43
|
+
return 0
|
|
44
|
+
self._attempts[challenge_id] = self._attempts.get(challenge_id, 0) + 1
|
|
45
|
+
return self._attempts[challenge_id]
|
|
46
|
+
|
|
47
|
+
async def cleanup_expired(self) -> int:
|
|
48
|
+
"""Remove every challenge whose ``expires_at`` is in the past.
|
|
49
|
+
|
|
50
|
+
Returns the number of entries evicted. Safe to call from a background
|
|
51
|
+
task; intended to be scheduled periodically by the host application.
|
|
52
|
+
"""
|
|
53
|
+
now = self.clock.now()
|
|
54
|
+
async with self._lock:
|
|
55
|
+
dead = [cid for cid, ch in self._data.items() if ch.is_expired(now)]
|
|
56
|
+
for cid in dead:
|
|
57
|
+
self._data.pop(cid, None)
|
|
58
|
+
self._attempts.pop(cid, None)
|
|
59
|
+
return len(dead)
|
|
60
|
+
|
|
61
|
+
async def size(self) -> int:
|
|
62
|
+
async with self._lock:
|
|
63
|
+
return len(self._data)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: captchakit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async-first, fully type-hinted, minimal captcha library with adapters for aiogram, FastAPI and Discord.
|
|
5
|
+
Project-URL: Homepage, https://github.com/akerem16/captchakit
|
|
6
|
+
Project-URL: Repository, https://github.com/akerem16/captchakit
|
|
7
|
+
Project-URL: Issues, https://github.com/akerem16/captchakit/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/akerem16/captchakit/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: akerem16 <pypi@kerempy.com.tr>
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: aiogram,async,asyncio,bot,captcha,discord,fastapi,verification
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Framework :: FastAPI
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
26
|
+
Classifier: Topic :: Security
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Requires-Dist: pillow<13,>=10.0
|
|
30
|
+
Provides-Extra: aiogram
|
|
31
|
+
Requires-Dist: aiogram>=3.4; extra == 'aiogram'
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: fastapi>=0.110; extra == 'dev'
|
|
34
|
+
Requires-Dist: httpx>=0.27; extra == 'dev'
|
|
35
|
+
Requires-Dist: hypothesis>=6.100; extra == 'dev'
|
|
36
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
37
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
38
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
39
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
40
|
+
Requires-Dist: python-multipart>=0.0.9; extra == 'dev'
|
|
41
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
42
|
+
Requires-Dist: uvicorn[standard]>=0.30; extra == 'dev'
|
|
43
|
+
Provides-Extra: discord
|
|
44
|
+
Requires-Dist: discord-py>=2.3; extra == 'discord'
|
|
45
|
+
Provides-Extra: docs
|
|
46
|
+
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
|
|
47
|
+
Requires-Dist: mkdocstrings[python]>=0.25; extra == 'docs'
|
|
48
|
+
Provides-Extra: fastapi
|
|
49
|
+
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
|
|
50
|
+
Requires-Dist: python-multipart>=0.0.9; extra == 'fastapi'
|
|
51
|
+
Provides-Extra: redis
|
|
52
|
+
Requires-Dist: redis>=5.0; extra == 'redis'
|
|
53
|
+
Description-Content-Type: text/markdown
|
|
54
|
+
|
|
55
|
+
# captchakit
|
|
56
|
+
|
|
57
|
+
> **Async-first, fully type-hinted captcha library for Python 3.10+.**
|
|
58
|
+
> Zero runtime deps beyond Pillow. Drop-in adapters for FastAPI, aiogram and discord.py.
|
|
59
|
+
|
|
60
|
+
[](https://pypi.org/project/captchakit/)
|
|
61
|
+
[](https://pypi.org/project/captchakit/)
|
|
62
|
+
[](https://github.com/akerem16/captchakit/actions/workflows/ci.yml)
|
|
63
|
+
[](http://mypy-lang.org/)
|
|
64
|
+
[](https://github.com/astral-sh/ruff)
|
|
65
|
+
[](LICENSE)
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## Why another one?
|
|
70
|
+
|
|
71
|
+
| Feature | `lepture/captcha` | `claptcha` | `multicolorcaptcha` | **captchakit** |
|
|
72
|
+
| ------------------------ | ----------------- | ---------- | ------------------- | --------------------------------- |
|
|
73
|
+
| Async API | ❌ | ❌ | ❌ | ✅ |
|
|
74
|
+
| `py.typed` + mypy strict | ⚠️ | ❌ | ❌ | ✅ |
|
|
75
|
+
| TTL & attempt tracking | ❌ | ❌ | ❌ | ✅ built-in |
|
|
76
|
+
| Pluggable storage | ❌ | ❌ | ❌ | ✅ `Protocol` |
|
|
77
|
+
| Framework adapters | ❌ | ❌ | ❌ | ✅ FastAPI · aiogram · discord.py |
|
|
78
|
+
| Runtime deps (core) | +Pillow | +Pillow | +Pillow | +Pillow |
|
|
79
|
+
|
|
80
|
+
## Install
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
pip install captchakit # core
|
|
84
|
+
pip install "captchakit[fastapi]" # + FastAPI adapter
|
|
85
|
+
pip install "captchakit[aiogram]" # + aiogram adapter (coming in 0.2)
|
|
86
|
+
pip install "captchakit[discord]" # + discord.py adapter (coming in 0.3)
|
|
87
|
+
pip install "captchakit[redis]" # + Redis storage backend (coming in 0.2)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
> Adapters other than FastAPI are declared in the roadmap but not shipped in
|
|
91
|
+
> 0.1 yet. The extras install today but the adapter modules land in later
|
|
92
|
+
> releases — see [ROADMAP.md](ROADMAP.md).
|
|
93
|
+
|
|
94
|
+
## 30-second example
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
import asyncio
|
|
98
|
+
from captchakit import (
|
|
99
|
+
CaptchaManager, ImageRenderer, MemoryStorage, TextChallengeFactory,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
async def main() -> None:
|
|
103
|
+
manager = CaptchaManager(
|
|
104
|
+
factory=TextChallengeFactory(length=5),
|
|
105
|
+
renderer=ImageRenderer(),
|
|
106
|
+
storage=MemoryStorage(),
|
|
107
|
+
ttl=120.0,
|
|
108
|
+
max_attempts=3,
|
|
109
|
+
)
|
|
110
|
+
challenge_id, png_bytes = await manager.issue()
|
|
111
|
+
# ... show png_bytes to the user, receive their answer ...
|
|
112
|
+
ok = await manager.verify(challenge_id, user_input="ABCDE")
|
|
113
|
+
print("verified" if ok else "wrong answer, more attempts remain")
|
|
114
|
+
|
|
115
|
+
asyncio.run(main())
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## FastAPI in 10 lines
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from fastapi import Depends, FastAPI
|
|
122
|
+
from captchakit import CaptchaManager, ImageRenderer, MathChallengeFactory, MemoryStorage
|
|
123
|
+
from captchakit.adapters.fastapi import captcha_router, verify_captcha
|
|
124
|
+
|
|
125
|
+
manager = CaptchaManager(MathChallengeFactory(), ImageRenderer(), MemoryStorage())
|
|
126
|
+
app = FastAPI()
|
|
127
|
+
app.include_router(captcha_router(manager, prefix="/captcha"))
|
|
128
|
+
|
|
129
|
+
@app.post("/register")
|
|
130
|
+
async def register(_: None = Depends(verify_captcha(manager))) -> dict[str, bool]:
|
|
131
|
+
return {"ok": True}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Run the bundled demo:
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
uv run python -m uvicorn examples.fastapi_login:app --reload
|
|
138
|
+
# open http://127.0.0.1:8000
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Design
|
|
142
|
+
|
|
143
|
+
```
|
|
144
|
+
┌─────────────────────────────────────────────────┐
|
|
145
|
+
│ Adapters (fastapi / aiogram / discord) │
|
|
146
|
+
├─────────────────────────────────────────────────┤
|
|
147
|
+
│ CaptchaManager (public facade) │
|
|
148
|
+
├──────────────┬──────────────┬───────────────────┤
|
|
149
|
+
│ Challenge │ Renderer │ Storage │
|
|
150
|
+
│ Text / Math │ Image (PIL) │ Memory / Redis │
|
|
151
|
+
└──────────────┴──────────────┴───────────────────┘
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
- **`Protocol`-based**, so you can drop in your own storage (Redis, Postgres,
|
|
155
|
+
Memcached), your own renderer (SVG, WebP, audio), or your own challenge
|
|
156
|
+
factory (wordlists, emoji grids, …).
|
|
157
|
+
- **Constant-time comparison** via `hmac.compare_digest`.
|
|
158
|
+
- **Crypto-safe randomness** via `secrets` for solution generation.
|
|
159
|
+
- **CPU-bound Pillow drawing** offloaded to a worker thread via
|
|
160
|
+
`asyncio.to_thread`, so the event loop never blocks.
|
|
161
|
+
|
|
162
|
+
## Security scope
|
|
163
|
+
|
|
164
|
+
**captchakit is a lightweight human-check**, not a bot-farm-grade security layer.
|
|
165
|
+
It is aimed at Telegram/Discord verification, simple FastAPI registration flows
|
|
166
|
+
and similar use cases where you just want to raise the cost for casual spam.
|
|
167
|
+
|
|
168
|
+
For high-value forms (login, payment) use **hCaptcha**, **Cloudflare Turnstile**
|
|
169
|
+
or **reCAPTCHA Enterprise** in addition. Combine captchakit with proper rate
|
|
170
|
+
limiting at the edge of your application.
|
|
171
|
+
|
|
172
|
+
## Roadmap
|
|
173
|
+
|
|
174
|
+
See [ROADMAP.md](ROADMAP.md) for the full development plan.
|
|
175
|
+
|
|
176
|
+
| Version | Highlights |
|
|
177
|
+
|---|---|
|
|
178
|
+
| 0.1 (MVP) | Core + Text/Math challenges + Image renderer + Memory storage + FastAPI |
|
|
179
|
+
| 0.2 | aiogram + Redis storage + EmojiGridChallenge + docs site |
|
|
180
|
+
| 0.3 | discord.py adapter + AudioChallenge (optional) + WordChallenge |
|
|
181
|
+
| 0.4 | i18n + theming + metrics hooks |
|
|
182
|
+
| 1.0 | Stable API, semver commitment |
|
|
183
|
+
|
|
184
|
+
## Contributing
|
|
185
|
+
|
|
186
|
+
Contributions welcome. Local development:
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
git clone https://github.com/akerem16/captchakit
|
|
190
|
+
cd captchakit
|
|
191
|
+
uv sync --all-extras
|
|
192
|
+
uv run ruff check .
|
|
193
|
+
uv run mypy
|
|
194
|
+
uv run pytest
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## License
|
|
198
|
+
|
|
199
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
captchakit/__init__.py,sha256=MwY5Dbcl-m-rK3z8igQ0fenu9UUH-fStW9_LC4kwLEI,1050
|
|
2
|
+
captchakit/_clock.py,sha256=Fm4PBJvaD4IyOQFF0nhZ-LTo7Q0e3ebsuc5utH6eUV4,484
|
|
3
|
+
captchakit/errors.py,sha256=tNWLIOoYVmLaDBxWnjQwbtHQyhKqrc8TRxDtcmOt87Q,1168
|
|
4
|
+
captchakit/manager.py,sha256=lHNTd58zW8emaAxmxnJD0p1cMJpL8lAgsz6waQcSujI,3288
|
|
5
|
+
captchakit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
captchakit/adapters/__init__.py,sha256=j3AJ-T6zxvmXs00_HWrOGbI1jYmWALlc6Aaw0E43Aks,46
|
|
7
|
+
captchakit/adapters/fastapi.py,sha256=_JnhY0RHnfKXpM7-Po0ZJ5Y42-G2LsAFOAxhhCEYpxE,4699
|
|
8
|
+
captchakit/challenges/__init__.py,sha256=9pQscoYkxYX3uLdoQL6hvholFX5tYV7yxK9alakgSZQ,409
|
|
9
|
+
captchakit/challenges/base.py,sha256=GVAIrRJWAC8jM8VetVb6JD-FOksOOTsIxGpIM2bZKU0,1447
|
|
10
|
+
captchakit/challenges/math.py,sha256=xVHgSaPp6xRzERH5ND-sRRDgwh0V9baCjGrhRlsMRpQ,1574
|
|
11
|
+
captchakit/challenges/text.py,sha256=wXZRApb83Xo-sSH66G03IDAXtaPzWtLrX8LBsVc7ppk,1046
|
|
12
|
+
captchakit/renderers/__init__.py,sha256=QjOgfgA6dC_gK3anJI-bQE5exhYQVjuhuVtCwgpcnOA,224
|
|
13
|
+
captchakit/renderers/base.py,sha256=G5oorhx_pIpz1qeAyg6DQG1N-GK9gZQR0BP92Mf9ms0,402
|
|
14
|
+
captchakit/renderers/image.py,sha256=4-HrJxLkcGcJw_BLInCP_GdhEKTzpopXDYvw0i7-AVk,3068
|
|
15
|
+
captchakit/storage/__init__.py,sha256=3K30GSIaxoG7ma0yXnOvSDNSuVJVVkM-QZttYo-YJVw,207
|
|
16
|
+
captchakit/storage/base.py,sha256=IWxAi9LtclLEB8lWbN7hiMAKI6Ft-Q4q_3CFKdvtLBQ,880
|
|
17
|
+
captchakit/storage/memory.py,sha256=Au4JHksp8o0iwSRW29lb-noX1s5qQjw2l4N5qzXvAwQ,2354
|
|
18
|
+
captchakit-0.1.0.dist-info/METADATA,sha256=YgDUFEsA6uzWdSR2xLqDoXUneg7K5SXNKhTNxE7QecY,8522
|
|
19
|
+
captchakit-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
20
|
+
captchakit-0.1.0.dist-info/licenses/LICENSE,sha256=CnUfMc6IsjaY19ciGu6TelkHn6U_cvE48X1J-S51Udk,1065
|
|
21
|
+
captchakit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 akerem16
|
|
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.
|