capwx 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.
Files changed (57) hide show
  1. capwx/__init__.py +52 -0
  2. capwx/_crypto.py +127 -0
  3. capwx/_jsint.py +68 -0
  4. capwx/_types.py +35 -0
  5. capwx/_vendor/__init__.py +1 -0
  6. capwx/_vendor/hashwx/COMMIT +1 -0
  7. capwx/_vendor/hashwx/LICENSE +165 -0
  8. capwx/_vendor/hashwx/SHA256 +1 -0
  9. capwx/_vendor/hashwx/__init__.py +1 -0
  10. capwx/_vendor/hashwx/hashwx.wasm +0 -0
  11. capwx/challenge.py +545 -0
  12. capwx/config.py +116 -0
  13. capwx/contrib/__init__.py +1 -0
  14. capwx/contrib/django/__init__.py +7 -0
  15. capwx/contrib/django/_types.py +12 -0
  16. capwx/contrib/django/apps.py +22 -0
  17. capwx/contrib/django/conf.py +334 -0
  18. capwx/contrib/django/decorators.py +68 -0
  19. capwx/contrib/django/forms.py +68 -0
  20. capwx/contrib/django/management/__init__.py +0 -0
  21. capwx/contrib/django/management/commands/__init__.py +0 -0
  22. capwx/contrib/django/management/commands/capwx_check.py +200 -0
  23. capwx/contrib/django/static/capwx/VERSIONS.json +51 -0
  24. capwx/contrib/django/static/capwx/cap.min.js +1 -0
  25. capwx/contrib/django/static/capwx/cap_wasm_bg.wasm +0 -0
  26. capwx/contrib/django/static/capwx/hashwx-LICENSE.txt +165 -0
  27. capwx/contrib/django/static/capwx/hashwx.wasm +0 -0
  28. capwx/contrib/django/static/capwx/pako_inflate.min.js +2 -0
  29. capwx/contrib/django/templates/capwx/scripts.html +14 -0
  30. capwx/contrib/django/templates/capwx/widget.html +2 -0
  31. capwx/contrib/django/templatetags/__init__.py +0 -0
  32. capwx/contrib/django/templatetags/capwx.py +61 -0
  33. capwx/contrib/django/urls.py +17 -0
  34. capwx/contrib/django/views.py +212 -0
  35. capwx/contrib/ninja/__init__.py +11 -0
  36. capwx/contrib/ninja/router.py +252 -0
  37. capwx/errors.py +35 -0
  38. capwx/protocols/__init__.py +1 -0
  39. capwx/protocols/hashwx.py +227 -0
  40. capwx/protocols/instrumentation/__init__.py +59 -0
  41. capwx/protocols/instrumentation/detect.py +394 -0
  42. capwx/protocols/instrumentation/generator.py +632 -0
  43. capwx/protocols/instrumentation/obfuscate.py +110 -0
  44. capwx/protocols/instrumentation/verify.py +191 -0
  45. capwx/protocols/sha256_pow.py +71 -0
  46. capwx/py.typed +0 -0
  47. capwx/stores/__init__.py +61 -0
  48. capwx/stores/django_cache.py +62 -0
  49. capwx/stores/memory.py +79 -0
  50. capwx/stores/redis.py +124 -0
  51. capwx/tokens.py +337 -0
  52. capwx-0.1.0.dist-info/METADATA +403 -0
  53. capwx-0.1.0.dist-info/RECORD +57 -0
  54. capwx-0.1.0.dist-info/WHEEL +4 -0
  55. capwx-0.1.0.dist-info/licenses/LICENSE +202 -0
  56. capwx-0.1.0.dist-info/licenses/NOTICE +31 -0
  57. capwx-0.1.0.dist-info/licenses/src/capwx/_vendor/hashwx/LICENSE +165 -0
