fastapi-panel 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.
fastapi_panel/py.typed ADDED
File without changes
@@ -0,0 +1,139 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import hashlib
5
+ import hmac
6
+ import json
7
+ import secrets
8
+ import time
9
+ from typing import Any
10
+
11
+ SCRYPT_N = 2**15
12
+ SCRYPT_R = 8
13
+ SCRYPT_P = 1
14
+ SCRYPT_MAXMEM = 128 * 1024 * 1024
15
+
16
+
17
+ def _b64encode(data: bytes) -> str:
18
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
19
+
20
+
21
+ def _b64decode(data: str) -> bytes:
22
+ return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
23
+
24
+
25
+ class Signer:
26
+ """Tamper-proof (not encrypted) JSON tokens, used for the session cookie."""
27
+
28
+ def __init__(self, secret: str, salt: str = "session") -> None:
29
+ self._key = hashlib.sha256(f"{salt}:{secret}".encode()).digest()
30
+
31
+ def _signature(self, payload: str) -> str:
32
+ return _b64encode(hmac.new(self._key, payload.encode(), hashlib.sha256).digest())
33
+
34
+ def dumps(self, data: object) -> str:
35
+ payload = _b64encode(json.dumps(data, separators=(",", ":")).encode())
36
+ return f"{payload}.{self._signature(payload)}"
37
+
38
+ def loads(self, token: str) -> object | None:
39
+ payload, _, signature = token.partition(".")
40
+ if not hmac.compare_digest(self._signature(payload).encode(), signature.encode()):
41
+ return None
42
+ try:
43
+ return json.loads(_b64decode(payload))
44
+ except ValueError:
45
+ return None
46
+
47
+
48
+ def hash_password(password: str) -> str:
49
+ salt = secrets.token_bytes(16)
50
+ digest = hashlib.scrypt(password.encode(), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P, maxmem=SCRYPT_MAXMEM)
51
+ return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${_b64encode(salt)}${_b64encode(digest)}"
52
+
53
+
54
+ def verify_password(password: str, encoded: str) -> bool:
55
+ try:
56
+ scheme, n, r, p, salt, digest = encoded.split("$")
57
+ if scheme != "scrypt":
58
+ return False
59
+ expected = _b64decode(digest)
60
+ actual = hashlib.scrypt(
61
+ password.encode(),
62
+ salt=_b64decode(salt),
63
+ n=int(n),
64
+ r=int(r),
65
+ p=int(p),
66
+ maxmem=SCRYPT_MAXMEM,
67
+ dklen=len(expected),
68
+ )
69
+ except (ValueError, AttributeError):
70
+ return False
71
+ return hmac.compare_digest(actual, expected)
72
+
73
+
74
+ # Verified against when a username does not exist, so response time doesn't reveal which do.
75
+ DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
76
+
77
+
78
+ class LoginThrottle:
79
+ # shortcut: counters live in this process, use a shared store if you run many workers and need a strict limit
80
+ def __init__(self, max_attempts: int = 5, window: int = 900, max_keys: int = 10_000) -> None:
81
+ self.max_attempts = max_attempts
82
+ self.window = window
83
+ self.max_keys = max_keys
84
+ self._failures: dict[str, list[float]] = {}
85
+
86
+ def _recent(self, key: str) -> list[float]:
87
+ cutoff = time.monotonic() - self.window
88
+ return [t for t in self._failures.get(key, []) if t > cutoff]
89
+
90
+ def blocked(self, key: str) -> bool:
91
+ return len(self._recent(key)) >= self.max_attempts
92
+
93
+ def fail(self, key: str) -> None:
94
+ if len(self._failures) >= self.max_keys:
95
+ self._failures.clear()
96
+ self._failures[key] = [*self._recent(key), time.monotonic()]
97
+
98
+ def reset(self, key: str) -> None:
99
+ self._failures.pop(key, None)
100
+
101
+
102
+ class BodyTooLarge(Exception):
103
+ pass
104
+
105
+
106
+ class LimitBody:
107
+ """Counts the bytes as they arrive, because a chunked request has no Content-Length to check."""
108
+
109
+ def __init__(self, app: Any, limit: int) -> None:
110
+ self.app = app
111
+ self.limit = limit
112
+
113
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
114
+ seen = 0
115
+
116
+ async def limited() -> Any:
117
+ nonlocal seen
118
+ message = await receive()
119
+ seen += len(message.get("body", b""))
120
+ if seen > self.limit:
121
+ raise BodyTooLarge
122
+ return message
123
+
124
+ await self.app(scope, limited if scope["type"] == "http" else receive, send)
125
+
126
+
127
+ SECURITY_HEADERS = {
128
+ "Content-Security-Policy": (
129
+ "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; "
130
+ "font-src 'self'; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; "
131
+ "frame-ancestors 'none'"
132
+ ),
133
+ "X-Content-Type-Options": "nosniff",
134
+ "X-Frame-Options": "DENY",
135
+ "Referrer-Policy": "same-origin",
136
+ "Cross-Origin-Opener-Policy": "same-origin",
137
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
138
+ "Cache-Control": "no-store",
139
+ }