generateApiKey 0.5.0__tar.gz → 0.7.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.
Files changed (77) hide show
  1. {generateapikey-0.5.0 → generateapikey-0.7.0}/AGENTS.md +8 -2
  2. generateapikey-0.7.0/CHANGELOG.md +258 -0
  3. generateapikey-0.7.0/CONTRIBUTING.md +59 -0
  4. {generateapikey-0.5.0 → generateapikey-0.7.0}/PKG-INFO +274 -52
  5. {generateapikey-0.5.0 → generateapikey-0.7.0}/README.md +262 -46
  6. generateapikey-0.7.0/SECURITY.md +226 -0
  7. generateapikey-0.7.0/benchmarks/compare.py +129 -0
  8. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/__init__.py +19 -2
  9. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/__main__.py +22 -0
  10. generateapikey-0.7.0/generateapikey/_jwt_asym.py +195 -0
  11. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/crypto.py +14 -1
  12. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/__init__.py +21 -2
  13. generateapikey-0.7.0/generateapikey/keystore.py +229 -0
  14. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/llms-full.txt +135 -2
  15. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/mfa.py +186 -15
  16. generateapikey-0.7.0/generateapikey/scanning.py +80 -0
  17. generateapikey-0.7.0/generateapikey/scopes.py +55 -0
  18. generateapikey-0.7.0/generateapikey/tokens.py +478 -0
  19. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/utils.py +61 -7
  20. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey.egg-info/PKG-INFO +274 -52
  21. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey.egg-info/SOURCES.txt +15 -1
  22. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey.egg-info/requires.txt +19 -1
  23. generateapikey-0.7.0/llms.txt +38 -0
  24. {generateapikey-0.5.0 → generateapikey-0.7.0}/pyproject.toml +11 -10
  25. {generateapikey-0.5.0 → generateapikey-0.7.0}/skills/generateapikey/SKILL.md +11 -2
  26. generateapikey-0.7.0/tests/test_compat.py +89 -0
  27. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_docs.py +9 -3
  28. generateapikey-0.7.0/tests/test_hardening_jwt.py +510 -0
  29. generateapikey-0.7.0/tests/test_hardening_mfa.py +315 -0
  30. generateapikey-0.7.0/tests/test_hardening_utils.py +241 -0
  31. generateapikey-0.7.0/tests/test_jwt.py +280 -0
  32. generateapikey-0.7.0/tests/test_keystore.py +81 -0
  33. generateapikey-0.7.0/tests/test_mfa_extras.py +98 -0
  34. generateapikey-0.7.0/tests/test_properties.py +106 -0
  35. generateapikey-0.7.0/tests/test_scopes_scanning.py +129 -0
  36. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_security.py +3 -0
  37. generateapikey-0.7.0/tests/test_vectors.py +359 -0
  38. generateapikey-0.5.0/CHANGELOG.md +0 -102
  39. generateapikey-0.5.0/CONTRIBUTING.md +0 -34
  40. generateapikey-0.5.0/SECURITY.md +0 -19
  41. generateapikey-0.5.0/generateapikey/tokens.py +0 -123
  42. generateapikey-0.5.0/llms.txt +0 -27
  43. generateapikey-0.5.0/tests/test_compat.py +0 -53
  44. {generateapikey-0.5.0 → generateapikey-0.7.0}/LICENSE +0 -0
  45. {generateapikey-0.5.0 → generateapikey-0.7.0}/MANIFEST.in +0 -0
  46. {generateapikey-0.5.0 → generateapikey-0.7.0}/benchmarks/bench.py +0 -0
  47. {generateapikey-0.5.0 → generateapikey-0.7.0}/examples/__init__.py +0 -0
  48. {generateapikey-0.5.0 → generateapikey-0.7.0}/examples/django_quickstart.md +0 -0
  49. {generateapikey-0.5.0 → generateapikey-0.7.0}/examples/fastapi_app.py +0 -0
  50. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateApiKey.py +0 -0
  51. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/aiohttp.py +0 -0
  52. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/django.py +0 -0
  53. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/drf.py +0 -0
  54. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/falcon.py +0 -0
  55. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/fastapi.py +0 -0
  56. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/flask.py +0 -0
  57. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/litestar.py +0 -0
  58. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/quart.py +0 -0
  59. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/sanic.py +0 -0
  60. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/integrations/starlette.py +0 -0
  61. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/limiters.py +0 -0
  62. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/py.typed +0 -0
  63. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey/qr.py +0 -0
  64. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey.egg-info/dependency_links.txt +0 -0
  65. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey.egg-info/entry_points.txt +0 -0
  66. {generateapikey-0.5.0 → generateapikey-0.7.0}/generateapikey.egg-info/top_level.txt +0 -0
  67. {generateapikey-0.5.0 → generateapikey-0.7.0}/setup.cfg +0 -0
  68. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/conftest.py +0 -0
  69. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_examples.py +0 -0
  70. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_extras.py +0 -0
  71. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_generate.py +0 -0
  72. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_integrations_asgi.py +0 -0
  73. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_integrations_core.py +0 -0
  74. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_integrations_django.py +0 -0
  75. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_integrations_flask.py +0 -0
  76. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_integrations_more.py +0 -0
  77. {generateapikey-0.5.0 → generateapikey-0.7.0}/tests/test_mfa.py +0 -0
