codetta 0.8.1__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 (63) hide show
  1. codetta/CHANGELOG.md +153 -0
  2. codetta/__init__.py +8 -0
  3. codetta/__main__.py +5 -0
  4. codetta/cli/__init__.py +0 -0
  5. codetta/cli/__main__.py +59 -0
  6. codetta/cli/run.py +129 -0
  7. codetta/core/__init__.py +0 -0
  8. codetta/core/acoustid.py +225 -0
  9. codetta/core/activity.py +161 -0
  10. codetta/core/artwork.py +238 -0
  11. codetta/core/auth.py +362 -0
  12. codetta/core/avatar.py +92 -0
  13. codetta/core/changelog.py +51 -0
  14. codetta/core/connections.py +159 -0
  15. codetta/core/describe.py +69 -0
  16. codetta/core/engine.py +470 -0
  17. codetta/core/health.py +520 -0
  18. codetta/core/inbox.py +195 -0
  19. codetta/core/index.py +672 -0
  20. codetta/core/library.py +177 -0
  21. codetta/core/musicbrainz.py +662 -0
  22. codetta/core/notifications.py +77 -0
  23. codetta/core/onboarding.py +39 -0
  24. codetta/core/organize.py +490 -0
  25. codetta/core/plugins.py +183 -0
  26. codetta/core/presets.py +452 -0
  27. codetta/core/providers.py +203 -0
  28. codetta/core/rawtags.py +135 -0
  29. codetta/core/slskd.py +650 -0
  30. codetta/core/tagmap.py +538 -0
  31. codetta/core/undo.py +186 -0
  32. codetta/core/updates.py +132 -0
  33. codetta/plugins/__init__.py +63 -0
  34. codetta/plugins/builtin/__init__.py +3 -0
  35. codetta/plugins/builtin/tidy.py +70 -0
  36. codetta/web/__init__.py +0 -0
  37. codetta/web/app.py +2909 -0
  38. codetta/web/security.py +170 -0
  39. codetta/web/static/app.css +2684 -0
  40. codetta/web/static/app.js +5694 -0
  41. codetta/web/static/apple-touch-icon.png +0 -0
  42. codetta/web/static/fonts/LICENSE-Inter.txt +93 -0
  43. codetta/web/static/fonts/LICENSE-SchibstedGrotesk.txt +93 -0
  44. codetta/web/static/fonts/inter-cyrillic.woff2 +0 -0
  45. codetta/web/static/fonts/schibsted-grotesk.woff2 +0 -0
  46. codetta/web/static/icon.svg +1 -0
  47. codetta/web/static/icons/codetta-dark.png +0 -0
  48. codetta/web/static/icons/codetta-dark.svg +1 -0
  49. codetta/web/static/icons/codetta-dark.webp +0 -0
  50. codetta/web/static/icons/codetta-light.png +0 -0
  51. codetta/web/static/icons/codetta-light.svg +1 -0
  52. codetta/web/static/icons/codetta-light.webp +0 -0
  53. codetta/web/static/icons/codetta.png +0 -0
  54. codetta/web/static/icons/codetta.svg +1 -0
  55. codetta/web/static/icons/codetta.webp +0 -0
  56. codetta/web/static/index.html +473 -0
  57. codetta/web/static/theme.js +12 -0
  58. codetta-0.8.1.dist-info/METADATA +282 -0
  59. codetta-0.8.1.dist-info/RECORD +63 -0
  60. codetta-0.8.1.dist-info/WHEEL +5 -0
  61. codetta-0.8.1.dist-info/entry_points.txt +2 -0
  62. codetta-0.8.1.dist-info/licenses/LICENSE +661 -0
  63. codetta-0.8.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,170 @@
