flask-deck 0.3.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 (101) hide show
  1. flask_deck-0.3.0/.gitignore +18 -0
  2. flask_deck-0.3.0/CHANGELOG.md +84 -0
  3. flask_deck-0.3.0/LICENSE +21 -0
  4. flask_deck-0.3.0/PKG-INFO +382 -0
  5. flask_deck-0.3.0/README.md +329 -0
  6. flask_deck-0.3.0/benchmarks/bench_deck.py +208 -0
  7. flask_deck-0.3.0/docs/assets/audit-dark.png +0 -0
  8. flask_deck-0.3.0/docs/assets/banner.svg +56 -0
  9. flask_deck-0.3.0/docs/assets/cmdk-dark.png +0 -0
  10. flask_deck-0.3.0/docs/assets/dashboard-dark.png +0 -0
  11. flask_deck-0.3.0/docs/assets/dashboard-light.png +0 -0
  12. flask_deck-0.3.0/docs/assets/form-widgets-dark.png +0 -0
  13. flask_deck-0.3.0/docs/assets/heatmap-dark.png +0 -0
  14. flask_deck-0.3.0/docs/assets/import-diff-dark.png +0 -0
  15. flask_deck-0.3.0/docs/assets/kanban-dark.png +0 -0
  16. flask_deck-0.3.0/docs/assets/orders-drawer-dark.png +0 -0
  17. flask_deck-0.3.0/docs/assets/schema-erd-dark.png +0 -0
  18. flask_deck-0.3.0/docs/assets/sla-page-dark.png +0 -0
  19. flask_deck-0.3.0/docs/assets/sql-console-dark.png +0 -0
  20. flask_deck-0.3.0/docs/assets/v03-cursor-trash-dark.png +0 -0
  21. flask_deck-0.3.0/docs/assets/v03-jobs-sse-dark.png +0 -0
  22. flask_deck-0.3.0/docs/assets/v03-mfa-qr-dark.png +0 -0
  23. flask_deck-0.3.0/docs/assets/v03-products-lightbox-dark.png +0 -0
  24. flask_deck-0.3.0/docs/assets/v03-products-media-dark.png +0 -0
  25. flask_deck-0.3.0/docs/assets/v03-revision-diff-dark.png +0 -0
  26. flask_deck-0.3.0/docs/assets/v03-rtl-arabic-dark.png +0 -0
  27. flask_deck-0.3.0/docs/assets/v03-wizard-dropzone-dark.png +0 -0
  28. flask_deck-0.3.0/docs/migration-from-flask-admin.md +71 -0
  29. flask_deck-0.3.0/examples/pure_sqlalchemy_app.py +50 -0
  30. flask_deck-0.3.0/examples/saas_demo/app.py +8 -0
  31. flask_deck-0.3.0/examples/saas_demo/sample_products_import.csv +5 -0
  32. flask_deck-0.3.0/pyproject.toml +146 -0
  33. flask_deck-0.3.0/src/flask_deck/__init__.py +184 -0
  34. flask_deck-0.3.0/src/flask_deck/adapters/__init__.py +23 -0
  35. flask_deck-0.3.0/src/flask_deck/adapters/sqlalchemy.py +272 -0
  36. flask_deck-0.3.0/src/flask_deck/audit.py +363 -0
  37. flask_deck-0.3.0/src/flask_deck/auth.py +462 -0
  38. flask_deck-0.3.0/src/flask_deck/branding.py +217 -0
  39. flask_deck-0.3.0/src/flask_deck/charts.py +514 -0
  40. flask_deck-0.3.0/src/flask_deck/cli.py +135 -0
  41. flask_deck-0.3.0/src/flask_deck/config.py +81 -0
  42. flask_deck-0.3.0/src/flask_deck/dashboard.py +416 -0
  43. flask_deck-0.3.0/src/flask_deck/deck.py +4153 -0
  44. flask_deck-0.3.0/src/flask_deck/demo.py +1066 -0
  45. flask_deck-0.3.0/src/flask_deck/events.py +309 -0
  46. flask_deck-0.3.0/src/flask_deck/exceptions.py +34 -0
  47. flask_deck-0.3.0/src/flask_deck/exporter.py +240 -0
  48. flask_deck-0.3.0/src/flask_deck/formatters.py +386 -0
  49. flask_deck-0.3.0/src/flask_deck/i18n.py +399 -0
  50. flask_deck-0.3.0/src/flask_deck/icons.py +92 -0
  51. flask_deck-0.3.0/src/flask_deck/importer.py +612 -0
  52. flask_deck-0.3.0/src/flask_deck/introspection.py +376 -0
  53. flask_deck-0.3.0/src/flask_deck/jobs.py +382 -0
  54. flask_deck-0.3.0/src/flask_deck/mfa.py +670 -0
  55. flask_deck-0.3.0/src/flask_deck/model_view.py +1097 -0
  56. flask_deck-0.3.0/src/flask_deck/py.typed +0 -0
  57. flask_deck-0.3.0/src/flask_deck/query.py +1220 -0
  58. flask_deck-0.3.0/src/flask_deck/schema_graph.py +137 -0
  59. flask_deck-0.3.0/src/flask_deck/security.py +373 -0
  60. flask_deck-0.3.0/src/flask_deck/sql_console.py +391 -0
  61. flask_deck-0.3.0/src/flask_deck/sso.py +293 -0
  62. flask_deck-0.3.0/src/flask_deck/static/css/deck.css +1333 -0
  63. flask_deck-0.3.0/src/flask_deck/static/js/deck.js +1433 -0
  64. flask_deck-0.3.0/src/flask_deck/storage.py +669 -0
  65. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/audit_list.html +117 -0
  66. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/base.html +454 -0
  67. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/custom_page.html +12 -0
  68. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/dashboard.html +32 -0
  69. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/diagnostics.html +80 -0
  70. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/error.html +15 -0
  71. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/import_wizard.html +143 -0
  72. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/jobs_list.html +95 -0
  73. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/login.html +93 -0
  74. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/login_mfa.html +59 -0
  75. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/mfa_setup.html +121 -0
  76. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/model_detail.html +124 -0
  77. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/model_form.html +389 -0
  78. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/model_list.html +489 -0
  79. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
  80. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
  81. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
  82. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/record_history.html +102 -0
  83. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/schema_inspector.html +83 -0
  84. flask_deck-0.3.0/src/flask_deck/templates/flask_deck/sql_console.html +87 -0
  85. flask_deck-0.3.0/tests/__init__.py +0 -0
  86. flask_deck-0.3.0/tests/conftest.py +356 -0
  87. flask_deck-0.3.0/tests/test_audit_and_revert.py +112 -0
  88. flask_deck-0.3.0/tests/test_auth_rbac_security.py +170 -0
  89. flask_deck-0.3.0/tests/test_bug_hunt_regressions.py +920 -0
  90. flask_deck-0.3.0/tests/test_cli_and_demo.py +78 -0
  91. flask_deck-0.3.0/tests/test_crud_and_inlines.py +181 -0
  92. flask_deck-0.3.0/tests/test_dashboard_and_charts.py +56 -0
  93. flask_deck-0.3.0/tests/test_edge_cases.py +95 -0
  94. flask_deck-0.3.0/tests/test_import_export.py +156 -0
  95. flask_deck-0.3.0/tests/test_introspection.py +73 -0
  96. flask_deck-0.3.0/tests/test_query_filters_n1.py +87 -0
  97. flask_deck-0.3.0/tests/test_security_adversarial.py +341 -0
  98. flask_deck-0.3.0/tests/test_v02_workbench.py +257 -0
  99. flask_deck-0.3.0/tests/test_v03_auth_jobs.py +369 -0
  100. flask_deck-0.3.0/tests/test_v03_media_i18n_brand.py +430 -0
  101. flask_deck-0.3.0/tests/test_v03_query_forms_lifecycle.py +472 -0
