cripcha 1.0.3__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.
cripcha/__init__.py ADDED
@@ -0,0 +1,100 @@
1
+ """Cripcha · server side check of the tokens of the widget (POST <api>/siteverify).
2
+
3
+ Fails closed: only {"success": true} accepts the form; an unreachable API or an unexpected answer refuses it,
4
+ without raising. No dependency (urllib).
5
+
6
+ from cripcha import verify, TOKEN_FIELD
7
+ result = verify(request.POST.get(TOKEN_FIELD), secret=settings.CRIPCHA_SECRET)
8
+ if not result.success:
9
+ ... # refuse the form
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from dataclasses import dataclass, field
19
+ from typing import Callable, Optional
20
+
21
+ __all__ = ["verify", "Result", "TOKEN_FIELD", "DEFAULT_API_URL", "DEFAULT_WIDGET_URL", "widget_html"]
22
+
23
+ TOKEN_FIELD = "cripcha-response"
24
+ DEFAULT_API_URL = "https://cripcha.crispy-medias.fr/api/v1"
25
+ DEFAULT_WIDGET_URL = "https://cripcha-widget.s3.eu-west-par.io.cloud.ovh.net/v1/widget.js"
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Result:
30
+ success: bool
31
+ error_codes: list = field(default_factory=list)
32
+ challenge_ts: Optional[str] = None
33
+ site_key: Optional[str] = None
34
+
35
+ def __bool__(self) -> bool:
36
+ return self.success
37
+
38
+
39
+ def _failure(code: str) -> Result:
40
+ return Result(False, [code])
41
+
42
+
43
+ # (url, form fields, timeout) -> (status, body); raises OSError when the API cannot be reached
44
+ Transport = Callable[[str, dict, float], "tuple[int, str]"]
45
+
46
+
47
+ def _urllib_transport(url: str, fields: dict, timeout: float) -> "tuple[int, str]":
48
+ request = urllib.request.Request(
49
+ url,
50
+ data=urllib.parse.urlencode(fields).encode(),
51
+ headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json", "User-Agent": "cripcha-python"},
52
+ method="POST",
53
+ )
54
+ try:
55
+ with urllib.request.urlopen(request, timeout=timeout) as response:
56
+ return response.status, response.read().decode("utf-8", "replace")
57
+ except urllib.error.HTTPError as error:
58
+ return error.code, error.read().decode("utf-8", "replace")
59
+
60
+
61
+ def verify(token: object, secret: str, api_url: str = DEFAULT_API_URL, timeout: float = 5.0, transport: Optional[Transport] = None) -> Result:
62
+ # no secret configured: every form refused, without calling the API
63
+ if not isinstance(secret, str) or secret.strip() == "":
64
+ return _failure("missing-input-secret")
65
+ value = token.strip() if isinstance(token, str) else ""
66
+ if value == "":
67
+ return _failure("missing-input-response")
68
+ try:
69
+ status, body = (transport or _urllib_transport)(api_url.rstrip("/") + "/siteverify", {"secret": secret, "response": value}, timeout)
70
+ except (OSError, ValueError):
71
+ return _failure("network-error")
72
+ if status != 200:
73
+ return _failure("bad-response")
74
+ try:
75
+ data = json.loads(body)
76
+ except ValueError:
77
+ return _failure("bad-response")
78
+ if not isinstance(data, dict):
79
+ return _failure("bad-response")
80
+ errors = [code for code in data.get("error-codes", []) if isinstance(code, str)] if isinstance(data.get("error-codes"), list) else []
81
+ if data.get("success") is not True:
82
+ return Result(False, errors)
83
+ challenge_ts = data.get("challenge_ts")
84
+ site_key = data.get("sitekey")
85
+ return Result(True, [], challenge_ts if isinstance(challenge_ts, str) else None, site_key if isinstance(site_key, str) else None)
86
+
87
+
88
+ def widget_html(site_key: str, widget_url: str = DEFAULT_WIDGET_URL, lang: Optional[str] = None, form: Optional[str] = None, with_script: bool = True) -> str:
89
+ """the widget for a template (Jinja2: {{ cripcha_widget|safe }})"""
90
+ from html import escape
91
+
92
+ attributes = f' data-sitekey="{escape(site_key)}"'
93
+ if lang:
94
+ attributes += f' data-lang="{escape(lang)}"'
95
+ if form:
96
+ attributes += f' data-form="{escape(form)}"'
97
+ html = f'<div class="cripcha"{attributes}></div>'
98
+ if with_script:
99
+ html += f'<script src="{escape(widget_url)}" async defer></script>'
100
+ return html
cripcha/django.py ADDED
@@ -0,0 +1,63 @@
1
+ """Django: a form field showing the widget and checking the token.
2
+
3
+ # settings.py
4
+ CRIPCHA_SITE_KEY = "ck_…"
5
+ CRIPCHA_SECRET = env("CRIPCHA_SECRET")
6
+
7
+ # forms.py
8
+ from cripcha.django import CripchaField
9
+ class ContactForm(forms.Form):
10
+ message = forms.CharField(widget=forms.Textarea)
11
+ cripcha = CripchaField()
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from django import forms
17
+ from django.conf import settings
18
+ from django.core.exceptions import ValidationError
19
+ from django.utils.safestring import mark_safe
20
+ from django.utils.translation import get_language, gettext_lazy as _
21
+
22
+ from . import DEFAULT_API_URL, DEFAULT_WIDGET_URL, TOKEN_FIELD, verify, widget_html
23
+
24
+
25
+ class CripchaWidget(forms.Widget):
26
+ """the widget of Cripcha; the token comes from the field cripcha-response that the widget adds to the form"""
27
+
28
+ def render(self, name, value, attrs=None, renderer=None):
29
+ lang = (get_language() or "")[:2] or None
30
+ return mark_safe(widget_html(getattr(settings, "CRIPCHA_SITE_KEY", ""), getattr(settings, "CRIPCHA_WIDGET_URL", DEFAULT_WIDGET_URL), lang=lang))
31
+
32
+ def value_from_datadict(self, data, files, name):
33
+ return data.get(TOKEN_FIELD, "")
34
+
35
+ def value_omitted_from_data(self, data, files, name):
36
+ return TOKEN_FIELD not in data
37
+
38
+
39
+ class CripchaField(forms.Field):
40
+ widget = CripchaWidget
41
+ default_error_messages = {"invalid": _("The bot check did not complete: wait a second, then send the form again.")}
42
+
43
+ def __init__(self, **kwargs):
44
+ kwargs.setdefault("label", "")
45
+ kwargs.setdefault("required", True)
46
+ super().__init__(**kwargs)
47
+
48
+ def validate(self, value):
49
+ if not getattr(settings, "CRIPCHA_ENABLED", True):
50
+ return
51
+ result = verify(
52
+ value,
53
+ secret=getattr(settings, "CRIPCHA_SECRET", ""),
54
+ api_url=getattr(settings, "CRIPCHA_API_URL", DEFAULT_API_URL),
55
+ timeout=getattr(settings, "CRIPCHA_TIMEOUT", 5.0),
56
+ )
57
+ if not result.success:
58
+ raise ValidationError(self.error_messages["invalid"], code="invalid")
59
+
60
+ def clean(self, value):
61
+ # the token is only checked, never kept in cleaned_data
62
+ self.validate(value)
63
+ return None
cripcha/fastapi.py ADDED
@@ -0,0 +1,35 @@
1
+ """FastAPI: a dependency refusing the request (403) when the token of the form is not valid.
2
+
3
+ from cripcha.fastapi import CripchaGuard
4
+ guard = CripchaGuard(secret=os.environ["CRIPCHA_SECRET"])
5
+
6
+ @app.post("/contact")
7
+ async def contact(message: str = Form(...), _: Result = Depends(guard)):
8
+ ...
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Optional
14
+
15
+ from fastapi import Form, HTTPException
16
+ from starlette.concurrency import run_in_threadpool
17
+
18
+ from . import DEFAULT_API_URL, TOKEN_FIELD, Result, verify
19
+
20
+
21
+ class CripchaGuard:
22
+ def __init__(self, secret: str, api_url: str = DEFAULT_API_URL, timeout: float = 5.0, enabled: bool = True):
23
+ self.secret = secret
24
+ self.api_url = api_url
25
+ self.timeout = timeout
26
+ self.enabled = enabled
27
+
28
+ async def __call__(self, token: Optional[str] = Form(default=None, alias=TOKEN_FIELD)) -> Result:
29
+ if not self.enabled:
30
+ return Result(True)
31
+ # urllib blocks: in the thread pool, not in the event loop
32
+ result = await run_in_threadpool(verify, token, self.secret, self.api_url, self.timeout)
33
+ if not result.success:
34
+ raise HTTPException(status_code=403, detail={"error": "cripcha", "error_codes": result.error_codes})
35
+ return result
cripcha/flask.py ADDED
@@ -0,0 +1,41 @@
1
+ """Flask: the token of the submitted form, checked; and the widget in the Jinja2 templates.
2
+
3
+ from cripcha.flask import Cripcha
4
+ cripcha = Cripcha(app) # CRIPCHA_SITE_KEY, CRIPCHA_SECRET in app.config
5
+
6
+ @app.post("/contact")
7
+ def contact():
8
+ if not cripcha.verify_request():
9
+ abort(403)
10
+
11
+ {{ cripcha_widget() }} in the form
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from flask import Flask, request
17
+ from markupsafe import Markup
18
+
19
+ from . import DEFAULT_API_URL, DEFAULT_WIDGET_URL, TOKEN_FIELD, Result, verify, widget_html
20
+
21
+
22
+ class Cripcha:
23
+ def __init__(self, app: Flask | None = None):
24
+ if app is not None:
25
+ self.init_app(app)
26
+
27
+ def init_app(self, app: Flask) -> None:
28
+ app.config.setdefault("CRIPCHA_SITE_KEY", "")
29
+ app.config.setdefault("CRIPCHA_SECRET", "")
30
+ app.config.setdefault("CRIPCHA_API_URL", DEFAULT_API_URL)
31
+ app.config.setdefault("CRIPCHA_WIDGET_URL", DEFAULT_WIDGET_URL)
32
+ app.config.setdefault("CRIPCHA_ENABLED", True)
33
+ app.extensions["cripcha"] = self
34
+ app.jinja_env.globals["cripcha_widget"] = lambda **options: Markup(widget_html(app.config["CRIPCHA_SITE_KEY"], app.config["CRIPCHA_WIDGET_URL"], **options))
35
+ self.app = app
36
+
37
+ def verify_request(self) -> Result:
38
+ config = self.app.config
39
+ if not config["CRIPCHA_ENABLED"]:
40
+ return Result(True)
41
+ return verify(request.form.get(TOKEN_FIELD), secret=config["CRIPCHA_SECRET"], api_url=config["CRIPCHA_API_URL"])
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: de\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Die Bot-Prüfung wurde nicht abgeschlossen: Warten Sie eine Sekunde und senden Sie das Formular erneut."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: es\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "La verificación antirrobots no se ha completado: espere un segundo y vuelva a enviar el formulario."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: fr\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "La vérification anti-robot n'a pas abouti : patientez une seconde puis renvoyez le formulaire."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: it\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "La verifica antibot non è stata completata: attenda un secondo e invii di nuovo il modulo."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: nl\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "De botcontrole is niet voltooid: wacht een seconde en verstuur het formulier opnieuw."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: pt\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "A verificação anti-robô não foi concluída: aguarde um segundo e envie o formulário de novo."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: ro\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Verificarea anti-robot nu s-a încheiat: așteptați o secundă și trimiteți din nou formularul."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: ru\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Проверка на робота не завершена: подождите секунду и отправьте форму ещё раз."
Binary file
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: uk\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Перевірку на робота не завершено: зачекайте секунду й надішліть форму ще раз."
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: cripcha
3
+ Version: 1.0.3
4
+ Summary: Server side check of Cripcha tokens (Django, Flask, FastAPI): the privacy-first, cookie-free captcha hosted in the EU
5
+ Author-email: Crispy Medias <contact@crispy-medias.fr>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://cripcha.crispy-medias.fr
8
+ Project-URL: Documentation, https://cripcha.crispy-medias.fr
9
+ Project-URL: Source, https://github.com/cripcha/cripcha-python
10
+ Keywords: captcha,cripcha,anti-spam,gdpr,django,flask,fastapi
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Flask
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ Provides-Extra: django
21
+ Requires-Dist: django>=4.2; extra == "django"
22
+ Provides-Extra: flask
23
+ Requires-Dist: flask>=2.3; extra == "flask"
24
+ Provides-Extra: fastapi
25
+ Requires-Dist: fastapi>=0.100; extra == "fastapi"
26
+ Requires-Dist: python-multipart; extra == "fastapi"
27
+
28
+ # cripcha
29
+
30
+ Server side check of [Cripcha](https://cripcha.crispy-medias.fr) tokens for Python 3.9+: Django, Flask, FastAPI. No dependency.
31
+
32
+ ```bash
33
+ pip install cripcha # or: pip install "cripcha[django]", "cripcha[flask]", "cripcha[fastapi]"
34
+ ```
35
+
36
+ ```python
37
+ from cripcha import verify, TOKEN_FIELD
38
+ result = verify(form_data.get(TOKEN_FIELD), secret=os.environ["CRIPCHA_SECRET"])
39
+ ```
40
+
41
+ Django (`CRIPCHA_SITE_KEY`, `CRIPCHA_SECRET` in the settings; `"cripcha"` in `INSTALLED_APPS` for the translated
42
+ message):
43
+
44
+ ```python
45
+ from cripcha.django import CripchaField
46
+ class ContactForm(forms.Form):
47
+ message = forms.CharField(widget=forms.Textarea)
48
+ cripcha = CripchaField()
49
+ ```
50
+
51
+ Flask: `cripcha = Cripcha(app)`, `cripcha.verify_request()` in the view, `{{ cripcha_widget() }}` in the template.
52
+
53
+ FastAPI: `guard = CripchaGuard(secret=…)` then `Depends(guard)` on the route (403 when refused).
54
+
55
+ Fails closed, never raises for an API error. Test secrets: `cs_test_always_pass` / `cs_test_always_fail`.
@@ -0,0 +1,26 @@
1
+ cripcha/__init__.py,sha256=ienxY6Ko_DjZpehDaxiF2lcXgAAwSdjU7AgEUXJPQgQ,3968
2
+ cripcha/django.py,sha256=MTnonJMegi6phIAH15TEsJk9oZrpnQtQD-jnSFRdb8w,2259
3
+ cripcha/fastapi.py,sha256=68vxTnN_feyDpwGZm0BcY-6Qk_GDoFGIgHiwulBWQow,1290
4
+ cripcha/flask.py,sha256=UdKD8C-KV_X2jyo3S1w2fx-wA4IP2JmM2fJuf-E2tyQ,1535
5
+ cripcha/locale/de/LC_MESSAGES/django.mo,sha256=-EJlRMusXlJHkjyAg5KZB1y1t8Z-Ld9nfuCuN3BaFsY,312
6
+ cripcha/locale/de/LC_MESSAGES/django.po,sha256=Z1ySpxH37diTLnknj_UBwuGLRVRTxkXI6urqo4AXukk,275
7
+ cripcha/locale/es/LC_MESSAGES/django.mo,sha256=KN1orplnWPFkfizHwaBJpsAXnWR8v-zHyb44DRWaztU,309
8
+ cripcha/locale/es/LC_MESSAGES/django.po,sha256=knc_ZLxZxdun4l06cCOBaCbb1wpKxFvpVM8p5HqcwMU,272
9
+ cripcha/locale/fr/LC_MESSAGES/django.mo,sha256=deL6Re4dUuX11S_h1wTBE0nXE5ZITllFCrBHcmkohRQ,304
10
+ cripcha/locale/fr/LC_MESSAGES/django.po,sha256=YPoqLJIGxnNleymeYMmUV1I7GnlqsILaXA4xf5zRhlI,267
11
+ cripcha/locale/it/LC_MESSAGES/django.mo,sha256=OaiO_xW596xlqr_73yCiHUMi7JLuL_bGVdNctS5dX4E,300
12
+ cripcha/locale/it/LC_MESSAGES/django.po,sha256=y6nEFzggdlgnoAVq8c6H-aBJXdR470v0olb7ceS49LU,263
13
+ cripcha/locale/nl/LC_MESSAGES/django.mo,sha256=FdL9kJUZjOGGRuB0nhRqXD-zfGdf92JiY4oHapXw34k,294
14
+ cripcha/locale/nl/LC_MESSAGES/django.po,sha256=ykIA4F3SQFYlLWQjciIj7TWrLXMODUL7LzO6ESonKVA,257
15
+ cripcha/locale/pt/LC_MESSAGES/django.mo,sha256=E03vkHcBm93PAApdBX_ZRA0qU0JNZrvr1OMTjJfLd40,306
16
+ cripcha/locale/pt/LC_MESSAGES/django.po,sha256=hhQFLRtdGyuB8y1ZWoiT9wtK7_kM5pfPRc466PRYbhg,269
17
+ cripcha/locale/ro/LC_MESSAGES/django.mo,sha256=5isRC216b9iPQrrVbNmTc3u4EXU2hiFolbJRWI-lweA,307
18
+ cripcha/locale/ro/LC_MESSAGES/django.po,sha256=mOTfk9pjajjNKAvo_vS46KN5_Dl4BjQluYYCEm8YmTY,270
19
+ cripcha/locale/ru/LC_MESSAGES/django.mo,sha256=gOAIxx-oRE3g7F_UeHQQYe-zodp1S6l8hHbhTDq5EyY,350
20
+ cripcha/locale/ru/LC_MESSAGES/django.po,sha256=cZh6s__htY1Q8pUXFNgqNhz48UfgLQF7SFgtiWlmquc,313
21
+ cripcha/locale/uk/LC_MESSAGES/django.mo,sha256=tHksQdeLimTeTS59M1aooMWZv_zTDSDtGRki9HDwOxg,350
22
+ cripcha/locale/uk/LC_MESSAGES/django.po,sha256=wKLhNlvBVxFoQO-iyalKaLHhl7QNuYIPF_cbjX3B_e8,313
23
+ cripcha-1.0.3.dist-info/METADATA,sha256=6pjvRqS5Ewf6lIDhiQZI1FocEwXj3LcfQHTjmClyGYU,2092
24
+ cripcha-1.0.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
25
+ cripcha-1.0.3.dist-info/top_level.txt,sha256=6SWKofnPIi4p0_zErYPZVZxgp-UgMg9N6X6T2s4-GAQ,8
26
+ cripcha-1.0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ cripcha