flask-deck 0.3.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. flask_deck/__init__.py +184 -0
  2. flask_deck/adapters/__init__.py +23 -0
  3. flask_deck/adapters/sqlalchemy.py +272 -0
  4. flask_deck/audit.py +363 -0
  5. flask_deck/auth.py +462 -0
  6. flask_deck/branding.py +217 -0
  7. flask_deck/charts.py +514 -0
  8. flask_deck/cli.py +135 -0
  9. flask_deck/config.py +81 -0
  10. flask_deck/dashboard.py +416 -0
  11. flask_deck/deck.py +4153 -0
  12. flask_deck/demo.py +1066 -0
  13. flask_deck/events.py +309 -0
  14. flask_deck/exceptions.py +34 -0
  15. flask_deck/exporter.py +240 -0
  16. flask_deck/formatters.py +386 -0
  17. flask_deck/i18n.py +399 -0
  18. flask_deck/icons.py +92 -0
  19. flask_deck/importer.py +612 -0
  20. flask_deck/introspection.py +376 -0
  21. flask_deck/jobs.py +382 -0
  22. flask_deck/mfa.py +670 -0
  23. flask_deck/model_view.py +1097 -0
  24. flask_deck/py.typed +0 -0
  25. flask_deck/query.py +1220 -0
  26. flask_deck/schema_graph.py +137 -0
  27. flask_deck/security.py +373 -0
  28. flask_deck/sql_console.py +391 -0
  29. flask_deck/sso.py +293 -0
  30. flask_deck/static/css/deck.css +1333 -0
  31. flask_deck/static/js/deck.js +1433 -0
  32. flask_deck/storage.py +669 -0
  33. flask_deck/templates/flask_deck/audit_list.html +117 -0
  34. flask_deck/templates/flask_deck/base.html +454 -0
  35. flask_deck/templates/flask_deck/custom_page.html +12 -0
  36. flask_deck/templates/flask_deck/dashboard.html +32 -0
  37. flask_deck/templates/flask_deck/diagnostics.html +80 -0
  38. flask_deck/templates/flask_deck/error.html +15 -0
  39. flask_deck/templates/flask_deck/import_wizard.html +143 -0
  40. flask_deck/templates/flask_deck/jobs_list.html +95 -0
  41. flask_deck/templates/flask_deck/login.html +93 -0
  42. flask_deck/templates/flask_deck/login_mfa.html +59 -0
  43. flask_deck/templates/flask_deck/mfa_setup.html +121 -0
  44. flask_deck/templates/flask_deck/model_detail.html +124 -0
  45. flask_deck/templates/flask_deck/model_form.html +389 -0
  46. flask_deck/templates/flask_deck/model_list.html +489 -0
  47. flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
  48. flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
  49. flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
  50. flask_deck/templates/flask_deck/record_history.html +102 -0
  51. flask_deck/templates/flask_deck/schema_inspector.html +83 -0
  52. flask_deck/templates/flask_deck/sql_console.html +87 -0
  53. flask_deck-0.3.0.dist-info/METADATA +382 -0
  54. flask_deck-0.3.0.dist-info/RECORD +57 -0
  55. flask_deck-0.3.0.dist-info/WHEEL +4 -0
  56. flask_deck-0.3.0.dist-info/entry_points.txt +5 -0
  57. flask_deck-0.3.0.dist-info/licenses/LICENSE +21 -0