1
+ """A protective layer in front of every request.
2
+
3
+ * **Size limits.** Request bodies are capped per endpoint *before* they're
4
+ read, so nobody (signed in or not) can exhaust the server's memory.
5
+ * **Cross-site protection.** Requests that change something must come from
6
+ Codetta's own page. Browsers label requests with ``Sec-Fetch-Site``; for
7
+ older ones we compare ``Origin`` with the host. This also blocks other apps
8
+ on the same server (other ports count as the "same site" for cookies).
9
+ * **Allowed hosts** (optional). With ``CODETTA_ALLOWED_HOSTS`` set, requests
10
+ for any other host name are refused, which stops DNS-rebinding attacks.
11
+ * **Security headers** on every response: a strict Content Security Policy
12
+ (scripts only from Codetta itself), no framing, no MIME sniffing.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from urllib.parse import urlsplit
19
+
20
+ from codetta.core.artwork import MAX_ART_BYTES
21
+ from codetta.core.avatar import MAX_AVATAR_BYTES
22
+
23
+ KB = 1024
24
+ MB = 1024 * KB
25
+
26
+ # Largest request body accepted, by path (the image limits come from the core
27
+ # modules, so there's one source of truth). Everything else gets DEFAULT_LIMIT.
28
+ BODY_LIMITS = {
29
+ "/api/art": MAX_ART_BYTES,
30
+ "/api/account/avatar": MAX_AVATAR_BYTES,
31
+ }
32
+ DEFAULT_LIMIT = 1 * MB # JSON: tag edits, presets, sign-in...
33
+ SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
34
+
35
+ CSP = "; ".join([
36
+ "default-src 'self'",
37
+ "script-src 'self'",
38
+ "style-src 'self' 'unsafe-inline'", # style="" attributes on a few elements
39
+ "img-src 'self' blob: data:", # blob: previews of pending art / avatars
40
+ "font-src 'self'",
41
+ "connect-src 'self'",
42
+ "object-src 'none'",
43
+ "base-uri 'none'",
44
+ "form-action 'self'",
45
+ "frame-ancestors 'none'",
46
+ ])
47
+ SECURITY_HEADERS = [
48
+ (b"x-content-type-options", b"nosniff"),
49
+ (b"x-frame-options", b"DENY"),
50
+ (b"referrer-policy", b"same-origin"),
51
+ (b"cross-origin-opener-policy", b"same-origin"),
52
+ (b"permissions-policy", b"camera=(), microphone=(), geolocation=(), payment=()"),
53
+ ]
54
+ # The interactive API docs load Swagger UI from a CDN, so they get no CSP.
55
+ NO_CSP_PATHS = ("/docs", "/openapi.json")
56
+
57
+
58
+ def _first(value: str) -> str:
59
+ """X-Forwarded-Host can be a list ("a.example, b.internal"); the first is the client's."""
60
+ return value.split(",")[0].strip()
61
+
62
+
63
+ def _host_only(host: str) -> str:
64
+ """ "Example.com:8111" -> "example.com", "[::1]:8111" -> "::1"."""
65
+ host = host.strip().lower()
66
+ if host.startswith("["):
67
+ return host[1:].split("]", 1)[0]
68
+ return host.rsplit(":", 1)[0] if host.count(":") == 1 else host
69
+
70
+
71
+ class GuardMiddleware:
72
+ """Pure ASGI middleware (runs before FastAPI reads anything)."""
73
+
74
+ def __init__(self, app, allowed_hosts: set[str] | None = None) -> None:
75
+ self.app = app
76
+ self.allowed_hosts = {h.strip().lower() for h in allowed_hosts or set() if h.strip()}
77
+
78
+ async def __call__(self, scope, receive, send):
79
+ if scope["type"] != "http":
80
+ return await self.app(scope, receive, send)
81
+
82
+ headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope["headers"]}
83
+ method = scope["method"].upper()
84
+ path = scope["path"]
85
+ # The names this request was addressed to: Host, and behind a reverse
86
+ # proxy the original one it forwards. (A web page can't set
87
+ # X-Forwarded-Host on a cross-site request, so trusting it is safe.)
88
+ hosts = [h for h in (headers.get("host", ""), _first(headers.get("x-forwarded-host", ""))) if h]
89
+
90
+ if self.allowed_hosts and not any(_host_only(h) in self.allowed_hosts for h in hosts):
91
+ return await _reject(send, 421, "This server doesn't answer to that host name.")
92
+
93
+ if method not in SAFE_METHODS:
94
+ site = headers.get("sec-fetch-site")
95
+ if site is not None:
96
+ if site not in ("same-origin", "none"):
97
+ return await _reject(send, 403, "Cross-site request blocked.")
98
+ else:
99
+ origin = headers.get("origin")
100
+ if origin is not None:
101
+ # "null" comes from sandboxed frames and cross-site redirects: never ours.
102
+ netloc = urlsplit(origin).netloc.lower() if origin != "null" else None
103
+ if netloc not in {h.lower() for h in hosts}:
104
+ return await _reject(send, 403, "Cross-site request blocked.")
105
+
106
+ limit = BODY_LIMITS.get(path, DEFAULT_LIMIT)
107
+ length = headers.get("content-length")
108
+ if length is None:
109
+ if "chunked" in headers.get("transfer-encoding", "").lower():
110
+ return await _reject(send, 411, "Send a Content-Length header.")
111
+ else:
112
+ try:
113
+ if int(length) > limit:
114
+ return await _reject(send, 413, f"Request too large (max {limit // MB or 1} MB).")
115
+ except ValueError:
116
+ return await _reject(send, 400, "Invalid Content-Length.")
117
+
118
+ async def send_with_headers(message):
119
+ if message["type"] == "http.response.start":
120
+ extra = list(SECURITY_HEADERS)
121
+ if path.startswith("/static/") and path.endswith((".js", ".css")):
122
+ # Always check with the server (a tiny 304 when unchanged), so an update is
123
+ # picked up on the next load instead of whenever the browser feels like it.
124
+ extra.append((b"cache-control", b"no-cache"))
125
+ if not path.startswith(NO_CSP_PATHS):
126
+ extra.append((b"content-security-policy", CSP.encode()))
127
+ existing = {k.lower() for k, _ in message.get("headers", [])}
128
+ message = {**message, "headers": [*message.get("headers", []),
129
+ *[(k, v) for k, v in extra if k not in existing]]}
130
+ await send(message)
131
+
132
+ await self.app(scope, receive, send_with_headers)
133
+
134
+
135
+ # Already compressed (images, fonts) or must stay byte-exact for seeking (audio): never gzipped.
136
+ NO_GZIP_PATHS = ("/api/stream", "/api/art", "/api/account/avatar", "/api/musicbrainz/cover")
137
+ GZIP_STATIC = (".js", ".css", ".svg", ".html", ".json", ".txt", ".webmanifest")
138
+
139
+
140
+ def gzip_worthy(path: str) -> bool:
141
+ """Text Codetta sends (the page, its script and styles, API answers) shrinks to a
142
+ quarter with gzip, which matters on a phone; media doesn't shrink at all."""
143
+ if path == "/":
144
+ return True
145
+ if path.startswith("/static/"):
146
+ return path.lower().endswith(GZIP_STATIC)
147
+ return path.startswith("/api/") and not path.startswith(NO_GZIP_PATHS)
148
+
149
+
150
+ class SelectiveGZip:
151
+ """Starlette's GZipMiddleware, only for responses that are worth it."""
152
+
153
+ def __init__(self, app, minimum_size: int = 1400) -> None:
154
+ from starlette.middleware.gzip import GZipMiddleware
155
+ self.app = app
156
+ self.gzip = GZipMiddleware(app, minimum_size=minimum_size, compresslevel=6)
157
+
158
+ async def __call__(self, scope, receive, send):
159
+ if scope["type"] == "http" and gzip_worthy(scope["path"]):
160
+ return await self.gzip(scope, receive, send)
161
+ return await self.app(scope, receive, send)
162
+
163
+
164
+ async def _reject(send, status: int, detail: str) -> None:
165
+ body = json.dumps({"detail": detail}).encode()
166
+ await send({"type": "http.response.start", "status": status, "headers": [
167
+ (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode()),
168
+ *SECURITY_HEADERS,
169
+ ]})
170
+ await send({"type": "http.response.body", "body": body})