@@ -1,6 +1,6 @@
1
1
  # AGENTS.md
2
2
 
3
- Guidance for AI coding agents working **on** this repository. To *use* the library, read [generateapikey/llms-full.txt](generateapikey/llms-full.txt).
3
+ Guidance for AI coding agents working **on** the Python package (`python/` in the monorepo; see the root `AGENTS.md` for the repo layout and `spec/SPEC.md` for the cross-language wire formats). To *use* the library, read [generateapikey/llms-full.txt](generateapikey/llms-full.txt).
4
4
 
5
5
  ## Project
6
6
 
@@ -11,7 +11,11 @@ generateapikey/
11
11
  __init__.py generate_api_key, ApiKey, batch/async, legacy generateApiKey(), re-exports
12
12
  utils.py charsets, unbiased rejection sampling, derivation, checksum, hashing
13
13
  mfa.py TOTP/HOTP, recovery codes, OTP, AttemptLimiter
14
- tokens.py signed expiring tokens
14
+ tokens.py signed expiring tokens, JWT (HS*; asymmetric algorithms via _jwt_asym.py)
15
+ _jwt_asym.py RS/PS/ES/EdDSA and ML-DSA-44/65/87 (FIPS 204, JOSE per RFC 9964) [crypto extra]
16
+ imports `cryptography` lazily; ML-DSA imports cryptography...asymmetric.mldsa only
17
+ when used (needs cryptography>=48, else ImportError). Parsed PEM keys are cached
18
+ (_load_private/_load_public, functools.lru_cache(maxsize=64))
15
19
  qr.py QR output (optional `qrcode` extra, imported lazily)
16
20
  crypto.py SecretBox (AES-GCM) for secrets at rest [crypto extra]
17
21
  limiters.py Redis attempt limiters (atomic Lua) [redis extra]
@@ -29,6 +33,7 @@ examples/, benchmarks/
29
33
  ## Commands
30
34
 