@@ -0,0 +1,18 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ .venv/
5
+ venv/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+ .coverage
13
+ htmlcov/
14
+ *.db
15
+ *.sqlite
16
+ *.sqlite3
17
+ .DS_Store
18
+ .env
@@ -0,0 +1,84 @@
1
+ # Changelog
2
+
3
+ All notable changes to `flask-deck` are documented in this file.
4
+
5
+ ## [0.3.0] - 2026-11-21
6
+
7
+ ### Added
8
+ - **Pillar 1 — First-Class Media, File Uploads & Object Storage (`storage.py`):**
9
+ - Pluggable `StorageBackend` protocol with `LocalFileStorage` (path-traversal-proof atomic writes), `S3StorageBackend` (AWS S3 / Cloudflare R2 / MinIO with lazy optional `boto3`), and `MemoryFileStorage`.
10
+ - Pure-Python magic-byte MIME validation (blocking SVG XSS by default) and PNG/JPEG/GIF/WebP header decompression-bomb protection (`max_image_pixels`) with zero Pillow dependency.
11
+ - Declarative `ModelView.file_fields` (`FileFieldConfig`) with drag-and-drop upload dropzone, instant DataURL image preview, atomic replace/delete cleanup, `ImageFormatter` + click-to-open **Image Lightbox Modal**, `FileFormatter`, and RBAC + `scope_query`-guarded `/_media/<slug>/<field>/<pk>` streaming proxy (`X-Content-Type-Options: nosniff`, `Content-Disposition: attachment`).
12
+ - **Pillar 2 — Enterprise i18n, Native RTL & Per-User Timezones (`i18n.py`):**
13
+ - `Translator` protocol with built-in zero-dependency `DictTranslator` (`en`, `tr`, `de`, `ar` RTL catalogs) and optional `BabelTranslator` (`flask-deck[babel]`).
14
+ - Native CSS Logical Properties (`margin-inline`, `padding-inline`, `inset-inline`, `border-inline`) powering seamless `dir="rtl"` right-to-left layouts without a second stylesheet.
15
+ - Stdlib `zoneinfo.ZoneInfo` UTC ↔ user-timezone conversion (`DateTimeFormatter`, locale/TZ-aware `CurrencyFormatter` & `RelativeTimeFormatter`) + interactive Topbar Locale & Timezone switcher (`/_preferences`).
16
+ - **Pillar 3 — Strict-CSP Brand Customization & Safe Extension Slots (`branding.py`):**
17
+ - `BrandConfig` supporting preset (`cobalt`, `emerald`, `amber`, `crimson`, `slate`, `monochrome`) or validated `#RRGGBB` custom accents with automatic WCAG 2.1 contrast calculation, custom `logo_url`/`logo_dark_url`/`favicon_url`, login page title/subtitle/notice, same-origin `extra_css`/`extra_js`, and 7 allowlisted `template_slots`.
18
+ - Dynamic brand variables served via external `/_theme.css` (SHA-256 cached, `style-src 'self'`) — preserving **0 `'unsafe-inline'`** and **0 `<style>` tags**.
19
+ - **Pillar 4 — Enterprise Auth: Built-In Pure-Python TOTP 2FA, OIDC/OAuth2 SSO & Audited Impersonation (`mfa.py`, `sso.py`):**
20
+ - RFC 6238 TOTP (`generate_totp_secret`, `compute_totp`, `verify_totp`) with per-user timestep replay prevention, PBKDF2 single-use recovery codes, `InMemoryMFAStore` / `SQLAlchemyMFAStore`, and a **pure-Python ISO/IEC 18004 QR Code → Strict-CSP SVG encoder** (`/_security/mfa`, `/login/mfa`).
21
+ - `OIDCAuthProvider` with PKCE `S256`, `state`/`nonce` CSRF protection, `allowed_domains`, and IdP group-to-role mapping (`/login/sso/<provider>`).
22
+ - Superuser **User Impersonation** (`/_impersonate/start` & `/stop`) with full session audit attribution (`impersonated_by`), immutable audit trail, and persistent amber topbar banner.
23
+ - **Pillar 5 — Scale-Out Query Engine & PostgreSQL Native Power (`query.py`, `adapters/sqlalchemy.py`):**
24
+ - **HMAC-SHA256 Signed Keyset Cursor Pagination** (`pagination_mode="cursor"`, `LIMIT N+1`, opaque `after`/`before` cursors) eliminating `OFFSET` scan degradation on multi-million-row tables.
25
+ - `count_mode="estimated"` (`pg_class.reltuples` O(1) count on PostgreSQL) and `count_mode="none"`.
26
+ - Multi-database / multi-bind SQLAlchemy support (`binds={"analytics": engine}`) with per-`ModelView` `bind_key`.
27
+ - Dialect-aware **PostgreSQL `JSONB` & `ARRAY` native filtering** (`?`, `->>`, `#>>`, `@>`, `&&` on Postgres; `json_type`/`json_extract` fallback on SQLite) + structured multi-operator filter rule builder (`eq`, `neq`, `contains`, `gt`, `gte`, `lt`, `lte`, `is_null`, `not_null`, `has_key`, `contains_any`).
28
+ - **Pillar 6 — Intelligent Dynamic Forms & Validation (`model_view.py`, `model_form.html`):**
29
+ - **Conditional Field Visibility (`field_conditions`)** (`data-show-when` zero-latency DOM toggling + server-side validation awareness).
30
+ - **Cascading Dependent Foreign Keys (`dependent_fields`)** filtering `/_api/fk/<slug>` choices dynamically by parent field (`dep_col`/`dep_val`).
31
+ - **Multi-Step Form Wizard (`form_layout="wizard"`)** with numbered stepper navigation, client validation per step, and automatic error-step focus.
32
+ - Native **`ARRAY` Tag-Chip Editor** (`sa.ARRAY` introspection + interactive chips) and pluggable **`form_validator` + `pydantic_validator(Schema)`** adapter (`flask-deck[pydantic]`).
33
+ - **Pillar 7 — Record Lifecycle: Soft-Delete Trash & Side-by-Side Revision Diffs (`model_view.py`, `deck.py`, `record_history.html`):**
34
+ - Declarative `soft_delete_column` with automatic active-list filtering, single-pass `CASE` Trash tab counter, `?trashed=1` Trash view, one-click **Restore** (`/<slug>/<pk>/restore`), and confirmed **Force Delete** (`force=1`).
35
+ - Per-record **Side-by-Side Revision History & Visual Diff** (`/<slug>/<pk>/history`) comparing `Before`, `After`, and `Current Live` values with one-click Safe Revert.
36
+ - **Pillar 8 — Background Jobs, Real-Time SSE Streaming & SSRF-Safe Webhooks (`jobs.py`, `events.py`, `jobs_list.html`):**
37
+ - Pluggable `JobBackend` protocol with `ThreadPoolJobBackend` (Flask `app_context` propagation, bounded log ring, cooperative cancellation, downloadable file artifacts).
38
+ - `@action(..., async_job=True)` for background bulk jobs, **Background CSV Export** (`/<slug>/export-async`), live `/_jobs` console with **Server-Sent Events (`/_api/jobs/<id>/stream`)** real-time progress bar & logs, cancel, and artifact download.
39
+ - Typed `DeckEventBus` (`@deck.on("record.updated")`) and SSRF-hardened HMAC-SHA256 `WebhookSink` blocking loopback, RFC 1918 private, link-local, and cloud metadata IPs (`169.254.169.254`, `127.0.0.1`, `::1`).
40
+
41
+ ## [0.2.0] - 2026-11-21
42
+
43
+ ### Added
44
+ - **Data Workspace Upgrades (`ModelView` & Grid):**
45
+ - **Kanban Board Mode (`?view=board`)**: Opt-in status-lane board via `kanban_column` with HTML5 drag-and-drop transitions, full CSRF + RBAC + `scope_query` + audit logging, plus Table / Board toggle pills.
46
+ - **Table Summary Footer (`column_aggregates`)**: Page-scoped `sum`, `avg`, `min`, `max`, and `count` footer totals aligned with `tabular-nums` and formatted via column formatters.
47
+ - **Saved Filter Presets (`saved_views`)**: Declarative 1-click saved view pills synchronized cleanly with URL query parameters.
48
+ - **Parameterized Bulk Actions (`ActionField`)**: `@action(..., fields=(ActionField(...),))` renders a strict-CSP modal form (`text`, `textarea`, `select`, `number`, `checkbox`) for structured bulk workflows (e.g., refund reason, stock delta) with safe `form_data` coercion.
49
+ - **Clone / Duplicate Record (`?clone=<pk>`)**: Pre-fills the Create form from an existing record while stripping PKs, unique fields, readonly/hidden/sensitive fields, and honoring `scope_query`.
50
+ - **Grid Density Switcher & Linear-Style Keyboard Shortcuts**: `Compact / Normal` density toggle (`localStorage`), `j`/`k` row cursor, `Space` row select, `Enter` Quick Peek, `c` create, `g d` dashboard, `g a` audit, `?` shortcuts cheat sheet, and hover click-to-copy on `CodeFormatter(copyable=True)`.
51
+ - **Rich Form Inputs & Layouts:**
52
+ - **Tabbed Forms & 2-Column Sections (`form_layout`)**: Clean multi-tab form navigation (auto-activates the first tab containing validation errors) and responsive 2-column section grids.
53
+ - **Zero-Dependency Custom Input Widgets (`field_widgets`)**: `SegmentedControlWidget`, `SwitchWidget`, `TagInputWidget`, `SliderWidget`, `CodeEditorWidget` (with JSON format & syntax validation), and `MarkdownPreviewWidget` (strict-CSP safe preview).
54
+ - **Dashboard & Analytics Visualization Suite (100% Pure SSR SVG, Strict CSP):**
55
+ - **`HeatmapWidget`**: 91-day GitHub-style activity calendar with 5-level intensity scale and interactive hover tooltips.
56
+ - **`StatBarWidget`**: Horizontal ranked progress breakdown bars (e.g., top products by revenue).
57
+ - **`GaugeWidget`**: Semi-circular radial SLA/utilization meter with semantic threshold coloring.
58
+ - **`ChartWidget(kind="grouped_bar")`**: Multi-series side-by-side comparison bar charts with legend.
59
+ - **`TimelineWidget`**: Chronological event feed with semantic status dots.
60
+ - **`CalloutWidget`**: Dismissible/contextual `info`, `ok`, `warn`, and `danger` operational alerts.
61
+ - **Dashboard Date Range Selector (`7d` / `30d` / `90d`)**: Passes `ctx.range_days` into dashboard builders and custom pages.
62
+ - **Built-In Operations & Developer Modules:**
63
+ - **Interactive Schema ERD (`/admin/_schema`)**: Pure SVG topological entity-relationship graph inspecting SQLAlchemy models, PK/FK keys, cardinalities, indexes, and quick links to each model grid.
64
+ - **Security & Performance Diagnostics (`/admin/_diagnostics`)**: Live browser view of the `flask deck audit` checks, session/CSP posture, SQLAlchemy engine telemetry, and unindexed `searchable_columns` warnings.
65
+ - **Hardened Read-Only SQL Console (`/admin/_sql`)**: Superuser-gated opt-in (`enable_sql_console=True`) SQL workbench with multi-layer read-only AST/regex firewall (`SELECT`/`WITH`/`EXPLAIN` only), statement blocking, auto-`LIMIT`, automatic `[REDACTED]` masking on sensitive columns, and sanitized CSV export.
66
+ - **Custom Pages SDK (`@deck.page(...)`)**: Build full custom operations pages (e.g., `/admin/_page/sla-capacity`) using the same widget grid, RBAC permission gating, sidebar navigation, and `⌘K` indexing.
67
+ - **3-Tab Quick Peek Drawer, Topbar Notification Bell & Demo Role Switcher:**
68
+ - Quick Peek Drawer upgraded with **Overview**, **Relations** (lazy preview of related child records), and **Audit** tabs.
69
+ - Topbar Activity Bell lazily loads recent audit events via `/admin/_api/notifications` without adding queries to normal page loads.
70
+ - Bottom-left `SESSION ROLE` switcher for instant 1-click RBAC switching (`Admin` / `Support` / `Viewer`) in demos — strictly forbidden when `environment == "production"`.
71
+
72
+ ## [0.1.0] - 2026-11-21
73
+
74
+ ### Added
75
+ - **SQLAlchemy 2.0 & Flask-SQLAlchemy Dual Adapter**: Full support for `DeclarativeBase` + `Mapped[]`, composite primary keys, relationships, and request-scoped session management.
76
+ - **Carbon Dark & Swiss Light Precision Workbench UI**: Zero Node build, zero CDN, `<12 KB` gzipped CSS + vanilla ES6 JS, `44px` topbar, `228px` rail, `28px` live SQL telemetry status bar.
77
+ - **Global `⌘K` Command Palette**: Instant keyboard navigation across models, quick actions, and RBAC-scoped live cross-model record search.
78
+ - **Composable Dashboard & Pure SVG Charts**: Auto-generated fallback dashboard plus `KPIWidget`, `ChartWidget` (`area`, `bar`, `donut`), `TableWidget`, `ActivityWidget`, and `MarkdownWidget` with interactive hover tooltips and zero third-party chart JS.
79
+ - **Power Data Grid**: Single-pass `CASE` Quick Filter Tabs, faceted filters, URL-synced state, column visibility persistence, Slide-Over Quick Peek Drawer, Inline Quick-Edit, and Floating Bulk Action Dock with Type-to-Confirm safeguards.
80
+ - **Smart Forms & Relations**: Tabbed fieldsets, async searchable FK combobox, M2M tag multi-select, JSON editor, and inline One-to-Many child record management with parent-ownership IDOR protection.
81
+ - **Dry-Run Savepoint Import & Streaming Export**: `SAVEPOINT` + guaranteed `ROLLBACK` CSV/JSON import preview with visual field-level diffs, single-use user/session-bound preview tokens, `O(1)`-RAM streaming export, and CSV formula-injection neutralization.
82
+ - **Fail-Closed Auth & 4-Level RBAC**: `BasicAuthProvider`, `RBACAuthProvider`, `FlaskLoginAuthProvider`, explicit opt-in `OpenAuthProvider`, sliding-window login brute-force throttler, session fixation & timeout guards, field masking/read-only/hidden rules, multi-tenant `scope_query`, and `/admin/_rbac` visual matrix.
83
+ - **Field-Level Audit Log & Safe Revert**: `SQLAlchemyAuditStore` and bounded `InMemoryAuditStore` with automatic sensitive field redaction (`[REDACTED]`), visual diff timeline, per-record history, and one-click safe revert.
84
+ - **Hardened Security Middleware**: Strict per-request nonce CSP with zero `'unsafe-inline'`, double-layer CSRF + `Sec-Fetch-Site`, `no-store` caching on admin responses, and `flask deck audit` CLI security + index checker.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Duhan Güler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,382 @@
1
+ Metadata-Version: 2.5
2
+ Name: flask-deck
3
+ Version: 0.3.0
4
+ Summary: Precision Carbon Dark & Swiss Light admin panel and operations workbench for Flask and SQLAlchemy 2.0 — zero Node build, zero CDN, fail-closed RBAC, dry-run diff import, and field-level audit logs.
5
+ Project-URL: Homepage, https://github.com/duhanguler/flask-deck
6
+ Project-URL: Repository, https://github.com/duhanguler/flask-deck
7
+ Project-URL: Documentation, https://github.com/duhanguler/flask-deck#readme
8
+ Project-URL: Issues, https://github.com/duhanguler/flask-deck/issues
9
+ Project-URL: Changelog, https://github.com/duhanguler/flask-deck/blob/main/CHANGELOG.md
10
+ Author-email: Duhan Güler <45712664+duhanguler@users.noreply.github.com>
11
+ License: MIT
12
+ License-File: LICENSE
13
+ Keywords: admin,audit-log,command-palette,crud,dashboard,django-unfold,flask,flask-admin,rbac,sqladmin,sqlalchemy,wsgi
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Environment :: Web Environment
16
+ Classifier: Framework :: Flask
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Database :: Front-Ends
26
+ Classifier: Topic :: Internet :: WWW/HTTP :: WSGI
27
+ Classifier: Topic :: Security
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.10
30
+ Requires-Dist: flask>=2.3.0
31
+ Requires-Dist: jinja2>=3.1.0
32
+ Requires-Dist: markupsafe>=2.1.0
33
+ Requires-Dist: sqlalchemy>=2.0.0
34
+ Requires-Dist: werkzeug>=2.3.0
35
+ Provides-Extra: babel
36
+ Requires-Dist: flask-babel>=4.0.0; extra == 'babel'
37
+ Provides-Extra: dev
38
+ Requires-Dist: flask-login>=0.6.3; extra == 'dev'
39
+ Requires-Dist: flask-sqlalchemy>=3.1.0; extra == 'dev'
40
+ Requires-Dist: mypy>=1.11.0; extra == 'dev'
41
+ Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
42
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
43
+ Requires-Dist: ruff>=0.6.0; extra == 'dev'
44
+ Provides-Extra: flask-login
45
+ Requires-Dist: flask-login>=0.6.3; extra == 'flask-login'
46
+ Provides-Extra: flask-sqlalchemy
47
+ Requires-Dist: flask-sqlalchemy>=3.1.0; extra == 'flask-sqlalchemy'
48
+ Provides-Extra: pydantic
49
+ Requires-Dist: pydantic>=2.0.0; extra == 'pydantic'
50
+ Provides-Extra: s3
51
+ Requires-Dist: boto3>=1.34.0; extra == 's3'
52
+ Description-Content-Type: text/markdown
53
+
54
+ <p align="center">
55
+ <img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/banner.svg" alt="flask-deck — Precision Enterprise Admin Panel and Operations Workbench for Flask and SQLAlchemy 2.0" width="100%" />
56
+ </p>
57
+
58
+ <p align="center">
59
+ <a href="https://github.com/duhanguler/flask-deck/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/duhanguler/flask-deck/ci.yml?branch=main&style=flat-square&label=CI" alt="CI" /></a>
60
+ <a href="https://pypi.org/project/flask-deck/"><img src="https://img.shields.io/pypi/v/flask-deck?style=flat-square&color=0D7A52&logo=pypi&logoColor=white" alt="PyPI" /></a>
61
+ <img src="https://img.shields.io/badge/Python-3.10%20--%203.13-18181b?style=flat-square&logo=python&logoColor=white" alt="Python 3.10-3.13" />
62
+ <img src="https://img.shields.io/badge/Flask-2.3%2B%20%7C%203.x-18181b?style=flat-square&logo=flask&logoColor=white" alt="Flask" />
63
+ <img src="https://img.shields.io/badge/SQLAlchemy-2.0%2B-18181b?style=flat-square&logo=sqlalchemy&logoColor=white" alt="SQLAlchemy 2.0+" />
64
+ <img src="https://img.shields.io/badge/Assets-23.6%20KB%20gzip-18181b?style=flat-square" alt="23.6 KB gzip" />
65
+ <img src="https://img.shields.io/badge/CSP-Strict%20Nonce-18181b?style=flat-square" alt="Strict Nonce CSP" />
66
+ <a href="https://github.com/duhanguler/flask-deck/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-18181b?style=flat-square" alt="MIT License" /></a>
67
+ </p>
68
+
69
+ # flask-deck
70
+
71
+ **A precision, fail-closed Enterprise Admin Panel & Operations Workbench for Flask and SQLAlchemy 2.0** — engineered for teams that want the visual craft of **Django-Unfold / Filament / Linear** plus enterprise security, media storage, i18n/RTL, cursor pagination, background SSE jobs, and pure-Python TOTP 2FA on WSGI — without shipping Bootstrap, jQuery, Node build pipelines, or external CDNs.
72
+
73
+ - **Zero Node Build · Zero External CDN · `23.6 KB` gzip total** (`8.83 KB` CSS + `14.76 KB` vanilla ES6 JS + inline SVGs + pure SSR SVG visualizations & QR codes). Runs out of the box in air-gapped enterprise environments.
74
+ - **Carbon Dark, Swiss Light & Strict-CSP Brand Themes**: `1px` hairline grids, `tabular-nums`, CSS Logical Properties for native **RTL**, custom `#RRGGBB` brand accents served over external `/_theme.css` (auto WCAG 2.1 contrast, **0 `'unsafe-inline'`**), and 7 allowlisted extension slots.
75
+ - **8 Enterprise Capabilities Built In (`v0.3.0`)**:
76
+ 1. **Media, File Uploads & Object Storage (`LocalFileStorage`, `S3StorageBackend` for S3/R2/MinIO)**: Pure-Python magic-byte MIME validation (SVG XSS blocked by default), PNG/JPEG/GIF/WebP decompression-bomb protection, drag-and-drop dropzone, **Image Lightbox**, and RBAC-guarded `/_media` streaming proxy.
77
+ 2. **Enterprise i18n, Native RTL & Per-User Timezones**: Built-in `en`/`tr`/`de`/`ar` catalogs (`DictTranslator`) + optional `BabelTranslator`, native `dir="rtl"` logical layout, stdlib `ZoneInfo` UTC ↔ local TZ conversion, and Topbar Globe switcher.
78
+ 3. **Built-In Pure-Python TOTP 2FA, OIDC/OAuth2 SSO & Audited Impersonation**: RFC 6238 TOTP with replay prevention, PBKDF2 recovery codes, **pure-Python ISO/IEC 18004 SVG QR generator**, PKCE `S256` OIDC SSO with group-to-role mapping, and superuser Impersonation with immutable audit attribution.
79
+ 4. **Scale-Out Query Engine & PostgreSQL Native Power**: HMAC-signed **Keyset Cursor Pagination** (`LIMIT N+1`), `pg_class.reltuples` O(1) estimated counts, multi-bind database routing (`binds={...}`), dialect-aware `JSONB`/`ARRAY` native filters (`?`, `->>`, `#>>`, `@>`, `&&`), and multi-operator filter Rule Builder.
80
+ 5. **Intelligent Dynamic Forms**: Conditional visibility (`field_conditions`), cascading dependent FK dropdowns (`dependent_fields`), **Multi-Step Form Wizards (`form_layout="wizard"`)**, native `ARRAY` tag-chip editor, and `pydantic_validator(Schema)`.
81
+ 6. **Record Lifecycle**: Declarative **Soft-Delete Trash** (`soft_delete_column`, `?trashed=1`, one-click **Restore**, confirmed **Force Delete**) and **Side-by-Side Revision Diffs** (`/<slug>/<pk>/history`) with one-click Safe Revert.
82
+ 7. **Background Jobs, Live SSE Streaming & SSRF-Safe Webhooks**: `ThreadPoolJobBackend`, `@action(..., async_job=True)`, Background CSV Export, `/_jobs` live **Server-Sent Events** progress/log streaming & downloadable artifacts, `@deck.on(...)` event bus, and HMAC-SHA256 `WebhookSink` blocking RFC 1918 / loopback / cloud metadata IPs.
83
+ 8. **Full Operations Workbench (`v0.1`–`v0.2`)**: Drag-and-Drop **Kanban Board**, Pure SVG Analytics (**91d Heatmap, Radial Gauge, Area/Donut/Grouped Bars, Stat Bars, Timeline**), **Interactive Schema ERD (`/_schema`)**, **Redacting Read-Only SQL Console (`/_sql`)**, **Security Diagnostics (`/_diagnostics`)**, **`@deck.page` Custom Pages**, **`⌘K` Command Palette**, **3-Tab Quick Peek Drawer**, and **SAVEPOINT Dry-Run CSV/JSON Import**.
84
+
85
+ ---
86
+
87
+ ### Try the Live Demo in 5 Seconds
88
+
89
+ ```bash
90
+ uvx flask-deck demo
91
+ # or
92
+ pip install flask-deck && flask-deck demo
93
+ ```
94
+
95
+ Open `http://127.0.0.1:5055/admin/` and explore:
96
+ - **Live RBAC Switching**: Bottom-left **SESSION ROLE** switcher (`Admin` / `Support` with live email PII masking / `Viewer` read-only) plus **Impersonate User**.
97
+ - **Media & 3-Step Wizard**: Click any Product thumbnail on `/admin/products/` for the Lightbox, or open **Edit** for the 3-step Wizard with image dropzone & metadata editor.
98
+ - **Cursor Pagination & Soft-Delete Trash**: Explore `/admin/tickets/` with HMAC keyset cursors and Trash / Restore tabs.
99
+ - **TOTP 2FA QR, Revision Diffs, Background SSE Jobs & Arabic RTL**: Visit `/admin/_security/mfa`, `/admin/orders/1/history`, `/admin/_jobs`, or switch to **العربية (AR)** + `Europe/Istanbul` in the topbar Globe popover.
100
+
101
+ Optional extras (zero mandatory bloat in the base wheel):
102
+
103
+ ```bash
104
+ pip install "flask-deck[s3]" # boto3 for S3 / R2 / MinIO
105
+ pip install "flask-deck[babel]" # Flask-Babel / Babel catalog integration
106
+ pip install "flask-deck[pydantic]" # Pydantic v2 form validation adapter
107
+ ```
108
+
109
+ ---
110
+
111
+ ### Carbon Dark, Swiss Light & Enterprise Workbench Gallery
112
+
113
+ <p align="center">
114
+ <picture>
115
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/dashboard-dark.png" />
116
+ <source media="(prefers-color-scheme: light)" srcset="docs/assets/dashboard-light.png" />
117
+ <img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/dashboard-dark.png" alt="flask-deck Carbon Dark & Swiss Light Dashboard Workbench" width="100%" />
118
+ </picture>
119
+ </p>
120
+
121
+ <details>
122
+ <summary>Explore All 18 Workbench &amp; Enterprise Views (Media Lightbox, 3-Step Wizard, Keyset Cursor &amp; Trash, TOTP QR, Side-by-Side Diff, Background SSE Jobs, Arabic RTL, Kanban, Heatmap, ERD, SQL Console &amp; More)</summary>
123
+ <br />
124
+ <p align="center"><strong>Products Media Grid &amp; Click-to-Open Image Lightbox (RBAC-Guarded <code>/_media</code> Proxy)</strong></p>
125
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/v03-products-lightbox-dark.png" alt="flask-deck Products Media Lightbox" width="100%" /></p>
126
+ <p align="center"><strong>Multi-Step Form Wizard with Drag-and-Drop Image Upload &amp; Live DataURL Preview</strong></p>
127
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/v03-wizard-dropzone-dark.png" alt="flask-deck 3-Step Form Wizard and Dropzone" width="100%" /></p>
128
+ <p align="center"><strong>HMAC-Signed Keyset Cursor Pagination &amp; Soft-Delete Trash / One-Click Restore</strong></p>
129
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/v03-cursor-trash-dark.png" alt="flask-deck Keyset Cursor Pagination and Trash Restore" width="100%" /></p>
130
+ <p align="center"><strong>Built-In TOTP 2FA Enrollment with Pure-Python ISO/IEC 18004 SVG QR Code (Zero External Libs)</strong></p>
131
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/v03-mfa-qr-dark.png" alt="flask-deck TOTP 2FA Setup with Pure-Python SVG QR" width="100%" /></p>
132
+ <p align="center"><strong>Per-Record Side-by-Side Revision Diff History &amp; Safe Revert (<code>/&lt;slug&gt;/&lt;pk&gt;/history</code>)</strong></p>
133
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/v03-revision-diff-dark.png" alt="flask-deck Side-by-Side Revision Diff" width="100%" /></p>
134
+ <p align="center"><strong>Background Jobs Console with Live SSE Progress, Logs &amp; Artifact Download (<code>/_jobs</code>)</strong></p>
135
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/v03-jobs-sse-dark.png" alt="flask-deck Background Jobs and SSE Logs" width="100%" /></p>
136
+ <p align="center"><strong>Native Arabic RTL (<code>dir="rtl"</code>) &amp; Per-User Timezone (<code>Europe/Istanbul</code>) via CSS Logical Properties</strong></p>
137
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/v03-rtl-arabic-dark.png" alt="flask-deck Arabic RTL Dashboard" width="100%" /></p>
138
+ <p align="center"><strong>Swiss Light Theme (Range Switcher + Callout + Pure SVG Area &amp; Donut Charts)</strong></p>
139
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/dashboard-light.png" alt="flask-deck Swiss Light Dashboard" width="100%" /></p>
140
+ <p align="center"><strong>91-Day Activity Heatmap &amp; Ranked Stat Progress Bars (100% Pure SSR SVG)</strong></p>
141
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/heatmap-dark.png" alt="flask-deck 91-Day Activity Heatmap and Stat Bars" width="100%" /></p>
142
+ <p align="center"><strong>Drag-and-Drop Kanban Board Mode (CSRF + RBAC + Audit Logged Transitions)</strong></p>
143
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/kanban-dark.png" alt="flask-deck Orders Kanban Board" width="100%" /></p>
144
+ <p align="center"><strong>Tabbed Forms &amp; Zero-Dependency Rich Widgets (Segmented Pills, Toggle Switch, Tag Input, Code Editor)</strong></p>
145
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/form-widgets-dark.png" alt="flask-deck Tabbed Form and Rich Widgets" width="100%" /></p>
146
+ <p align="center"><strong>Interactive SQLAlchemy Schema ERD Inspector (<code>/admin/_schema</code>)</strong></p>
147
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/schema-erd-dark.png" alt="flask-deck Pure SVG Schema ERD" width="100%" /></p>
148
+ <p align="center"><strong>Hardened Read-Only SQL Console with Automatic <code>[REDACTED]</code> Secret Masking (<code>/admin/_sql</code>)</strong></p>
149
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/sql-console-dark.png" alt="flask-deck Read-Only SQL Console with Redaction" width="100%" /></p>
150
+ <p align="center"><strong>Custom <code>@deck.page</code> Operations View (Radial SLA Gauge + Grouped Bar + Timeline)</strong></p>
151
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/sla-page-dark.png" alt="flask-deck Custom SLA and Capacity Page" width="100%" /></p>
152
+ <p align="center"><strong>Global ⌘K Command Palette (RBAC-Scoped Cross-Model Live Search)</strong></p>
153
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/cmdk-dark.png" alt="flask-deck Command Palette" width="100%" /></p>
154
+ <p align="center"><strong>Orders Grid + Quick Filter Tabs + 3-Tab Slide-Over Quick Peek Drawer</strong></p>
155
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/orders-drawer-dark.png" alt="flask-deck Slide-Over Quick Peek Drawer" width="100%" /></p>
156
+ <p align="center"><strong>SAVEPOINT-Verified Dry-Run CSV/JSON Diff Import</strong></p>
157
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/import-diff-dark.png" alt="flask-deck Dry-Run Import Diff Preview" width="100%" /></p>
158
+ <p align="center"><strong>Immutable Audit Ledger with Field-Level Diffs, Auto-Redaction &amp; Safe Revert</strong></p>
159
+ <p align="center"><img src="https://raw.githubusercontent.com/duhanguler/flask-deck/main/docs/assets/audit-dark.png" alt="flask-deck Audit Diff Ledger" width="100%" /></p>
160
+ </details>
161
+
162
+ ---
163
+
164
+ ## 5-Line Quickstart
165
+
166
+ ```python
167
+ from flask import Flask
168
+ from flask_sqlalchemy import SQLAlchemy
169
+ from flask_deck import BasicAuthProvider, BrandConfig, Deck
170
+
171
+ app = Flask(__name__)
172
+ app.config["SECRET_KEY"] = "replace-with-32-byte-random-secret"
173
+ app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"
174
+ db = SQLAlchemy(app)
175
+
176
+ deck = Deck(
177
+ app,
178
+ db,
179
+ auth=BasicAuthProvider.from_plain_passwords({"admin": "change-me"}),
180
+ title="Acme Ops",
181
+ brand=BrandConfig(accent="cobalt", login_subtitle="Operations Control Plane"),
182
+ )
183
+ deck.register(Organization, User, Product, Order)
184
+ ```
185
+
186
+ Using **pure SQLAlchemy 2.0** without `Flask-SQLAlchemy`? Pass `session_factory=SessionLocal, engine=engine` (and optional multi-DB `binds={"analytics": analytics_engine}`) directly — see [examples/pure_sqlalchemy_app.py](https://github.com/duhanguler/flask-deck/blob/main/examples/pure_sqlalchemy_app.py).
187
+
188
+ ---
189
+
190
+ ## Declarative `ModelView`: Media, Wizards, Cursor Pagination, Soft-Delete & Async Jobs
191
+
192
+ ```python
193
+ from types import MappingProxyType
194
+ from flask_deck import (
195
+ CodeFormatter,
196
+ CurrencyFormatter,
197
+ FileFieldConfig,
198
+ FileFormatter,
199
+ ImageFormatter,
200
+ LocalFileStorage,
201
+ ModelView,
202
+ action,
203
+ )
204
+
205
+ uploads = LocalFileStorage("./uploads")
206
+
207
+
208
+ class ProductView(ModelView):
209
+ model = Product
210
+ icon = "package"
211
+ category = "Catalog"
212
+ columns = ("thumbnail_key", "sku", "name", "price_cents", "stock", "spec_key")
213
+ filterable_columns = ("category", "is_active", "specs_json")
214
+
215
+ # 3-Step Form Wizard + Secure File/Image Fields
216
+ form_layout = "wizard"
217
+ fieldsets = (
218
+ ("Catalog Identity", ("sku", "name", "category", "is_active")),
219
+ ("Pricing & Media", ("price_cents", "stock", "thumbnail_key", "spec_key")),
220
+ ("Structured Metadata", ("specs_json",)),
221
+ )
222
+ file_fields = MappingProxyType({
223
+ "thumbnail_key": FileFieldConfig(
224
+ storage=uploads,
225
+ kind="image",
226
+ prefix="products/thumbnails",
227
+ max_bytes=2 * 1024 * 1024,
228
+ ),
229
+ "spec_key": FileFieldConfig(
230
+ storage=uploads,
231
+ kind="file",
232
+ prefix="products/specs",
233
+ allowed_mimes=frozenset({"application/pdf"}),
234
+ max_bytes=10 * 1024 * 1024,
235
+ ),
236
+ })
237
+ column_formatters = MappingProxyType({
238
+ "thumbnail_key": ImageFormatter(alt_prefix="Product"),
239
+ "sku": CodeFormatter(copyable=True),
240
+ "price_cents": CurrencyFormatter(currency="USD", divisor=100),
241
+ "spec_key": FileFormatter(),
242
+ })
243
+
244
+
245
+ class OrderView(ModelView):
246
+ model = Order
247
+ icon = "shopping-bag"
248
+ category = "Commerce"
249
+ columns = ("order_number", "organization", "customer", "status", "total_cents", "created_at")
250
+ searchable_columns = ("order_number", "organization.name", "customer.email")
251
+ filterable_columns = ("status", "organization_id", "total_cents", "created_at")
252
+ inline_editable_columns = ("status",)
253
+ inlines = (OrderItemInline,)
254
+
255
+ # Opt-in Kanban Board + Page Summary Footer + Cascading FK + Conditional Visibility
256
+ kanban_column = "status"
257
+ kanban_card_fields = ("order_number", "organization", "total_cents")
258
+ column_aggregates = MappingProxyType({"total_cents": "sum"})
259
+ field_widgets = MappingProxyType({"status": "segmented", "notes": "markdown"})
260
+ saved_views = (("High Value", "?f_total_cents__gte=100000"),)
261
+ dependent_fields = MappingProxyType({"customer_id": ("organization_id", "organization_id")})
262
+ field_conditions = MappingProxyType({"notes": ("status", "in", ("refunded", "cancelled"))})
263
+
264
+ @action("sync_erp", label="Sync to ERP (Background Job)", icon="activity", async_job=True)
265
+ def sync_erp(self, records, form_data, user, job_ctx):
266
+ total = max(len(records), 1)
267
+ for idx, order in enumerate(records, start=1):
268
+ if job_ctx.is_cancelled():
269
+ return "ERP sync cancelled."
270
+ job_ctx.set_progress(int(idx * 100 / total), f"Synced {order.order_number}")
271
+ return f"Synced {len(records)} order(s) to ERP."
272
+
273
+
274
+ class TicketView(ModelView):
275
+ model = Ticket
276
+ pagination_mode = "cursor" # HMAC-signed keyset cursor (LIMIT N+1)
277
+ count_mode = "estimated" # O(1) pg_class.reltuples on PostgreSQL
278
+ soft_delete_column = "deleted_at" # Automatic Trash tab, Restore & Force Delete
279
+ ```
280
+
281
+ ---
282
+
283
+ ## Events, Webhooks & Custom Operations Pages
284
+
285
+ ```python
286
+ from flask_deck import WebhookSink
287
+
288
+ # Typed in-process event bus
289
+ @deck.on("record.updated")
290
+ def on_record_updated(event):
291
+ print(f"{event.actor_name} updated {event.model_slug}#{event.record_pk}")
292
+
293
+ # SSRF-hardened HMAC-SHA256 webhook sink (blocks loopback, RFC 1918, CGNAT & 169.254.169.254)
294
+ deck.add_webhook(
295
+ WebhookSink(
296
+ url="https://hooks.example.com/admin-events",
297
+ secret="whsec_replace_me",
298
+ events=frozenset({"record.created", "record.deleted", "action.executed"}),
299
+ )
300
+ )
301
+ ```
302
+
303
+ ---
304
+
305
+ ## Ecosystem Comparison
306
+
307
+ | Capability | **flask-deck `v0.3`** | `flask-admin` v2.2 | `flask-appbuilder` | `sqladmin` | `django-unfold` |
308
+ | :--- | :---: | :---: | :---: | :---: | :---: |
309
+ | **Flask / WSGI Native** | **Yes** | Yes | Yes | No (ASGI) | No (Django) |
310
+ | **Pure SQLAlchemy 2.0 + Multi-Bind DBs** | **Yes** | Partial | No | Yes | N/A |
311
+ | **Zero Node Build & Zero CDN** | **Yes (`23.6 KB` gz)** | Partial | Partial | No | Partial |
312
+ | **Media Upload (Local + S3/R2/MinIO + Lightbox)** | **Yes (Magic-byte + Bomb guard)** | Local only | Partial | Via lib | Via Django |
313
+ | **Built-In i18n, Native RTL & Per-User TZ** | **Yes (CSS Logical Props)** | Babel | Babel | No | Yes |
314
+ | **Strict-CSP Dynamic Brand Theme & Slots** | **Yes (`/_theme.css`)** | Manual | Manual | Manual | Tailwind |
315
+ | **Built-In TOTP 2FA + Pure SVG QR + OIDC SSO** | **Yes (0 external deps)** | No | OAuth only | No | Via plugins |
316
+ | **Audited User Impersonation** | **Yes** | No | No | No | Via plugin |
317
+ | **Keyset Cursor Pagination + PG `JSONB`/`ARRAY`** | **Yes (HMAC cursor)** | No | No | No | Partial |
318
+ | **Conditional Fields, Cascading FK & Wizards** | **Yes (+ Pydantic)** | No | No | No | Partial |
319
+ | **Soft-Delete Trash & Side-by-Side Diff Revert** | **Yes** | No | No | No | Via plugin |
320
+ | **Background Jobs + Live SSE + SSRF Webhooks** | **Yes** | No | No | No | Via Celery |
321
+ | **Kanban + Schema ERD + Redacting SQL Console** | **Yes** | No | No | No | No |
322
+ | **SAVEPOINT Dry-Run CSV/JSON Diff Import** | **Yes** | No | No | No | Via plugin |
323
+ | **4-Level RBAC + Field Masking + Matrix UI** | **Yes** | Manual | Partial | Manual | Via Django |
324
+ | **Strict Nonce CSP (`0 unsafe-inline`)** | **Yes** | No | No | No | No |
325
+
326
+ ---
327
+
328
+ ## Performance Architecture & Benchmarks
329
+
330
+ Measured on Python 3.13 + SQLAlchemy 2.1 + SQLite via `uv run python benchmarks/bench_deck.py`:
331
+
332
+ | Workload | Result | Engineering Mechanism |
333
+ | :--- | :--- | :--- |
334
+ | **Frontend Asset Payload** | **`23.59 KB` gzip** (`8.83 KB` CSS + `14.76 KB` JS) | Zero frameworks, zero icon fonts, zero chart or QR libraries; SHA-256 immutable caching (`?v=<hash>`). |
335
+ | **Offset List View (50 / 2,000 rows + FK + 4 Tabs)** | **`4.16 ms` p50 · `4` SQL queries** | Auto `joinedload`/`selectinload` (zero N+1), single-pass `CASE` Quick Tab & Trash aggregation, `defer()` heavy blobs, single-query sidebar counts. |
336
+ | **Keyset Cursor List (50 / 2,000 rows, `count=none`)** | **`4.40 ms` p50 · `4` SQL queries** | HMAC-signed opaque cursor (`LIMIT N+1`, no `OFFSET` table scan, zero `COUNT(*)` overhead). |
337
+ | **Streaming CSV Export (2,000 rows)** | **`51.6 ms` (`38,768 rows/s`) · `2.8 MB` peak** | `session.scalars(stmt).yield_per(500)` + generator streaming (`O(1)` RAM) shared with Background CSV Jobs; CSV formula neutralization. |
338
+ | **Dry-Run Savepoint Import (1,000 rows)** | **`153.1 ms` · `0` leaked mutations** | Chunked `IN (...)` batch preload (`batch_size=500`) + released `SAVEPOINT` validation + unconditional `finally: rollback()`. |
339
+
340
+ Every page footer displays live request telemetry (`SQLAlchemy 2.0 · 4 queries · 0.3 ms SQL · 8.1 ms`) measured via lightweight request-scoped SQLAlchemy event listeners.
341
+
342
+ ---
343
+
344
+ ## Security Architecture (OWASP Defense-in-Depth)
345
+
346
+ | Vector | Built-in Protection in `flask-deck` |
347
+ | :--- | :--- |
348
+ | **Unauthenticated Exposure** | **Fail-closed:** Refuses to mount when `app.debug is False` without an explicit `AuthProvider` or `SECRET_KEY` (`SecurityConfigurationError`). Demo role switcher is hard-blocked whenever `environment == "production"`. |
349
+ | **XSS & Script Injection** | Strict per-request nonce CSP (`default-src 'none'; script-src 'self' 'nonce-…'; style-src 'self'; frame-ancestors 'none'`), zero `'unsafe-inline'`, zero `<style>`, zero inline `style=` or `on*=`, zero untrusted `innerHTML`, validated `#RRGGBB` `/_theme.css`, safe allowlisted `template_slots`. |
350
+ | **File Upload & Media Attacks** | Pure-Python magic-byte MIME verification (SVG XSS blocked by default), PNG/JPEG/GIF/WebP header decompression-bomb guard (`max_image_pixels`), path-traversal-proof storage keys, RBAC + `scope_query` enforcement on `/_media`, `X-Content-Type-Options: nosniff`, `Content-Disposition: attachment`. |
351
+ | **Account Takeover & SSO** | Built-in RFC 6238 TOTP 2FA with timestep replay prevention & PBKDF2 recovery codes, PKCE `S256` + `state`/`nonce` OIDC SSO with `allowed_domains`, sliding-window login rate limiter (`HTTP 429` + `Retry-After`), `session.clear()` fixation rotation, server-side idle/absolute timeouts, and audited superuser Impersonation (`impersonated_by`). |
352
+ | **CSRF & Clickjacking** | Cryptographic per-session token (`hmac.compare_digest`) + `Sec-Fetch-Site` / `Origin` enforcement on every mutation (login, MFA, preferences, Kanban, restore, impersonate, async jobs) + `X-Frame-Options: DENY`. |
353
+ | **Mass Assignment & IDOR** | Strict `allowed_form_fields()` allowlist rejecting tampered PK/readonly/hidden/sensitive fields (including on `?clone=`); inline parent-ownership verification; uniform `scope_query` across list, cursor, Kanban, media, history, drawer, search, export, and import. |
354
+ | **SSRF & Data Exfiltration** | `WebhookSink` validates DNS & target IPs before dispatch, blocking loopback, RFC 1918 private, link-local, multicast, and cloud metadata endpoints (`169.254.169.254`, `127.0.0.1`, `::1`). Opt-in superuser `/_sql` console enforces multi-layer read-only SQL firewall + automatic `[REDACTED]` masking. |
355
+
356
+ ### Built-In CLI & In-App Security Auditor
357
+
358
+ ```bash
359
+ flask --app yourapp deck info
360
+ flask --app yourapp deck audit
361
+ ```
362
+
363
+ Both `flask deck audit` and the live `/admin/_diagnostics` panel inspect `SECRET_KEY` entropy, session cookie flags (`HttpOnly`, `SameSite`, `Secure`), `OpenAuthProvider` misuse, MFA/impersonation posture, sensitive column exposure, SQL console posture, and unindexed `searchable_columns`.
364
+
365
+ ---
366
+
367
+ ## Migrating from `flask-admin`
368
+
369
+ See the 1-to-1 migration guide in [docs/migration-from-flask-admin.md](https://github.com/duhanguler/flask-deck/blob/main/docs/migration-from-flask-admin.md).
370
+
371
+ ## Development
372
+
373
+ ```bash
374
+ git clone https://github.com/duhanguler/flask-deck.git
375
+ cd flask-deck
376
+ uv sync --extra dev
377
+ make check
378
+ ```
379
+
380
+ ## License
381
+
382
+ MIT © 2026 [Duhan Güler](https://github.com/duhanguler)