flask_deck/auth.py ADDED
@@ -0,0 +1,462 @@
1
+ from __future__ import annotations
2
+
3
+ import fnmatch
4
+ import time
5
+ from abc import ABC, abstractmethod
6
+ from collections.abc import Callable, Mapping, Sequence
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ from flask import session
11
+ from werkzeug.security import generate_password_hash
12
+
13
+ from flask_deck.security import (
14
+ DEFAULT_PASSWORD_HASH_METHOD,
15
+ mask_value,
16
+ rotate_csrf_token,
17
+ verify_password_constant_time,
18
+ )
19
+
20
+ AUTH_USER_KEY = "_deck_auth_user_id"
21
+ AUTH_IAT_KEY = "_deck_auth_iat"
22
+ AUTH_LAST_KEY = "_deck_auth_last"
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class DeckUser:
27
+ """Authenticated principal inside Flask-Deck."""
28
+
29
+ id: str
30
+ username: str
31
+ display_name: str = ""
32
+ email: str = ""
33
+ roles: tuple[str, ...] = ("viewer",)
34
+ is_superuser: bool = False
35
+ tenant_id: Any = None
36
+ metadata: Mapping[str, Any] = field(default_factory=dict)
37
+
38
+ @property
39
+ def label(self) -> str:
40
+ return self.display_name or self.username or self.id
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class Role:
45
+ """Declarative RBAC role definition covering model, action, and field rules."""
46
+
47
+ name: str
48
+ label: str = ""
49
+ description: str = ""
50
+ permissions: frozenset[str] = field(default_factory=frozenset)
51
+ hidden_fields: Mapping[str, frozenset[str]] = field(default_factory=dict)
52
+ readonly_fields: Mapping[str, frozenset[str]] = field(default_factory=dict)
53
+ masked_fields: Mapping[str, frozenset[str]] = field(default_factory=dict)
54
+
55
+ @property
56
+ def display_label(self) -> str:
57
+ return self.label or self.name.replace("_", " ").title()
58
+
59
+ def grants(self, permission: str) -> bool:
60
+ for pattern in self.permissions:
61
+ if pattern == "*" or pattern == permission or fnmatch.fnmatchcase(permission, pattern):
62
+ return True
63
+ return False
64
+
65
+
66
+ @dataclass(frozen=True, slots=True)
67
+ class RBACAccount:
68
+ """Built-in credential record for RBACAuthProvider."""
69
+
70
+ user: DeckUser
71
+ password_hash: str
72
+
73
+
74
+ class AuthProvider(ABC):
75
+ """Pluggable authentication & 4-level RBAC provider contract."""
76
+
77
+ supports_login_form: bool = False
78
+
79
+ @abstractmethod
80
+ def get_current_user(
81
+ self,
82
+ *,
83
+ idle_timeout: int = 1800,
84
+ absolute_timeout: int = 43200,
85
+ ) -> DeckUser | None:
86
+ """Return the currently authenticated DeckUser, or None if unauthenticated."""
87
+
88
+ def authenticate(self, username: str, password: str) -> DeckUser | None:
89
+ """Verify credentials for built-in login form; return DeckUser or None."""
90
+ return None
91
+
92
+ def login_user(self, user: DeckUser) -> None:
93
+ """Rotate session safely to prevent session fixation and store auth timestamps."""
94
+ now = int(time.time())
95
+ session.clear()
96
+ session[AUTH_USER_KEY] = user.id
97
+ session[AUTH_IAT_KEY] = now
98
+ session[AUTH_LAST_KEY] = now
99
+ rotate_csrf_token()
100
+
101
+ def logout_user(self) -> None:
102
+ """Clear session completely on logout."""
103
+ session.clear()
104
+ rotate_csrf_token()
105
+
106
+ def _validate_session_timestamps(
107
+ self,
108
+ *,
109
+ idle_timeout: int,
110
+ absolute_timeout: int,
111
+ ) -> str | None:
112
+ user_id = session.get(AUTH_USER_KEY)
113
+ if not isinstance(user_id, str) or not user_id:
114
+ return None
115
+ now = int(time.time())
116
+ iat = session.get(AUTH_IAT_KEY)
117
+ last = session.get(AUTH_LAST_KEY)
118
+ if not isinstance(iat, int) or not isinstance(last, int):
119
+ session.clear()
120
+ return None
121
+ if absolute_timeout > 0 and (now - iat) > absolute_timeout:
122
+ session.clear()
123
+ return None
124
+ if idle_timeout > 0 and (now - last) > idle_timeout:
125
+ session.clear()
126
+ return None
127
+ session[AUTH_LAST_KEY] = now
128
+ return user_id
129
+
130
+ def has_permission(
131
+ self,
132
+ user: DeckUser | None,
133
+ permission: str,
134
+ *,
135
+ model_slug: str | None = None,
136
+ obj: Any = None,
137
+ ) -> bool:
138
+ """Deny-by-default permission check."""
139
+ if user is None:
140
+ return False
141
+ return user.is_superuser
142
+
143
+ def hidden_fields_for(self, user: DeckUser | None, model_slug: str) -> frozenset[str]:
144
+ """Return field names completely hidden from user on model_slug."""
145
+ return frozenset()
146
+
147
+ def readonly_fields_for(self, user: DeckUser | None, model_slug: str) -> frozenset[str]:
148
+ """Return field names user may see but never modify on model_slug."""
149
+ return frozenset()
150
+
151
+ def masked_fields_for(self, user: DeckUser | None, model_slug: str) -> frozenset[str]:
152
+ """Return field names whose values should be masked for user on model_slug."""
153
+ return frozenset()
154
+
155
+ def mask_field_value(
156
+ self,
157
+ user: DeckUser | None,
158
+ model_slug: str,
159
+ field_name: str,
160
+ value: Any,
161
+ ) -> Any:
162
+ if field_name in self.masked_fields_for(user, model_slug):
163
+ return mask_value(value)
164
+ return value
165
+
166
+ def get_roles(self) -> Sequence[Role]:
167
+ """Return declared roles for rendering the /_rbac matrix."""
168
+ return ()
169
+
170
+ def get_user_by_id(self, user_id: str) -> DeckUser | None:
171
+ """Resolve a DeckUser by user_id when supported by the provider."""
172
+ _ = user_id
173
+ return None
174
+
175
+
176
+ class OpenAuthProvider(AuthProvider):
177
+ """Explicit opt-in open access provider for local development and tests only."""
178
+
179
+ supports_login_form = False
180
+
181
+ def __init__(self, user: DeckUser | None = None) -> None:
182
+ self._user = user or DeckUser(
183
+ id="local-dev",
184
+ username="developer",
185
+ display_name="Local Developer",
186
+ roles=("admin",),
187
+ is_superuser=True,
188
+ )
189
+
190
+ def get_current_user(
191
+ self,
192
+ *,
193
+ idle_timeout: int = 1800,
194
+ absolute_timeout: int = 43200,
195
+ ) -> DeckUser | None:
196
+ return self._user
197
+
198
+ def has_permission(
199
+ self,
200
+ user: DeckUser | None,
201
+ permission: str,
202
+ *,
203
+ model_slug: str | None = None,
204
+ obj: Any = None,
205
+ ) -> bool:
206
+ return user is not None
207
+
208
+
209
+ class BasicAuthProvider(AuthProvider):
210
+ """Password-hash authenticated provider with built-in login form."""
211
+
212
+ supports_login_form = True
213
+
214
+ def __init__(self, password_hashes: Mapping[str, str]) -> None:
215
+ self._hashes = dict(password_hashes)
216
+ self._users = {
217
+ username: DeckUser(
218
+ id=username,
219
+ username=username,
220
+ display_name=username,
221
+ roles=("admin",),
222
+ is_superuser=True,
223
+ )
224
+ for username in password_hashes
225
+ }
226
+
227
+ @classmethod
228
+ def from_plain_passwords(cls, credentials: Mapping[str, str]) -> BasicAuthProvider:
229
+ """Helper for demos/tests that hashes plaintext passwords using pbkdf2:sha256."""
230
+ return cls(
231
+ {
232
+ username: generate_password_hash(password, method=DEFAULT_PASSWORD_HASH_METHOD)
233
+ for username, password in credentials.items()
234
+ }
235
+ )
236
+
237
+ def authenticate(self, username: str, password: str) -> DeckUser | None:
238
+ stored_hash = self._hashes.get(username)
239
+ if verify_password_constant_time(stored_hash, password):
240
+ return self._users.get(username)
241
+ return None
242
+
243
+ def get_current_user(
244
+ self,
245
+ *,
246
+ idle_timeout: int = 1800,
247
+ absolute_timeout: int = 43200,
248
+ ) -> DeckUser | None:
249
+ user_id = self._validate_session_timestamps(
250
+ idle_timeout=idle_timeout,
251
+ absolute_timeout=absolute_timeout,
252
+ )
253
+ if user_id is None:
254
+ return None
255
+ return self._users.get(user_id)
256
+
257
+ def get_user_by_id(self, user_id: str) -> DeckUser | None:
258
+ return self._users.get(user_id)
259
+
260
+ def has_permission(
261
+ self,
262
+ user: DeckUser | None,
263
+ permission: str,
264
+ *,
265
+ model_slug: str | None = None,
266
+ obj: Any = None,
267
+ ) -> bool:
268
+ return user is not None and user.is_superuser
269
+
270
+
271
+ class RBACAuthProvider(AuthProvider):
272
+ """Full 4-level RBAC provider with built-in login or external user loader."""
273
+
274
+ def __init__(
275
+ self,
276
+ *,
277
+ roles: Sequence[Role],
278
+ accounts: Sequence[RBACAccount] = (),
279
+ user_loader: Callable[[], DeckUser | None] | None = None,
280
+ ) -> None:
281
+ self._roles: dict[str, Role] = {r.name: r for r in roles}
282
+ self._accounts_by_username: dict[str, RBACAccount] = {
283
+ acc.user.username.lower(): acc for acc in accounts
284
+ }
285
+ self._accounts_by_id: dict[str, RBACAccount] = {acc.user.id: acc for acc in accounts}
286
+ self._user_loader = user_loader
287
+ self.supports_login_form = bool(accounts)
288
+
289
+ @classmethod
290
+ def make_account(
291
+ cls,
292
+ *,
293
+ user: DeckUser,
294
+ password: str | None = None,
295
+ password_hash: str | None = None,
296
+ ) -> RBACAccount:
297
+ if password_hash is None:
298
+ if password is None:
299
+ raise ValueError("Provide either password or password_hash")
300
+ password_hash = generate_password_hash(password, method=DEFAULT_PASSWORD_HASH_METHOD)
301
+ return RBACAccount(user=user, password_hash=password_hash)
302
+
303
+ def authenticate(self, username: str, password: str) -> DeckUser | None:
304
+ account = self._accounts_by_username.get(username.strip().lower())
305
+ stored_hash = account.password_hash if account is not None else None
306
+ if verify_password_constant_time(stored_hash, password) and account is not None:
307
+ return account.user
308
+ return None
309
+
310
+ def get_current_user(
311
+ self,
312
+ *,
313
+ idle_timeout: int = 1800,
314
+ absolute_timeout: int = 43200,
315
+ ) -> DeckUser | None:
316
+ if self._user_loader is not None:
317
+ return self._user_loader()
318
+ user_id = self._validate_session_timestamps(
319
+ idle_timeout=idle_timeout,
320
+ absolute_timeout=absolute_timeout,
321
+ )
322
+ if user_id is None:
323
+ return None
324
+ account = self._accounts_by_id.get(user_id)
325
+ return account.user if account is not None else None
326
+
327
+ def _user_roles(self, user: DeckUser | None) -> list[Role]:
328
+ if user is None:
329
+ return []
330
+ return [self._roles[name] for name in user.roles if name in self._roles]
331
+
332
+ def has_permission(
333
+ self,
334
+ user: DeckUser | None,
335
+ permission: str,
336
+ *,
337
+ model_slug: str | None = None,
338
+ obj: Any = None,
339
+ ) -> bool:
340
+ if user is None:
341
+ return False
342
+ if user.is_superuser:
343
+ return True
344
+ return any(role.grants(permission) for role in self._user_roles(user))
345
+
346
+ def _collect_field_rule(
347
+ self,
348
+ user: DeckUser | None,
349
+ model_slug: str,
350
+ attr: str,
351
+ ) -> frozenset[str]:
352
+ if user is None or user.is_superuser:
353
+ return frozenset()
354
+ roles = self._user_roles(user)
355
+ if not roles:
356
+ return frozenset()
357
+ # Filter to roles that actually grant the relevant access on model_slug so an unrelated
358
+ # role (e.g. audit-only) never intersects empty restrictions and wipes out field guards.
359
+ if attr == "readonly_fields":
360
+ relevant = [
361
+ r
362
+ for r in roles
363
+ if r.grants(f"{model_slug}:edit") or r.grants(f"{model_slug}:create")
364
+ ]
365
+ else:
366
+ relevant = [r for r in roles if r.grants(f"{model_slug}:view")]
367
+ target_roles = relevant or roles
368
+ sets: list[frozenset[str]] = []
369
+ for role in target_roles:
370
+ mapping: Mapping[str, frozenset[str]] = getattr(role, attr)
371
+ restricted = set(mapping.get("*", frozenset())) | set(
372
+ mapping.get(model_slug, frozenset())
373
+ )
374
+ sets.append(frozenset(restricted))
375
+ if not sets:
376
+ return frozenset()
377
+ result = set(sets[0])
378
+ for s in sets[1:]:
379
+ result &= s
380
+ return frozenset(result)
381
+
382
+ def hidden_fields_for(self, user: DeckUser | None, model_slug: str) -> frozenset[str]:
383
+ return self._collect_field_rule(user, model_slug, "hidden_fields")
384
+
385
+ def readonly_fields_for(self, user: DeckUser | None, model_slug: str) -> frozenset[str]:
386
+ return self._collect_field_rule(user, model_slug, "readonly_fields")
387
+
388
+ def masked_fields_for(self, user: DeckUser | None, model_slug: str) -> frozenset[str]:
389
+ return self._collect_field_rule(user, model_slug, "masked_fields")
390
+
391
+ def get_roles(self) -> Sequence[Role]:
392
+ return tuple(self._roles.values())
393
+
394
+ def get_demo_accounts(self) -> Sequence[DeckUser]:
395
+ """Return configured accounts for opt-in non-production demo role switching."""
396
+ return tuple(acc.user for acc in self._accounts_by_id.values())
397
+
398
+ def get_account_by_id(self, user_id: str) -> DeckUser | None:
399
+ acc = self._accounts_by_id.get(user_id)
400
+ return acc.user if acc is not None else None
401
+
402
+ def get_user_by_id(self, user_id: str) -> DeckUser | None:
403
+ return self.get_account_by_id(user_id)
404
+
405
+
406
+ class FlaskLoginAuthProvider(RBACAuthProvider):
407
+ """Bridge Flask-Login's ``current_user`` into Flask-Deck RBAC."""
408
+
409
+ def __init__(
410
+ self,
411
+ *,
412
+ roles: Sequence[Role] = (),
413
+ role_getter: Callable[[Any], Sequence[str]] | None = None,
414
+ superuser_getter: Callable[[Any], bool] | None = None,
415
+ tenant_getter: Callable[[Any], Any] | None = None,
416
+ ) -> None:
417
+ self._role_getter = role_getter
418
+ self._superuser_getter = superuser_getter
419
+ self._tenant_getter = tenant_getter
420
+ super().__init__(roles=roles, user_loader=self._load_from_flask_login)
421
+
422
+ def _load_from_flask_login(self) -> DeckUser | None:
423
+ try:
424
+ from flask_login import current_user
425
+ except ImportError as exc: # pragma: no cover
426
+ raise RuntimeError(
427
+ "flask-login must be installed to use FlaskLoginAuthProvider"
428
+ ) from exc
429
+
430
+ if current_user is None or not getattr(current_user, "is_authenticated", False):
431
+ return None
432
+
433
+ uid = str(getattr(current_user, "id", getattr(current_user, "get_id", lambda: "")()))
434
+ username = str(
435
+ getattr(current_user, "username", getattr(current_user, "email", uid))
436
+ )
437
+ display_name = str(getattr(current_user, "name", getattr(current_user, "full_name", username)))
438
+ email = str(getattr(current_user, "email", ""))
439
+
440
+ if self._role_getter is not None:
441
+ roles = tuple(self._role_getter(current_user))
442
+ else:
443
+ raw_roles = getattr(current_user, "roles", getattr(current_user, "role", ()))
444
+ roles = (raw_roles,) if isinstance(raw_roles, str) else tuple(str(r) for r in raw_roles)
445
+
446
+ if self._superuser_getter is not None:
447
+ is_super = bool(self._superuser_getter(current_user))
448
+ else:
449
+ is_super = bool(
450
+ getattr(current_user, "is_superuser", getattr(current_user, "is_admin", False))
451
+ )
452
+
453
+ tenant_id = self._tenant_getter(current_user) if self._tenant_getter else None
454
+ return DeckUser(
455
+ id=uid,
456
+ username=username,
457
+ display_name=display_name,
458
+ email=email,
459
+ roles=roles,
460
+ is_superuser=is_super,
461
+ tenant_id=tenant_id,
462
+ )
flask_deck/branding.py ADDED
@@ -0,0 +1,217 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import re
5
+ from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ from markupsafe import Markup, escape
10
+
11
+ from flask_deck.security import is_safe_display_url
12
+
13
+ _HEX_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
14
+
15
+ # Precision anti-AI-slop accent presets: preset_name -> (dark_accent, light_accent)
16
+ ACCENT_PRESETS: dict[str, tuple[str, str]] = {
17
+ "monochrome": ("#fafafa", "#18181b"),
18
+ "cobalt": ("#3b82f6", "#2563eb"),
19
+ "emerald": ("#10b981", "#059669"),
20
+ "amber": ("#f59e0b", "#d97706"),
21
+ "crimson": ("#ef4444", "#dc2626"),
22
+ "slate": ("#94a3b8", "#334155"),
23
+ }
24
+
25
+ VALID_TEMPLATE_SLOTS: frozenset[str] = frozenset(
26
+ {
27
+ "head_extra",
28
+ "topbar_right",
29
+ "rail_top",
30
+ "rail_bottom",
31
+ "dashboard_top",
32
+ "list_above_table",
33
+ "login_footer",
34
+ }
35
+ )
36
+
37
+
38
+ def _validate_hex(value: str, *, field_name: str) -> str:
39
+ clean = value.strip()
40
+ if not _HEX_COLOR_RE.fullmatch(clean):
41
+ raise ValueError(
42
+ f"BrandConfig.{field_name} must be a valid 6-digit hex color (#RRGGBB), got {value!r}"
43
+ )
44
+ return clean.lower()
45
+
46
+
47
+ def _validate_relative_asset(path: str, *, field_name: str) -> str:
48
+ if (
49
+ not isinstance(path, str)
50
+ or "\\" in path
51
+ or any(ord(ch) < 32 or ord(ch) == 127 for ch in path)
52
+ ):
53
+ raise ValueError(
54
+ f"BrandConfig.{field_name} entries must be relative same-origin paths starting with '/': {path!r}"
55
+ )
56
+ clean = path.strip()
57
+ if not clean or not clean.startswith("/") or clean.startswith("//"):
58
+ raise ValueError(
59
+ f"BrandConfig.{field_name} entries must be relative same-origin paths starting with '/': {path!r}"
60
+ )
61
+ return clean
62
+
63
+
64
+ def _hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
65
+ return (
66
+ int(hex_color[1:3], 16),
67
+ int(hex_color[3:5], 16),
68
+ int(hex_color[5:7], 16),
69
+ )
70
+
71
+
72
+ def _relative_luminance(hex_color: str) -> float:
73
+ r, g, b = _hex_to_rgb(hex_color)
74
+ channels = []
75
+ for c in (r, g, b):
76
+ s = c / 255.0
77
+ channels.append(s / 12.92 if s <= 0.03928 else ((s + 0.055) / 1.055) ** 2.4)
78
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]
79
+
80
+
81
+ def _contrast_fg(hex_color: str) -> str:
82
+ """Choose WCAG high-contrast foreground (#09090b or #fafafa) for a button background."""
83
+ return "#09090b" if _relative_luminance(hex_color) > 0.42 else "#fafafa"
84
+
85
+
86
+ def _shift_hex(hex_color: str, factor: float) -> str:
87
+ """Darken (factor < 1) or lighten (factor > 1) a hex color cleanly."""
88
+ r, g, b = _hex_to_rgb(hex_color)
89
+ if factor < 1.0:
90
+ nr, ng, nb = int(r * factor), int(g * factor), int(b * factor)
91
+ else:
92
+ delta = factor - 1.0
93
+ nr = int(r + (255 - r) * delta)
94
+ ng = int(g + (255 - g) * delta)
95
+ nb = int(b + (255 - b) * delta)
96
+ return f"#{max(0, min(255, nr)):02x}{max(0, min(255, ng)):02x}{max(0, min(255, nb)):02x}"
97
+
98
+
99
+ SlotRenderer = str | Callable[[Mapping[str, Any]], Markup | str]
100
+
101
+
102
+ @dataclass(frozen=True, slots=True)
103
+ class BrandConfig:
104
+ """Strict-CSP white-label branding & safe template slot configuration."""
105
+
106
+ accent: str = "monochrome"
107
+ accent_light: str | None = None
108
+ logo_url: str | None = None
109
+ logo_dark_url: str | None = None
110
+ logo_mark: str | None = None
111
+ favicon_url: str | None = None
112
+ login_title: str | None = None
113
+ login_subtitle: str | None = None
114
+ login_notice: str | None = None
115
+ footer_note: str | None = None
116
+ extra_css: tuple[str, ...] = ()
117
+ extra_js: tuple[str, ...] = ()
118
+ template_slots: Mapping[str, SlotRenderer] = field(default_factory=dict)
119
+
120
+ def __post_init__(self) -> None:
121
+ acc_lower = self.accent.strip().lower()
122
+ if acc_lower not in ACCENT_PRESETS:
123
+ _validate_hex(self.accent, field_name="accent")
124
+ if self.accent_light is not None:
125
+ _validate_hex(self.accent_light, field_name="accent_light")
126
+ for attr in ("logo_url", "logo_dark_url", "favicon_url"):
127
+ val = getattr(self, attr)
128
+ if val is not None:
129
+ if not is_safe_display_url(val):
130
+ raise ValueError(f"BrandConfig.{attr} must be a safe relative or http(s) URL")
131
+ object.__setattr__(self, attr, val.strip())
132
+ clean_css = tuple(
133
+ _validate_relative_asset(css_path, field_name="extra_css")
134
+ for css_path in self.extra_css
135
+ )
136
+ clean_js = tuple(
137
+ _validate_relative_asset(js_path, field_name="extra_js")
138
+ for js_path in self.extra_js
139
+ )
140
+ object.__setattr__(self, "extra_css", clean_css)
141
+ object.__setattr__(self, "extra_js", clean_js)
142
+ unknown_slots = set(self.template_slots.keys()) - VALID_TEMPLATE_SLOTS
143
+ if unknown_slots:
144
+ raise ValueError(
145
+ f"Unknown BrandConfig.template_slots: {sorted(unknown_slots)}. "
146
+ f"Allowed: {sorted(VALID_TEMPLATE_SLOTS)}"
147
+ )
148
+
149
+ @property
150
+ def has_custom_theme(self) -> bool:
151
+ return self.accent.strip().lower() != "monochrome" or self.accent_light is not None
152
+
153
+ def resolved_accents(self) -> tuple[str, str]:
154
+ """Return (dark_hex, light_hex) accent colors."""
155
+ key = self.accent.strip().lower()
156
+ if key in ACCENT_PRESETS:
157
+ dark_hex, light_hex = ACCENT_PRESETS[key]
158
+ else:
159
+ dark_hex = _validate_hex(self.accent, field_name="accent")
160
+ light_hex = dark_hex
161
+ if self.accent_light is not None:
162
+ light_hex = _validate_hex(self.accent_light, field_name="accent_light")
163
+ return dark_hex, light_hex
164
+
165
+
166
+ def render_brand_css(brand: BrandConfig) -> tuple[bytes, str]:
167
+ """Generate strict-CSP external /_theme.css bytes and SHA-256 cache-busting hash."""
168
+ if not brand.has_custom_theme:
169
+ empty = b"/* flask-deck default monochrome tokens */\n"
170
+ return empty, hashlib.sha256(empty).hexdigest()[:10]
171
+
172
+ dark_hex, light_hex = brand.resolved_accents()
173
+ dark_fg = _contrast_fg(dark_hex)
174
+ light_fg = _contrast_fg(light_hex)
175
+ dark_hover = _shift_hex(dark_hex, 0.88 if _relative_luminance(dark_hex) > 0.35 else 1.15)
176
+ light_hover = _shift_hex(light_hex, 0.86)
177
+ dr, dg, db = _hex_to_rgb(dark_hex)
178
+ lr, lg, lb = _hex_to_rgb(light_hex)
179
+
180
+ css = (
181
+ ":root,[data-theme=\"dark\"]{"
182
+ f"--btn-bg:{dark_hex};"
183
+ f"--btn-fg:{dark_fg};"
184
+ f"--btn-hover:{dark_hover};"
185
+ f"--chart-stroke:{dark_hex};"
186
+ f"--chart-fill:rgba({dr},{dg},{db},0.10);"
187
+ f"--accent-soft:rgba({dr},{dg},{db},0.14);"
188
+ "}\n"
189
+ "[data-theme=\"light\"]{"
190
+ f"--btn-bg:{light_hex};"
191
+ f"--btn-fg:{light_fg};"
192
+ f"--btn-hover:{light_hover};"
193
+ f"--chart-stroke:{light_hex};"
194
+ f"--chart-fill:rgba({lr},{lg},{lb},0.09);"
195
+ f"--accent-soft:rgba({lr},{lg},{lb},0.12);"
196
+ "}\n"
197
+ ).encode()
198
+ return css, hashlib.sha256(css).hexdigest()[:10]
199
+
200
+
201
+ def render_safe_slot(
202
+ brand: BrandConfig,
203
+ slot_name: str,
204
+ context: Mapping[str, Any],
205
+ *,
206
+ template_renderer: Callable[..., str],
207
+ ) -> Markup:
208
+ """Safely render a configured brand template slot without unescaped string injection."""
209
+ if slot_name not in VALID_TEMPLATE_SLOTS:
210
+ return Markup("")
211
+ handler = brand.template_slots.get(slot_name)
212
+ if handler is None:
213
+ return Markup("")
214
+ if isinstance(handler, str):
215
+ return Markup(template_renderer(handler, **context))
216
+ out = handler(context)
217
+ return out if isinstance(out, Markup) else Markup(escape(str(out)))