31
35
  ```bash
36
+ cd python
32
37
  pip install -e ".[dev]" # test deps + every extra + ruff/mypy/bandit/pre-commit
33
38
  pytest -q # passes on 3.9-3.14
34
39
  ruff check . && ruff format --check . && mypy && bandit -q -r generateapikey generateApiKey.py
@@ -43,5 +48,6 @@ python -m build && twine check dist/*
43
48
  - **Version lives in two places:** `pyproject.toml` and `generateapikey/__init__.py`. A test enforces that they match. Don't switch to `attr:` dynamic versioning: on case-insensitive filesystems setuptools resolves it to the `generateApiKey.py` alias.
44
49
  - **When adding a public function:** add it to `__all__`, give it a typed signature and docstring, write tests, and update README.md, `generateapikey/llms-full.txt` and CHANGELOG.md.
45
50
  - **Framework adapters stay thin.** All auth logic lives in `integrations/__init__.py` so every framework behaves the same. Adapters only map request -> `extract`/`authenticate` and `AuthError` -> response. Test each adapter against the real framework (`pytest.importorskip`).
51
+ - **Don't remove the PEM key cache** in `_jwt_asym.py`. Loading an RSA-2048 PEM costs ~47 ms because `cryptography` re-validates the key; without the cache RS256 signing drops from 1,344/s to 22/s (Apple M3, Python 3.11, cryptography 51).
46
52
  - **MFA code must match the RFCs.** Keep the RFC 4226/6238 test vectors in `tests/test_mfa.py` passing.
47
53
  - Supported Python is 3.9+. Use `from __future__ import annotations` and `typing.Optional`/`Union` rather than runtime `X | Y`.
@@ -0,0 +1,258 @@
1
+ # Changelog
2
+
3
+ ## 0.7.0
4
+
5
+ ### Added
6
+ - Post-quantum JWT signatures: `encode_jwt` / `decode_jwt` / `decode_jwt_jwks` accept
7
+ `ML-DSA-44`, `ML-DSA-65` and `ML-DSA-87` (NIST FIPS 204, JOSE encoding per RFC 9964: empty
8
+ context, raw signature, `AKP` JWKs). Keys are PEM PKCS#8/SPKI. Needs `cryptography>=48`
9
+ (imported lazily; older versions raise `ImportError` only when an ML-DSA algorithm is used).
10
+ Tokens verify in the npm package and vice versa.
11
+ - `decode_jwt(..., verify_aud=True, typ=None)`, also accepted by `decode_jwt_jwks`:
12
+ `verify_aud=False` turns the audience check off (see Security); `typ="at+jwt"` requires that
13
+ header `typ` (RFC 8725 §3.11 explicit typing; compared case-insensitively, `application/`
14
+ prefix optional).
15
+ - `encode_jwt(..., headers={"typ": "at+jwt"})` now keeps a string `typ` header instead of forcing `"JWT"`, so explicitly
16
+ typed tokens can be issued and then checked with the `typ` decode option.
17
+ - `utils.code_needs_rehash(hashed, iterations=KDF_ITERATIONS)`: true when a stored OTP/recovery
18
+ code hash uses another iteration count (or is malformed). Call it after a successful verify and
19
+ store a fresh hash, to move to a new count without breaking old hashes.
20
+ - `mfa.find_steam_step(secret, code, *, window=1, at=None, last_used_step=None)` and
21
+ `verify_steam_code(..., last_used_step=None)`: replay protection for Steam Guard codes, like
22
+ `find_totp_step`.
23
+ - `mfa.MAX_TOTP_WINDOW = 10` and `mfa.MAX_HOTP_LOOK_AHEAD = 100`.
24
+
25
+ ### Changed
26
+ - JWTs up to 16384 characters are accepted (was 8192), so ML-DSA-87 tokens fit. Signed tokens
27
+ (`verify_signed_token`) keep the 8192 limit.
28
+ - Wire-format spec v3 (`spec/SPEC.md`). v2 added the ML-DSA algorithms and the new JWT length
29
+ limit; v3 adds the verification rules under Security. The only produced value
30
+ that changes is a JWT header given a string `typ`, but some tokens and hashes
31
+ that 0.6 accepted are now rejected, and some calls now raise (below).
32
+
33
+ ### Security
34
+ Each item below **may reject tokens, codes or calls that 0.6 accepted**; the ones marked
35
+ *breaking* change the result for well-formed input from a correctly configured caller.
36
+ - **`decode_jwt` / `decode_jwt_jwks` no longer raise on hostile tokens.** A deeply nested JSON
37
+ header (about 15 KB) raised `RecursionError` before any signature check, so any client could
38
+ trigger a 500. Both now return `None`, the claims JSON is parsed only after the signature
39
+ verifies, and `decode_jwt_jwks` enforces the 16384-character limit before parsing anything
40
+ (the same class as Authlib CVE-2025-61920).
41
+ - **JWT segments must be UTF-8** (RFC 7515 §2, RFC 7519 §7.2). UTF-16/UTF-32 header or claims
42
+ JSON was accepted (via `json.detect_encoding`) though the npm package rejected it; both now
43
+ reject it. One leading UTF-8 BOM is still ignored, as in JS.
44
+ - **`crit` headers are rejected** (RFC 7515 §4.1.11): a token whose header has `crit`, even
45
+ `[]`, is invalid, because no JWS extensions are implemented. `encode_jwt(headers={"crit": ...})`
46
+ raises `ValueError`. Same bug as PyJWT CVE-2026-32597 (GHSA-752w-5fwx-jx9f) and Authlib
47
+ CVE-2025-59420.
48
+ - **NaN and Infinity.** `exp`, `nbf` and `iat` must be finite, non-boolean numbers. Before, an
49
+ `exp` of `NaN`, `Infinity` or `1e400` never expired, in JWTs and in signed tokens. An integer too
50
+ large for a float (which JavaScript reads as Infinity) also counts as non-finite. `NaN` and
51
+ `Infinity` literals anywhere in a token are rejected (they aren't JSON), and `encode_jwt` /
52
+ `generate_signed_token` raise `ValueError` instead of emitting them.
53
+ - **Canonical base64url only.** All three JWT segments must be unpadded, URL-safe and canonical
54
+ (unused low bits zero). Before, `sig + "="`, `+`/`/`, inserted junk characters or a different
55
+ last character still verified, so one token had many spellings and could dodge a denylist keyed
56
+ on the token string. This removes the "Python-only" leniency the v2 spec listed.
57
+ - **Public keys are refused as HMAC secrets** (*breaking* for misconfigured callers). An HS
58
+ secret, and the secret of `generate_signed_token` / `verify_signed_token`, that starts (after
59
+ whitespace) with `-----BEGIN`, `ssh-rsa`, `ssh-ed25519`, `ecdsa-sha2-` or `{"kty"` raises
60
+ `ValueError`. A public key used as an HMAC secret lets anyone forge tokens: the root cause of
61
+ CVE-2022-29217 (PyJWT), CVE-2024-33663 (python-jose) and CVE-2024-37568 (Authlib).
62
+ - **Audience** (*breaking*). A token with an `aud` claim is rejected unless you pass `audience`
63
+ (RFC 7519 §4.1.3), so a token issued for another service of the same issuer can't be replayed at
64
+ yours. If you check `aud` yourself, pass `verify_aud=False`. `aud: null` counts as absent.
65
+ - **`iat`**, if present, must be a finite number. A future `iat` is still accepted (rejecting it
66
+ only causes clock-skew false rejects).
67
+ - **RSA keys under 2048 bits no longer verify** (*breaking* for legacy issuers). `decode_jwt`
68
+ raises `ValueError`, as signing already did (RFC 7518 §3.3). In `decode_jwt_jwks` such keys are
69
+ skipped.
70
+ - **JWKS keys are filtered by `use`, `alg` and `key_ops`** (RFC 7517 §4.2-4.4). A JWK with `use`
71
+ other than `"sig"`, an `alg` other than the token's (`"Ed25519"` counts as `"EdDSA"`, RFC 9864),
72
+ or a `key_ops` without `"verify"` is skipped. Before, an encryption key (`use: "enc"`) or an
73
+ RS256-only key could verify a PS256 token.
74
+ - **Attacker-chosen algorithms no longer raise.** With several algorithms pinned, a token whose
75
+ header picks one the key can't do returns `None`. Before, it raised `ValueError`, as did
76
+ `decode_jwt_jwks` when a token without a `kid` met a JWKS with keys of another type. With one
77
+ pinned algorithm a wrong key still raises (a configuration error). `decode_jwt_jwks` now also
78
+ validates every entry of `algorithms`, not only the first.
79
+ - **Option validation** (*breaking* for out-of-range values). `leeway` must be a finite number
80
+ `>= 0` (`NaN` or `inf` accepted any expired token). TOTP/Steam `window` must be an integer in
81
+ 0..10 and HOTP `look_ahead` in 0..100; before, a huge window made a random 6-digit code likely to
82
+ pass, and a negative one silently returned `None`. Out-of-range values raise `ValueError`.
83
+ - **Steam Guard replay protection** (`last_used_step`, `find_steam_step`). Steps before the Unix
84
+ epoch are skipped instead of raising `struct.error`.
85
+ - **Stored PBKDF2 iteration counts are parsed strictly** (`[1-9][0-9]{3,7}`, still within
86
+ 1,000..10,000,000). `int()` accepted `" +1_000 "` and non-ASCII digits, and the JS package parsed
87
+ differently. `hash_code` always wrote canonical counts, so only edited or corrupted hashes are
88
+ affected. The default stays at 100,000 iterations (Cloudflare Workers' cap); use
89
+ `code_needs_rehash` to move to another count.
90
+ - `SecretBox` documents the AES-GCM random-nonce limit (NIST SP 800-38D §8.3): at most 2**32
91
+ encryptions per key, counted across every process sharing it. Rotate with `old_keys` /
92
+ `rotate()` well before that. No format change.
93
+ - `subkey()` results are cached (bounded `functools.lru_cache`, 32 entries; see Performance). A
94
+ rotated-out secret stays in the cache until evicted; call `utils.subkey.cache_clear()` to drop
95
+ it at once. A non-string secret now raises `TypeError` (was `AttributeError`).
96
+
97
+ ### Performance
98
+ Apple M3, single thread, 0.6.0 and 0.7.0 measured back to back on the same machine (Python 3.11, cryptography 51; best of 7 × 20,000 calls; µs per call, lower is better):
99
+
100
+ | Operation | 0.6.0 | 0.7.0 | Speed-up |
101
+ |---|--:|--:|--:|
102
+ | `hash_api_key` with a pepper | 2.67 | 1.19 | 2.2× |
103
+ | `verify_totp` (window 1) | 12.86 | 6.10 | 2.1× |
104
+ | `totp_uri` | 5.02 | 2.51 | 2.0× |
105
+ | `verify_api_key` with a pepper | 3.01 | 1.57 | 1.9× |
106
+ | `encode_jwt` HS256 | 5.59 | 3.33 | 1.7× |
107
+ | `generate_api_key(secret, seed)` | 5.57 | 3.74 | 1.5× |
108
+ | `generate_signed_token` / `verify_signed_token` | 6.41 / 5.56 | 4.47 / 3.88 | 1.4× |
109
+ | `decode_jwt` HS256 (now with the stricter checks) | 6.53 | 5.29 | 1.2× |
110
+
111
+ - Parsed PEM keys are cached (`functools.lru_cache`, 64 entries, the same size as the npm package's
112
+ cache). Before, every asymmetric `encode_jwt` / `decode_jwt` re-parsed the PEM, and loading an
113
+ RSA-2048 PEM takes about 47 ms, so `RS256` signing ran at 38 tokens/s. It now runs at the speed
114
+ of the RSA operation itself: 2,355 tokens/s (62×), the same as PyJWT and joserfc with pre-parsed
115
+ keys. `RS256` verifying went from 30,524 to 48,992/s.
116
+ - How: faster base32 decode and a reused keyed HMAC state for TOTP/HOTP; the otpauth query built
117
+ directly (byte-identical); pre-built JSON encoders, a cached default JWT header and one-shot
118
+ `hmac.digest`; cached per-purpose subkeys (bounded LRU); hash/padding objects resolved once per
119
+ algorithm.
120
+
121
+ ### Repository
122
+ - The repository is now a monorepo: this package lives in `python/`, and its JavaScript/TypeScript
123
+ sibling is published to npm as [`@nuhmanpk/generateapikey`](https://www.npmjs.com/package/@nuhmanpk/generateapikey)
124
+ under the same version number. Both are wire-compatible: keys, hashes, codes, tokens, JWTs and
125
+ ciphertexts made in one language verify in the other.
126
+ - `spec/SPEC.md` documents every format and algorithm (spec v3). `spec/vectors.json` is generated
127
+ from this package by `scripts/gen_vectors.py`, and `tests/test_vectors.py` runs it. `--check` fails if
128
+ the file is out of date. `scripts/interop.py` checks values made by the JS package.
129
+ - The release process changed: every push to `main` that changes `python/` uploads a new version
130
+ to PyPI (skipped when that version is already published) with a PyPI API token (`TWINE_TOKEN`
131
+ secret) instead of Trusted Publishing. The npm package is published by the maintainer from a
132
+ local machine, and `python.yml`, `js.yml`, `interop.yml` and `js-release.yml` were removed. Tests
133
+ run locally, not in GitHub Actions: before a release, 498 tests pass and ruff, mypy (strict) and
134
+ bandit are clean.
135
+ - `npm audit` on the JS package's dev dependencies reports 0 vulnerabilities (`undici`, `ws` and
136
+ `sharp`, pulled in by Miniflare, are pinned with `overrides`). Neither package has runtime dependencies.
137
+ - README links are absolute, so they also work on the PyPI page.
138
+
139
+ ## 0.6.0
140
+
141
+ ### Added
142
+ - `encode_jwt` / `decode_jwt`: standard JWTs with pinned algorithms, `exp`/`nbf`/`iss`/`aud` checks and no `alg: none`. Supports HS256/384/512, and RS256/384/512 and ES256/384/512 with PEM keys via the `crypto` extra. HS* and RS*/ES* can't be mixed in one decode (algorithm-confusion guard). Interoperates with PyJWT.
143
+ - Key scopes: `has_scope`, `has_all_scopes`, `has_any_scope`, `parse_scopes`, and `APIKeyAuth(required_scopes=...)` / `authenticate(key, scopes=...)` (403 when a valid key lacks a scope).
144
+ - `generateapikey.keystore`: `KeyStore` (SQLite, standard library) with create, lookup, list, revoke, last-used and rotation, plus `rotate_api_key` for your own database.
145
+ - Leak detection: `key_pattern`, `find_keys` and `scanning.gitleaks_rule`.
146
+ - JWT: PS256/384/512, EdDSA and `decode_jwt_jwks` (JWKS verification, `kid` only selects among trusted keys).
147
+ - MFA: `steam_code` / `verify_steam_code` (Steam Guard style codes) and `google_migration_uri` (Google Authenticator import).
148
+ - Tests: Hypothesis property and fuzz tests, a chi-square uniformity test (with a modulo-bias control), coverage reporting in CI.
149
+ - `generate-api-key --agent-rules` prints a snippet for `AGENTS.md` / `CLAUDE.md` / `.cursor/rules` that tells coding agents to use this library. Agent-facing docs (`llms.txt`, the LLM guide, the skill, `context7.json`) now include a "when to use" decision table, and PyPI keywords cover agent and JWT/scopes searches.
150
+ - New animated product tour `assets/tour.svg`, shown in the README.
151
+ - `benchmarks/compare.py` and a feature and speed comparison against secrets, pyotp, itsdangerous, PyJWT, shortuuid and nanoid in the README.
152
+
153
+ ### Performance
154
+ - `generate_api_key()` is about 2× faster (5.8 → 2.8 µs): the resolved alphabet is now cached instead of rebuilt on every call.
155
+
156
+ ### Fixed
157
+ - CI: Django extras on Python 3.9, UTF-8 doc reads on Windows, import-order lint.
158
+
159
+ ## 0.5.0
160
+
161
+ ### Renamed
162
+ - The package is now **`generateapikey`** (lowercase), both on PyPI and as the import name. PyPI treats names case-insensitively, so `pip install generateApiKey` still works. `import generateApiKey` (including submodules) keeps working through an alias module that emits a `DeprecationWarning`.
163
+
164
+ ### Security
165
+ Fixes from an internal review. The issues below were found in this release's code before it was published:
166
+ - **Attacker input could crash verification.** `verify_totp`, `verify_hotp`, `verify_checksum` and `verify_signed_token` raised `TypeError` on non-ASCII input (e.g. `١٢٣٤٥٦`), which surfaced as an HTTP 500. All verifiers now return False/None on any input.
167
+ - **`AttemptLimiter` could be bypassed with parallel requests.** The new atomic `hit()` counts an attempt before verification, and the docs now use it.
168
+ - **`AttemptLimiter` memory and CPU DoS.** It was O(n) per call after 100k keys and unbounded. It is now capped by `max_keys` with O(1) amortized eviction (expired entries first).
169
+ - **Short codes were stored with fast unsalted SHA-256.** OTPs reversed instantly from a leaked hash. OTPs and recovery codes now use salted PBKDF2-SHA256 (100k iterations, format `pbkdf2-sha256$...`).
170
+ - **Domain separation.** Tokens, hash peppers and derived keys use independent subkeys, so reusing one server secret can't forge across features.
171
+ - **Stricter inputs:**
172
+ - Empty peppers are rejected (they silently disabled the pepper before).
173
+ - TOTP secrets under 80 bits are rejected.
174
+ - Token secrets must be at least 16 characters.
175
+ - TOTP/HOTP `digits` is capped at 8, per the RFC.
176
+ - `:` is rejected in otpauth issuer/account.
177
+ - `inf`/`NaN` expiry is rejected.
178
+ - OTP `charset` is validated.
179
+ - Integer codes keep their leading zeros.
180
+ - Recovery codes must be at least 8 characters.
181
+ - **`repr(ApiKey)` is redacted** so keys don't leak into logs and tracebacks.
182
+ - **CLI secrets** can be passed via stdin (`-`) or `GENERATEAPIKEY_SECRET`, `GENERATEAPIKEY_PEPPER` and `GENERATEAPIKEY_TOTP_SECRET`, instead of argv.
183
+ - **CI hardening:**
184
+ - Read-only default permissions.
185
+ - The release workflow runs the full test suite and `twine check` before uploading.
186
+ - A bandit scan runs on every push.
187
+ - Dependabot is enabled.
188
+ - `SECURITY.md` has been added.
189
+
190
+ ### Added: production extras
191
+ - **More frameworks:** Sanic, aiohttp, Quart and Falcon (WSGI and ASGI), each tested against the real framework.
192
+ - **Rotation:**
193
+ - Django `AbstractAPIKey.rotate(grace=...)` keeps the old key valid during a grace period.
194
+ - Pepper rotation via `APIKeyAuth(previous_peppers=..., on_rehash=...)`, plus the Django `rehash_model()` hook.
195
+ - **Session-bound tokens:** `generate_signed_token(..., context=session_id)` and the matching `verify_signed_token(..., context=...)`. A leaked link fails outside the session that requested it.
196
+ - **`generateapikey.crypto`** (`[crypto]`): `SecretBox` encrypts TOTP and other secrets at rest. AES-256-GCM, associated data, key rotation.
197
+ - **`generateapikey.limiters`** (`[redis]`): `RedisAttemptLimiter` and `AsyncRedisAttemptLimiter` share atomic counters across processes. `APIKeyAuth` accepts sync or async limiters.
198
+ - **Segment-aware `exclude` matching:** `/health` no longer also excludes `/healthz`.
199
+ - **Tooling:**
200
+ - Strict mypy across the core and ruff lint and format.
201
+ - pre-commit config, plus a `dev` extra.
202
+ - CI tests Python 3.9–3.14 on Linux, macOS and Windows, adds a zero-dependency job, and runs ruff, mypy and bandit.
203
+ - **Repo:** `examples/` (a full FastAPI app run in CI, and a Django quickstart), `benchmarks/bench.py`, CONTRIBUTING.md, and issue/PR templates.
204
+
205
+ ### Added: framework integrations
206
+ - `generateapikey.integrations` holds the framework-agnostic core:
207
+ - `APIKeyAuth` handles header/Bearer extraction, prefix and checksum pre-checks, hash-only lookup, revoked/expired checks, optional rate limiting and an `on_success` hook. Lookups can be sync or async.
208
+ - `issue_api_key()` returns the key, its hash and a display hint.
209
+ - Adapters, each as an optional extra:
210
+ - **FastAPI**: `APIKeyDependency`, with an OpenAPI security scheme.
211
+ - **Starlette**: `APIKeyBackend`.
212
+ - **Django**: `AbstractAPIKey` model with `create_key`, `api_key_required` for sync and async views, `APIKeyMiddleware`, `model_lookup` and `touch_last_used`.
213
+ - **Django REST Framework**: `APIKeyAuthentication` and `HasAPIKey`.
214
+ - **Flask**: `require_api_key` and `FlaskAPIKey`.
215
+ - **Litestar**: `api_key_middleware`.
216
+ - Each adapter is tested against the real framework.
217
+
218
+ ### Added: MFA
219
+ - **TOTP / HOTP** (RFC 6238 / 4226) in `generateapikey.mfa`: `generate_totp_secret`, `totp`, `totp_now`, `verify_totp`, `find_totp_step` (replay protection), `hotp`, `verify_hotp`, `totp_uri` and `hotp_uri` (`otpauth://` URIs for QR setup). Supports SHA-1/256/512, 6–10 digits and custom periods. Tested against the official RFC test vectors.
220
+ - **Recovery codes**: `generate_recovery_codes`, `hash_recovery_code`, `verify_recovery_code`. Crockford base32, single use, tolerant of case, dashes and look-alike characters.
221
+ - **Email/SMS one-time codes**: `generate_otp`, `hash_otp`, `verify_otp`.
222
+ - **Signed tokens** for magic links, email verification and password resets, in `generateapikey.tokens`: `generate_signed_token`, `verify_signed_token`. HMAC-SHA256, with expiry, purpose binding and a unique `jti`.
223
+ - **`AttemptLimiter`**: thread-safe, in-memory brute-force guard.
224
+ - **QR codes** (`pip install "generateapikey[qr]"`): `qr_svg`, `qr_png`, `qr_ascii` in `generateapikey.qr`.
225
+ - CLI subcommands: `totp` (with `--qr`), `code`, `recovery`, `otp`, `token`. A `generateapikey` command alias is also installed.
226
+
227
+ ### Added: AI coding agent support
228
+ - `llms.txt` index and a full `llms-full.txt` guide. The guide ships in the wheel and is printed by `generate-api-key --llms`.
229
+ - A drop-in Agent Skill (`skills/generateapikey/SKILL.md`), `AGENTS.md` for contributors, and `context7.json`.
230
+ - Tests that fail if the documented imports drift from the real API.
231
+
232
+ ### Added: API keys
233
+ - `checksum=True`: appends a 6-char CRC32 (base62) to the key. Check it offline with `verify_checksum()`.
234
+ - `hash_api_key()` / `verify_api_key()`: SHA-256 storage hashing, with optional HMAC pepper and constant-time verification. `ApiKey.hash()` is a shortcut.
235
+ - `generate_api_keys(count, ...)` for batches.
236
+ - `entropy_bits()`, the `min_entropy=` option, and `WeakKeyWarning` for random keys below 128 bits.
237
+ - `expiry` accepts a `timedelta` or fractional minutes.
238
+ - `ApiKey.expires_in` and `ApiKey.expires_at_datetime`. `ApiKey` now pickles with its expiry and has an informative `repr`.
239
+ - `dash_char=` option.
240
+ - New charsets: `base32`, `crockford`, `unambiguous`.
241
+ - `generate-api-key` command-line tool (also `python -m generateApiKey`).
242
+ - `__version__`, `py.typed`, a test CI matrix (3.9–3.13, Linux/macOS/Windows), and `pyproject.toml`.
243
+
244
+ ### Changed
245
+ - **Derived keys (`secret` + `seed`) are now deterministic**: the same inputs give the same key. Previously a random salt and a timestamp made every call different, so the secret had no effect on the result. The legacy `generateApiKey()` keeps its old one-key-per-call behaviour.
246
+ - Character sampling uses rejection sampling, so it is unbiased. It is also about 20× faster.
247
+ - Removed the unused `cryptography` dependency. The package now has zero dependencies.
248
+
249
+ ### Fixed
250
+ - Modulo bias in derived keys: some characters were about 25% more likely.
251
+ - Duplicate characters in a custom charset skewed the output.
252
+ - `expiry=0` was silently ignored, and negative expiry was accepted.
253
+ - Empty `secret`/`seed` strings silently fell back to random keys.
254
+ - `include` without `secret`/`seed` was silently ignored.
255
+ - `case="lower"`/`"upper"` on `base58` re-introduced look-alike characters.
256
+
257
+ ### Deprecated
258
+ - `is_token_valid()`: no API ever produced the token format it checks. Use `ApiKey.is_expired` instead.
@@ -0,0 +1,59 @@
1
+ # Contributing
2
+
3
+ Thanks for helping! Bug reports, docs fixes, new framework adapters and features are all welcome.
4
+
5
+ ## Setup
6
+
7
+ ```bash
8
+ git clone https://github.com/nuhmanpk/generate-api-key
9
+ cd generate-api-key/python
10
+ python -m venv .venv && source .venv/bin/activate
11
+ pip install -e ".[dev]"
12
+ pre-commit install
13
+ ```
14
+
15
+ ## Checks (run these locally before pushing; GitHub Actions runs no tests)
16
+
17
+ ```bash
18
+ pytest -q # all tests, all frameworks
19
+ ruff check . && ruff format --check .
20
+ mypy # strict
21
+ bandit -q -r generateapikey generateApiKey.py
22
+ ```
23
+
24
+ JavaScript package, from the repo root (Node 24.7+ runs the ML-DSA tests; older Node skips them):
25
+
26
+ ```bash
27
+ cd js
28
+ npm ci
29
+ npm run typecheck
30
+ npm test
31
+ npm run build && npm run test:smoke
32
+ ```
33
+
34
+ Cross-language checks (from the repo root, after `npm run build`; Python needs the `crypto` extra):
35
+
36
+ ```bash
37
+ python python/scripts/gen_vectors.py --check # spec/vectors.json is up to date
38
+ node js/test/interop.mjs make > /tmp/js.json && python python/scripts/interop.py verify /tmp/js.json
39
+ python python/scripts/interop.py make > /tmp/py.json && node js/test/interop.mjs verify < /tmp/py.json
40
+ ```
41
+
42
+ ## Releases
43
+
44
+ The version lives in 4 places: `python/pyproject.toml`, `python/generateapikey/__init__.py`,
45
+ `js/package.json` and `js/src/index.ts` (`VERSION`). A test checks they match. Pushing a new
46
+ version to `main` is what triggers a PyPI release; the workflow skips versions already on PyPI.
47
+ The npm package is published by the maintainer.
48
+
49
+ ## Guidelines
50
+
51
+ - **No runtime dependencies.** Anything third-party goes behind an optional extra and a lazy import.
52
+ - **Security first.** Use `secrets` for randomness and `utils.safe_equals` for comparisons. Verifiers must return False/None on bad input, never raise. Add a test with hostile input.
53
+ - **Framework adapters stay thin.** Logic belongs in `generateapikey/integrations/__init__.py`. Test each adapter against the real framework, guarded by `pytest.importorskip`.
54
+ - **Docs:** when you change the public API, update `python/README.md`, `python/generateapikey/llms-full.txt` (the guide AI agents read) and `python/CHANGELOG.md`. `python/tests/test_docs.py` fails if a documented import doesn't exist.
55
+ - Supports Python 3.9+.
56
+
57
+ ## Security issues
58
+
59
+ Please report them privately. See [SECURITY.md](SECURITY.md).