capjs-server 0.1.0__tar.gz

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,29 @@
1
+ name: CI
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ubuntu-latest
6
+ strategy:
7
+ matrix:
8
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - uses: astral-sh/setup-uv@v5
12
+ - run: uv run nox -s "tests-${{ matrix.python-version }}"
13
+ lint:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: astral-sh/setup-uv@v5
18
+ - run: uv run nox -s lint
19
+ publish:
20
+ needs: [test, lint]
21
+ if: startsWith(github.ref, 'refs/tags/v')
22
+ runs-on: ubuntu-latest
23
+ permissions:
24
+ id-token: write
25
+ steps:
26
+ - uses: actions/checkout@v4
27
+ - uses: astral-sh/setup-uv@v5
28
+ - run: uv build
29
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .nox/
7
+ .venv/
8
+ *.xml
9
+ .coverage
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 VSHN AG
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: capjs-server
3
+ Version: 0.1.0
4
+ Summary: Python server-side implementation of the Cap.js proof-of-work CAPTCHA protocol
5
+ Project-URL: Homepage, https://github.com/vshn/capjs-server
6
+ Project-URL: Documentation, https://github.com/vshn/capjs-server#readme
7
+ Project-URL: Issues, https://github.com/vshn/capjs-server/issues
8
+ Project-URL: Source, https://github.com/vshn/capjs-server
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: bot-protection,capjs,captcha,proof-of-work,spam
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Flask
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Internet :: WWW/HTTP
19
+ Classifier: Topic :: Security
20
+ Requires-Python: >=3.10
21
+ Provides-Extra: django
22
+ Requires-Dist: django>=4.2; extra == 'django'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # capjs-server
26
+
27
+ Python server-side implementation of the [Cap.js](https://capjs.js.org/) proof-of-work CAPTCHA protocol. Framework-agnostic core with optional Django integration.
28
+
29
+ Cap.js is a privacy-friendly, cookie-free CAPTCHA that uses proof-of-work challenges instead of image recognition. This package provides the server side — challenge creation, solution verification, and token validation.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install capjs-server
35
+
36
+ # With Django integration
37
+ pip install capjs-server[django]
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ from capjs_server import CapServer
44
+
45
+ cap = CapServer(secret_key="your-secret-key")
46
+
47
+ # Create challenge → return as JSON to the Cap.js widget
48
+ challenge = cap.create_challenge()
49
+
50
+ # Verify solutions from the widget → return as JSON
51
+ result = cap.redeem(challenge["token"], solutions)
52
+
53
+ # Validate verification token in your form handler
54
+ if cap.validate(request.POST["cap-token"]):
55
+ process_form()
56
+ ```
57
+
58
+ ## Django Integration
59
+
60
+ ```python
61
+ # settings.py (all optional — sensible defaults)
62
+ CAP_SECRET_KEY = SECRET_KEY # defaults to Django's SECRET_KEY
63
+ CAP_CHALLENGE_COUNT = 50 # sub-challenges per solve
64
+ CAP_CHALLENGE_DIFFICULTY = 4 # target prefix length (hex chars)
65
+
66
+ # urls.py
67
+ from capjs_server.django.views import CapChallengeView, CapRedeemView
68
+
69
+ urlpatterns = [
70
+ path("cap/challenge", CapChallengeView.as_view()),
71
+ path("cap/redeem", CapRedeemView.as_view()),
72
+ ]
73
+
74
+ # views.py
75
+ from capjs_server.django import validate_cap_token
76
+
77
+ def contact(request):
78
+ if not validate_cap_token(request):
79
+ return HttpResponseForbidden()
80
+ # process form...
81
+ ```
82
+
83
+ ## Configuration
84
+
85
+ | Parameter | Default | Description |
86
+ |-----------|---------|-------------|
87
+ | `secret_key` | *(required)* | HMAC signing key. Keep stable across deploys. |
88
+ | `challenge_count` | `50` | Sub-challenges per solve |
89
+ | `challenge_size` | `32` | Salt length in hex chars |
90
+ | `challenge_difficulty` | `4` | Target prefix length in hex chars |
91
+ | `challenge_expiry_ms` | `600000` | Challenge token lifetime (10 min) |
92
+ | `token_expiry_ms` | `300000` | Verification token lifetime (5 min) |
93
+
94
+ ## Testing
95
+
96
+ A brute-force solver is included for writing integration tests without a browser:
97
+
98
+ ```python
99
+ from capjs_server import CapServer
100
+ from capjs_server.testing import solve
101
+
102
+ cap = CapServer(secret_key="test", challenge_count=2, challenge_difficulty=1)
103
+ challenge = cap.create_challenge()
104
+ solutions = solve(challenge["token"], challenge["challenge"])
105
+ result = cap.redeem(challenge["token"], solutions)
106
+ assert result["success"]
107
+ ```
108
+
109
+ ## How It Works
110
+
111
+ All state is encoded in HMAC-signed tokens — no server-side storage. This makes it safe for multi-instance deployments (Kubernetes, Cloud Run, serverless).
112
+
113
+ 1. **Challenge**: Server generates a random nonce and signs it with difficulty parameters into a token
114
+ 2. **Solve**: The Cap.js widget finds nonces whose SHA-256 hash starts with a PRNG-derived prefix
115
+ 3. **Redeem**: Server verifies the HMAC, checks solutions, and issues a signed verification token
116
+ 4. **Validate**: Server verifies the verification token's HMAC and expiry
117
+
118
+ ## License
119
+
120
+ Apache-2.0 — same as Cap.js.
@@ -0,0 +1,96 @@
1
+ # capjs-server
2
+
3
+ Python server-side implementation of the [Cap.js](https://capjs.js.org/) proof-of-work CAPTCHA protocol. Framework-agnostic core with optional Django integration.
4
+
5
+ Cap.js is a privacy-friendly, cookie-free CAPTCHA that uses proof-of-work challenges instead of image recognition. This package provides the server side — challenge creation, solution verification, and token validation.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install capjs-server
11
+
12
+ # With Django integration
13
+ pip install capjs-server[django]
14
+ ```
15
+
16
+ ## Quick Start
17
+
18
+ ```python
19
+ from capjs_server import CapServer
20
+
21
+ cap = CapServer(secret_key="your-secret-key")
22
+
23
+ # Create challenge → return as JSON to the Cap.js widget
24
+ challenge = cap.create_challenge()
25
+
26
+ # Verify solutions from the widget → return as JSON
27
+ result = cap.redeem(challenge["token"], solutions)
28
+
29
+ # Validate verification token in your form handler
30
+ if cap.validate(request.POST["cap-token"]):
31
+ process_form()
32
+ ```
33
+
34
+ ## Django Integration
35
+
36
+ ```python
37
+ # settings.py (all optional — sensible defaults)
38
+ CAP_SECRET_KEY = SECRET_KEY # defaults to Django's SECRET_KEY
39
+ CAP_CHALLENGE_COUNT = 50 # sub-challenges per solve
40
+ CAP_CHALLENGE_DIFFICULTY = 4 # target prefix length (hex chars)
41
+
42
+ # urls.py
43
+ from capjs_server.django.views import CapChallengeView, CapRedeemView
44
+
45
+ urlpatterns = [
46
+ path("cap/challenge", CapChallengeView.as_view()),
47
+ path("cap/redeem", CapRedeemView.as_view()),
48
+ ]
49
+
50
+ # views.py
51
+ from capjs_server.django import validate_cap_token
52
+
53
+ def contact(request):
54
+ if not validate_cap_token(request):
55
+ return HttpResponseForbidden()
56
+ # process form...
57
+ ```
58
+
59
+ ## Configuration
60
+
61
+ | Parameter | Default | Description |
62
+ |-----------|---------|-------------|
63
+ | `secret_key` | *(required)* | HMAC signing key. Keep stable across deploys. |
64
+ | `challenge_count` | `50` | Sub-challenges per solve |
65
+ | `challenge_size` | `32` | Salt length in hex chars |
66
+ | `challenge_difficulty` | `4` | Target prefix length in hex chars |
67
+ | `challenge_expiry_ms` | `600000` | Challenge token lifetime (10 min) |
68
+ | `token_expiry_ms` | `300000` | Verification token lifetime (5 min) |
69
+
70
+ ## Testing
71
+
72
+ A brute-force solver is included for writing integration tests without a browser:
73
+
74
+ ```python
75
+ from capjs_server import CapServer
76
+ from capjs_server.testing import solve
77
+
78
+ cap = CapServer(secret_key="test", challenge_count=2, challenge_difficulty=1)
79
+ challenge = cap.create_challenge()
80
+ solutions = solve(challenge["token"], challenge["challenge"])
81
+ result = cap.redeem(challenge["token"], solutions)
82
+ assert result["success"]
83
+ ```
84
+
85
+ ## How It Works
86
+
87
+ All state is encoded in HMAC-signed tokens — no server-side storage. This makes it safe for multi-instance deployments (Kubernetes, Cloud Run, serverless).
88
+
89
+ 1. **Challenge**: Server generates a random nonce and signs it with difficulty parameters into a token
90
+ 2. **Solve**: The Cap.js widget finds nonces whose SHA-256 hash starts with a PRNG-derived prefix
91
+ 3. **Redeem**: Server verifies the HMAC, checks solutions, and issues a signed verification token
92
+ 4. **Validate**: Server verifies the verification token's HMAC and expiry
93
+
94
+ ## License
95
+
96
+ Apache-2.0 — same as Cap.js.
@@ -0,0 +1,16 @@
1
+ import nox
2
+
3
+ nox.options.default_venv_backend = "uv"
4
+
5
+
6
+ @nox.session(python=["3.10", "3.11", "3.12", "3.13", "3.14"])
7
+ def tests(session: nox.Session) -> None:
8
+ session.install("-e", ".[django]", "--group", "dev")
9
+ session.run("pytest", *session.posargs)
10
+
11
+
12
+ @nox.session
13
+ def lint(session: nox.Session) -> None:
14
+ session.install("ruff")
15
+ session.run("ruff", "check", "src/", "tests/")
16
+ session.run("ruff", "format", "--check", "src/", "tests/")
@@ -0,0 +1,55 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "capjs-server"
7
+ version = "0.1.0"
8
+ description = "Python server-side implementation of the Cap.js proof-of-work CAPTCHA protocol"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ keywords = ["captcha", "proof-of-work", "capjs", "spam", "bot-protection"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Framework :: Django",
16
+ "Framework :: Flask",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Internet :: WWW/HTTP",
21
+ "Topic :: Security",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ django = ["django>=4.2"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/vshn/capjs-server"
29
+ Documentation = "https://github.com/vshn/capjs-server#readme"
30
+ Issues = "https://github.com/vshn/capjs-server/issues"
31
+ Source = "https://github.com/vshn/capjs-server"
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "nox[uv]>=2024.4",
36
+ "pytest>=8.0",
37
+ "pytest-cov>=5.0",
38
+ "ruff>=0.9",
39
+ "django>=5.1",
40
+ "pytest-django>=4.8",
41
+ ]
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/capjs_server"]
45
+
46
+ [tool.pytest.ini_options]
47
+ addopts = "--cov=capjs_server --cov-report=term-missing"
48
+ pythonpath = ["src", "."]
49
+ DJANGO_SETTINGS_MODULE = "tests.django_settings"
50
+
51
+ [tool.ruff]
52
+ target-version = "py310"
53
+
54
+ [tool.ruff.lint]
55
+ select = ["E", "F", "I", "W"]
@@ -0,0 +1,107 @@
1
+ """Cap.js proof-of-work CAPTCHA server for Python.
2
+
3
+ Usage::
4
+
5
+ from capjs_server import CapServer
6
+
7
+ cap = CapServer(secret_key="your-secret")
8
+ challenge = cap.create_challenge()
9
+ result = cap.redeem(token, solutions)
10
+ if cap.validate(verification_token):
11
+ process_form()
12
+ """
13
+
14
+ import hashlib
15
+ import logging
16
+ import secrets
17
+ import time
18
+
19
+ from .prng import prng
20
+ from .tokens import (
21
+ make_challenge_token,
22
+ make_verification_token,
23
+ verify_challenge_token,
24
+ verify_verification_token,
25
+ )
26
+
27
+ __all__ = ["CapServer"]
28
+ __version__ = "0.1.0"
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class CapServer:
34
+ """Stateless Cap.js proof-of-work CAPTCHA server.
35
+
36
+ All state is encoded in HMAC-signed tokens, so this works correctly
37
+ with multi-instance deployments (Cloud Run, Kubernetes, etc.).
38
+
39
+ Args:
40
+ secret_key: Secret used for HMAC token signatures. Keep this stable
41
+ across deployments — changing it invalidates all outstanding tokens.
42
+ challenge_count: Number of sub-challenges per solve (default 50).
43
+ challenge_size: Salt length in hex chars (default 32).
44
+ challenge_difficulty: Target prefix length in hex chars (default 4).
45
+ challenge_expiry_ms: Challenge expiry in milliseconds (default 600000 = 10 min).
46
+ token_expiry_ms: Verification token expiry in milliseconds
47
+ (default 300000 = 5 min).
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ secret_key: str,
53
+ *,
54
+ challenge_count: int = 50,
55
+ challenge_size: int = 32,
56
+ challenge_difficulty: int = 4,
57
+ challenge_expiry_ms: int = 600_000,
58
+ token_expiry_ms: int = 300_000,
59
+ ):
60
+ self._secret = secret_key.encode()
61
+ self._count = challenge_count
62
+ self._size = challenge_size
63
+ self._difficulty = challenge_difficulty
64
+ self._challenge_expiry_ms = challenge_expiry_ms
65
+ self._token_expiry_ms = token_expiry_ms
66
+
67
+ def create_challenge(self) -> dict:
68
+ """Generate a new proof-of-work challenge.
69
+
70
+ Returns a dict with keys ``challenge``, ``token``, ``expires``
71
+ suitable for JSON serialization to the Cap.js widget.
72
+ """
73
+ nonce = secrets.token_hex(25)
74
+ expires = time.time() * 1000 + self._challenge_expiry_ms
75
+ config = {"c": self._count, "s": self._size, "d": self._difficulty}
76
+ token = make_challenge_token(self._secret, nonce, expires, config)
77
+ return {"challenge": config, "token": token, "expires": expires}
78
+
79
+ def redeem(self, token: str, solutions: list[int]) -> dict:
80
+ """Verify proof-of-work solutions and issue a verification token.
81
+
82
+ Returns a dict with ``success`` (bool), and on success: ``token``, ``expires``.
83
+ """
84
+ parsed = verify_challenge_token(self._secret, token)
85
+ if parsed is None:
86
+ return {"success": False}
87
+
88
+ config = parsed["config"]
89
+ count, size, difficulty = config["c"], config["s"], config["d"]
90
+
91
+ if len(solutions) != count:
92
+ return {"success": False}
93
+
94
+ for i in range(1, count + 1):
95
+ salt = prng(token + str(i), size)
96
+ target = prng(token + str(i) + "d", difficulty)
97
+ h = hashlib.sha256((salt + str(solutions[i - 1])).encode()).hexdigest()
98
+ if not h.startswith(target):
99
+ return {"success": False}
100
+
101
+ expires = time.time() * 1000 + self._token_expiry_ms
102
+ vertoken = make_verification_token(self._secret, expires)
103
+ return {"success": True, "token": vertoken, "expires": expires}
104
+
105
+ def validate(self, token) -> bool:
106
+ """Validate a verification token. Returns True if valid."""
107
+ return verify_verification_token(self._secret, token)
@@ -0,0 +1,53 @@
1
+ """Django integration for capjs-server.
2
+
3
+ Requires ``pip install capjs-server[django]``.
4
+
5
+ Quick start::
6
+
7
+ # settings.py (all optional — sensible defaults)
8
+ CAP_SECRET_KEY = SECRET_KEY # defaults to SECRET_KEY
9
+ CAP_CHALLENGE_COUNT = 50
10
+ CAP_CHALLENGE_DIFFICULTY = 4
11
+
12
+ # urls.py
13
+ from capjs_server.django.views import CapChallengeView, CapRedeemView
14
+ urlpatterns = [
15
+ path("cap/challenge", CapChallengeView.as_view()),
16
+ path("cap/redeem", CapRedeemView.as_view()),
17
+ ]
18
+
19
+ # views.py
20
+ from capjs_server.django import validate_cap_token
21
+ if not validate_cap_token(request):
22
+ return HttpResponseForbidden()
23
+ """
24
+
25
+ from functools import lru_cache
26
+
27
+ from django.conf import settings
28
+
29
+ from capjs_server import CapServer
30
+
31
+ __all__ = ["get_cap_server", "validate_cap_token"]
32
+
33
+
34
+ @lru_cache(maxsize=1)
35
+ def get_cap_server() -> CapServer:
36
+ """Return a CapServer configured from Django settings."""
37
+ return CapServer(
38
+ secret_key=getattr(settings, "CAP_SECRET_KEY", settings.SECRET_KEY),
39
+ challenge_count=getattr(settings, "CAP_CHALLENGE_COUNT", 50),
40
+ challenge_size=getattr(settings, "CAP_CHALLENGE_SIZE", 32),
41
+ challenge_difficulty=getattr(settings, "CAP_CHALLENGE_DIFFICULTY", 4),
42
+ challenge_expiry_ms=getattr(settings, "CAP_CHALLENGE_EXPIRY", 600_000),
43
+ token_expiry_ms=getattr(settings, "CAP_TOKEN_EXPIRY", 300_000),
44
+ )
45
+
46
+
47
+ def validate_cap_token(request, field_name: str = "cap-token") -> bool:
48
+ """Validate the Cap.js verification token from a Django request.
49
+
50
+ Reads the token from ``request.POST[field_name]`` and validates it.
51
+ """
52
+ token = request.POST.get(field_name, "")
53
+ return get_cap_server().validate(token)