capwx/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """capwx: a Python server for the Cap CAPTCHA widget (HashWX, sha256-pow, instrumentation).
2
+
3
+ Importing ``capwx`` never imports wasmtime. The HashWX engine loads on first use, or eagerly via
4
+ :func:`hashwx_ready` at application startup.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from capwx.challenge import (
10
+ RedeemResult,
11
+ acreate_challenge,
12
+ aredeem,
13
+ create_challenge,
14
+ redeem,
15
+ set_event_callback,
16
+ )
17
+ from capwx.config import CapConfig, InstrumentationOptions
18
+ from capwx.errors import CapwxError, Reason
19
+ from capwx.stores.memory import MemoryStore
20
+ from capwx.tokens import avalidate_token, siteverify, validate_token
21
+
22
+ __version__ = "0.1.0"
23
+
24
+
25
+ def hashwx_ready(wasm_path: str | None = None) -> None:
26
+ """Force HashWX engine initialisation (imports wasmtime). Call at application startup.
27
+
28
+ Raises ``CapwxError`` if the vendored wasm is missing, tampered with, or cannot be instantiated.
29
+ """
30
+ from capwx.protocols.hashwx import hashwx_ready as _ready
31
+
32
+ _ready(wasm_path)
33
+
34
+
35
+ __all__ = [
36
+ "CapConfig",
37
+ "CapwxError",
38
+ "InstrumentationOptions",
39
+ "MemoryStore",
40
+ "Reason",
41
+ "RedeemResult",
42
+ "__version__",
43
+ "acreate_challenge",
44
+ "aredeem",
45
+ "avalidate_token",
46
+ "create_challenge",
47
+ "hashwx_ready",
48
+ "redeem",
49
+ "set_event_callback",
50
+ "siteverify",
51
+ "validate_token",
52
+ ]
capwx/_crypto.py ADDED
@@ -0,0 +1,127 @@
1
+ """capwx._crypto: b64url, JWT HS256, AES-GCM and sha256 helpers.
2
+
3
+ Byte-compatible with upstream ``core/src/crypto.js`` (capjs-core 0.1.5):
4
+ tokens minted here validate in Node and vice versa.
5
+
6
+ Client-supplied input (tokens, blobs) never raises: bad input yields ``None``.
7
+ Programmer errors (wrong secret type) still raise.
8
+ """
9
+
10
+ import base64
11
+ import hashlib
12
+ import hmac
13
+ import json
14
+ import os
15
+ import re
16
+ from typing import Any
17
+
18
+ from cryptography.exceptions import InvalidTag
19
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
20
+
21
+ from capwx._types import JsonDict, as_json_dict
22
+
23
+ _B64URL_RE = re.compile(r"[A-Za-z0-9_-]*")
24
+ _GCM_IV_LEN = 12
25
+ _GCM_TAG_LEN = 16
26
+
27
+
28
+ def random_hex(nbytes: int) -> str: # JS randomHex(n): n bytes -> 2n hex chars
29
+ return os.urandom(nbytes).hex()
30
+
31
+
32
+ def sha256_hex(s: str) -> str:
33
+ return hashlib.sha256(s.encode("utf-8")).hexdigest()
34
+
35
+
36
+ def b64url(data: bytes) -> str: # Node "base64url": NO padding
37
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
38
+
39
+
40
+ def b64url_decode(s: object) -> bytes:
41
+ """Strict base64url decode (no padding required). Raises ValueError on bad input."""
42
+ if not isinstance(s, str) or _B64URL_RE.fullmatch(s) is None or len(s) % 4 == 1:
43
+ raise ValueError("invalid base64url")
44
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
45
+
46
+
47
+ _JWT_HEADER_B64 = b64url(b'{"alg":"HS256","typ":"JWT"}') # exact bytes, do not re-serialise
48
+
49
+
50
+ def _key(secret: str | bytes) -> bytes:
51
+ return secret.encode("utf-8") if isinstance(secret, str) else secret
52
+
53
+
54
+ def jwt_sign(payload: JsonDict, secret: str | bytes) -> str:
55
+ body = b64url(json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8"))
56
+ sig_input = f"{_JWT_HEADER_B64}.{body}"
57
+ sig = hmac.new(_key(secret), sig_input.encode("ascii"), hashlib.sha256).digest()
58
+ return f"{sig_input}.{b64url(sig)}"
59
+
60
+
61
+ def jwt_verify(token: object, secret: str | bytes) -> JsonDict | None:
62
+ """Return the payload dict if the HS256 token is valid, else None. Never raises on bad input."""
63
+ key = _key(secret) # programmer error (wrong type) is allowed to raise
64
+ if not isinstance(token, str) or not token:
65
+ return None
66
+ first = token.find(".")
67
+ last = token.rfind(".")
68
+ # Exactly two dots, and the first one is not at index 0 (empty header is invalid).
69
+ if first < 1 or first == last or token.find(".", first + 1) != last:
70
+ return None
71
+ try:
72
+ expected = hmac.new(key, token[:last].encode("utf-8"), hashlib.sha256).digest()
73
+ actual = b64url_decode(token[last + 1 :])
74
+ except (ValueError, UnicodeError):
75
+ return None
76
+ if not hmac.compare_digest(expected, actual):
77
+ return None
78
+ try:
79
+ payload: Any = json.loads(b64url_decode(token[first + 1 : last]).decode("utf-8"))
80
+ except (ValueError, UnicodeError, RecursionError):
81
+ return None
82
+ return as_json_dict(payload)
83
+
84
+
85
+ def jwt_sig_hex(token: object) -> str | None: # hex of the decoded signature (replay key)
86
+ """Hex of the decoded signature segment, or None. Never raises on bad input."""
87
+ if not isinstance(token, str) or not token:
88
+ return None
89
+ last = token.rfind(".")
90
+ if last == -1:
91
+ return None
92
+ try:
93
+ return b64url_decode(token[last + 1 :]).hex()
94
+ except ValueError:
95
+ return None
96
+
97
+
98
+ def _derive_gcm_key(secret: str | bytes, info: str) -> bytes:
99
+ return hmac.new(_key(secret), info.encode("utf-8"), hashlib.sha256).digest() # 32 bytes
100
+
101
+
102
+ def encrypt_gcm(data: object, secret: str | bytes, info: str = "cap:enc-v1") -> str:
103
+ key = _derive_gcm_key(secret, info)
104
+ iv = os.urandom(_GCM_IV_LEN)
105
+ plaintext = json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
106
+ # AESGCM.encrypt returns ciphertext || tag; Node's blob layout is iv || tag || ciphertext.
107
+ ct_and_tag = AESGCM(key).encrypt(iv, plaintext, None)
108
+ ct, tag = ct_and_tag[:-_GCM_TAG_LEN], ct_and_tag[-_GCM_TAG_LEN:]
109
+ return b64url(iv + tag + ct)
110
+
111
+
112
+ def decrypt_gcm(blob: object, secret: str | bytes, info: str = "cap:enc-v1") -> Any | None:
113
+ """Decrypt a blob from encrypt_gcm / Node encryptGcm. Returns the JSON value, or None."""
114
+ key = _derive_gcm_key(secret, info) # programmer error (wrong type) may raise
115
+ try:
116
+ buf = b64url_decode(blob)
117
+ if len(buf) < _GCM_IV_LEN + _GCM_TAG_LEN:
118
+ return None
119
+ iv = buf[:_GCM_IV_LEN]
120
+ tag = buf[_GCM_IV_LEN : _GCM_IV_LEN + _GCM_TAG_LEN]
121
+ ct = buf[_GCM_IV_LEN + _GCM_TAG_LEN :]
122
+ # cryptography expects ciphertext || tag, so reorder the Node layout.
123
+ plaintext = AESGCM(key).decrypt(iv, ct + tag, None)
124
+ value: Any = json.loads(plaintext.decode("utf-8"))
125
+ return value
126
+ except (ValueError, UnicodeError, InvalidTag, RecursionError):
127
+ return None
capwx/_jsint.py ADDED
@@ -0,0 +1,68 @@
1
+ """JavaScript integer semantics. Every function here mirrors a JS operator.
2
+
3
+ Pitfall list:
4
+ - Python ``%`` on negatives differs from JS -> always ``js_rem``.
5
+ - Python ``bool`` is an ``int`` -> every "is this a number" check must exclude ``bool``.
6
+ - ``charCodeAt`` is UTF-16 code units, not code points -> ``utf16_units``.
7
+ """
8
+
9
+ import math
10
+
11
+
12
+ def to_int32(n: int) -> int: # JS: n | 0 (for integer n)
13
+ n &= 0xFFFFFFFF
14
+ return n - (1 << 32) if n & 0x80000000 else n
15
+
16
+
17
+ def to_uint32(n: int) -> int: # JS: n >>> 0
18
+ return n & 0xFFFFFFFF
19
+
20
+
21
+ def js_shl(a: int, k: int) -> int: # JS: a << k
22
+ return to_int32(to_int32(a) << (k & 31))
23
+
24
+
25
+ def js_sar(a: int, k: int) -> int: # JS: a >> k (arithmetic)
26
+ return to_int32(a) >> (k & 31)
27
+
28
+
29
+ def js_shr(a: int, k: int) -> int: # JS: a >>> k (logical)
30
+ return to_uint32(a) >> (k & 31)
31
+
32
+
33
+ def js_xor(a: int, b: int) -> int: # JS: a ^ b
34
+ return to_int32(to_int32(a) ^ to_int32(b))
35
+
36
+
37
+ def js_and(a: int, b: int) -> int:
38
+ return to_int32(to_int32(a) & to_int32(b))
39
+
40
+
41
+ def js_or(a: int, b: int) -> int:
42
+ return to_int32(to_int32(a) | to_int32(b))
43
+
44
+
45
+ def js_not(a: int) -> int: # JS: ~a
46
+ return to_int32(~to_int32(a))
47
+
48
+
49
+ def js_rem(a: int, b: int) -> int: # JS: a % b (sign follows dividend!)
50
+ return int(math.fmod(a, b))
51
+
52
+
53
+ def utf16_units(s: str) -> list[int]: # JS: s.charCodeAt(i) for each i
54
+ b = s.encode("utf-16-le")
55
+ return [int.from_bytes(b[i : i + 2], "little") for i in range(0, len(b), 2)]
56
+
57
+
58
+ def js_number_str(n: int) -> str: # JS: String(n) for safe integers
59
+ return str(n)
60
+
61
+
62
+ def is_js_number(x: object) -> bool: # JS: typeof x === "number" && isFinite(x)
63
+ if not isinstance(x, (int, float)) or isinstance(x, bool):
64
+ return False
65
+ try:
66
+ return math.isfinite(x)
67
+ except OverflowError: # int beyond double range acts as Infinity in JS
68
+ return False
capwx/_types.py ADDED
@@ -0,0 +1,35 @@
1
+ """capwx._types: shared typing helpers for the JSON-shaped payloads.
2
+
3
+ Challenge payloads, solutions and decrypted claims are JSON values whose contents are checked
4
+ at runtime. They are typed ``Any`` at the boundary and narrowed with the helpers below, which
5
+ cast once after an ``isinstance`` check, instead of leaving bare ``dict`` / ``list`` types behind.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from typing import Any, TypeAlias, cast
12
+
13
+ JsonDict: TypeAlias = dict[str, Any]
14
+ JsonList: TypeAlias = list[Any]
15
+
16
+
17
+ def as_json_dict(value: object) -> JsonDict | None:
18
+ """Return ``value`` as a JSON object (``dict``) or None. Never raises."""
19
+ if not isinstance(value, dict):
20
+ return None
21
+ return cast(JsonDict, value)
22
+
23
+
24
+ def as_mapping(value: object) -> Mapping[Any, Any] | None:
25
+ """Return ``value`` as a mapping (dict-like) or None. Never raises."""
26
+ if not isinstance(value, Mapping):
27
+ return None
28
+ return cast("Mapping[Any, Any]", value)
29
+
30
+
31
+ def as_json_list(value: object) -> JsonList | None:
32
+ """Return ``value`` as a JSON array (``list``) or None. Never raises."""
33
+ if not isinstance(value, list):
34
+ return None
35
+ return cast(JsonList, value)
@@ -0,0 +1 @@
1
+ """capwx._vendor: vendored third-party binary assets."""
@@ -0,0 +1 @@
1
+ 74b567a31276a4c5d7cb232a5b7639467f49f961
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1 @@
1
+ b1a0dbb3ef444d3c7069e0a5e0a0273ffa4cf8fef62cbbe43761c02f7cd6aff5 hashwx.wasm
@@ -0,0 +1 @@
1
+ """capwx._vendor.hashwx: vendored HashWX wasm (LGPL-3.0), loaded via importlib.resources."""
Binary file