hyper-admin 1.0.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 (442) hide show
  1. hyper_admin-1.0.0.dist-info/METADATA +366 -0
  2. hyper_admin-1.0.0.dist-info/RECORD +442 -0
  3. hyper_admin-1.0.0.dist-info/WHEEL +4 -0
  4. hyper_admin-1.0.0.dist-info/entry_points.txt +2 -0
  5. hyper_admin-1.0.0.dist-info/licenses/LICENSE +21 -0
  6. hyperadmin/__init__.py +52 -0
  7. hyperadmin/__main__.py +21 -0
  8. hyperadmin/adapters/__init__.py +28 -0
  9. hyperadmin/adapters/_estimate.py +33 -0
  10. hyperadmin/adapters/_filter_clause.py +9 -0
  11. hyperadmin/adapters/_occ.py +44 -0
  12. hyperadmin/adapters/_relation_loading.py +23 -0
  13. hyperadmin/adapters/_search.py +84 -0
  14. hyperadmin/adapters/filtering.py +86 -0
  15. hyperadmin/adapters/introspection.py +239 -0
  16. hyperadmin/adapters/registry.py +37 -0
  17. hyperadmin/adapters/schema.py +239 -0
  18. hyperadmin/adapters/sqlalchemy.py +423 -0
  19. hyperadmin/adapters/sqlmodel.py +650 -0
  20. hyperadmin/auth/__init__.py +156 -0
  21. hyperadmin/auth/_types.py +52 -0
  22. hyperadmin/auth/backend.py +37 -0
  23. hyperadmin/auth/bridge.py +351 -0
  24. hyperadmin/auth/exceptions.py +124 -0
  25. hyperadmin/auth/middleware.py +287 -0
  26. hyperadmin/auth/models.py +245 -0
  27. hyperadmin/auth/oauth/__init__.py +81 -0
  28. hyperadmin/auth/oauth/backend.py +611 -0
  29. hyperadmin/auth/oauth/providers.py +214 -0
  30. hyperadmin/auth/oauth/refresh.py +126 -0
  31. hyperadmin/auth/oauth/session.py +96 -0
  32. hyperadmin/auth/oauth/tokens.py +114 -0
  33. hyperadmin/auth/oauth/views.py +306 -0
  34. hyperadmin/auth/oauth/wiring.py +131 -0
  35. hyperadmin/auth/otp.py +189 -0
  36. hyperadmin/auth/permissions.py +232 -0
  37. hyperadmin/auth/session.py +81 -0
  38. hyperadmin/auth/session_middleware.py +164 -0
  39. hyperadmin/auth/token_handoff.py +452 -0
  40. hyperadmin/auth/user_cache.py +222 -0
  41. hyperadmin/auth/views.py +581 -0
  42. hyperadmin/core/__init__.py +76 -0
  43. hyperadmin/core/actions.py +151 -0
  44. hyperadmin/core/adapters.py +883 -0
  45. hyperadmin/core/app.py +1437 -0
  46. hyperadmin/core/auth.py +97 -0
  47. hyperadmin/core/bulk_results.py +28 -0
  48. hyperadmin/core/cache.py +68 -0
  49. hyperadmin/core/choices.py +38 -0
  50. hyperadmin/core/concurrency.py +107 -0
  51. hyperadmin/core/csrf.py +108 -0
  52. hyperadmin/core/discovery.py +161 -0
  53. hyperadmin/core/display.py +172 -0
  54. hyperadmin/core/fields.py +158 -0
  55. hyperadmin/core/fieldsets.py +22 -0
  56. hyperadmin/core/filtering.py +403 -0
  57. hyperadmin/core/filters_compat.py +78 -0
  58. hyperadmin/core/inlines.py +64 -0
  59. hyperadmin/core/introspection.py +280 -0
  60. hyperadmin/core/layouts.py +17 -0
  61. hyperadmin/core/lifecycle.py +278 -0
  62. hyperadmin/core/model.py +189 -0
  63. hyperadmin/core/navigation.py +354 -0
  64. hyperadmin/core/options.py +391 -0
  65. hyperadmin/core/palette.py +94 -0
  66. hyperadmin/core/panels.py +227 -0
  67. hyperadmin/core/plugin_wiring.py +205 -0
  68. hyperadmin/core/plugins.py +588 -0
  69. hyperadmin/core/primary_key.py +118 -0
  70. hyperadmin/core/rate_limit.py +90 -0
  71. hyperadmin/core/registry.py +129 -0
  72. hyperadmin/core/relation_loading.py +25 -0
  73. hyperadmin/core/schema.py +83 -0
  74. hyperadmin/core/sensitive.py +134 -0
  75. hyperadmin/core/settings.py +377 -0
  76. hyperadmin/core/storage_paths.py +54 -0
  77. hyperadmin/core/timezones.py +137 -0
  78. hyperadmin/core/uploads.py +16 -0
  79. hyperadmin/db.py +160 -0
  80. hyperadmin/discover.py +54 -0
  81. hyperadmin/filters/__init__.py +39 -0
  82. hyperadmin/filters/base.py +246 -0
  83. hyperadmin/filters/boolean.py +105 -0
  84. hyperadmin/filters/choice.py +74 -0
  85. hyperadmin/filters/date.py +265 -0
  86. hyperadmin/filters/relation.py +69 -0
  87. hyperadmin/filters/saved_views.py +203 -0
  88. hyperadmin/i18n/__init__.py +50 -0
  89. hyperadmin/i18n/loader.py +150 -0
  90. hyperadmin/i18n/middleware.py +159 -0
  91. hyperadmin/i18n/validation_messages.py +264 -0
  92. hyperadmin/loadtest/__init__.py +28 -0
  93. hyperadmin/loadtest/batch.py +263 -0
  94. hyperadmin/loadtest/checkpoint.py +168 -0
  95. hyperadmin/loadtest/generators/__init__.py +29 -0
  96. hyperadmin/loadtest/generators/auth.py +86 -0
  97. hyperadmin/loadtest/generators/erp.py +177 -0
  98. hyperadmin/loadtest/plan.py +189 -0
  99. hyperadmin/loadtest/pool.py +113 -0
  100. hyperadmin/loadtest/progress.py +150 -0
  101. hyperadmin/locale/ar/LC_MESSAGES/messages.mo +0 -0
  102. hyperadmin/locale/ar/LC_MESSAGES/messages.po +2139 -0
  103. hyperadmin/locale/de/LC_MESSAGES/messages.mo +0 -0
  104. hyperadmin/locale/de/LC_MESSAGES/messages.po +2114 -0
  105. hyperadmin/locale/en/LC_MESSAGES/messages.mo +0 -0
  106. hyperadmin/locale/en/LC_MESSAGES/messages.po +1780 -0
  107. hyperadmin/locale/es/LC_MESSAGES/messages.mo +0 -0
  108. hyperadmin/locale/es/LC_MESSAGES/messages.po +2094 -0
  109. hyperadmin/locale/fr/LC_MESSAGES/messages.mo +0 -0
  110. hyperadmin/locale/fr/LC_MESSAGES/messages.po +2100 -0
  111. hyperadmin/locale/he/LC_MESSAGES/messages.mo +0 -0
  112. hyperadmin/locale/he/LC_MESSAGES/messages.po +2076 -0
  113. hyperadmin/locale/hi/LC_MESSAGES/messages.mo +0 -0
  114. hyperadmin/locale/hi/LC_MESSAGES/messages.po +2084 -0
  115. hyperadmin/locale/id/LC_MESSAGES/messages.mo +0 -0
  116. hyperadmin/locale/id/LC_MESSAGES/messages.po +2071 -0
  117. hyperadmin/locale/it/LC_MESSAGES/messages.mo +0 -0
  118. hyperadmin/locale/it/LC_MESSAGES/messages.po +2098 -0
  119. hyperadmin/locale/ja/LC_MESSAGES/messages.mo +0 -0
  120. hyperadmin/locale/ja/LC_MESSAGES/messages.po +2049 -0
  121. hyperadmin/locale/ko/LC_MESSAGES/messages.mo +0 -0
  122. hyperadmin/locale/ko/LC_MESSAGES/messages.po +2049 -0
  123. hyperadmin/locale/nl/LC_MESSAGES/messages.mo +0 -0
  124. hyperadmin/locale/nl/LC_MESSAGES/messages.po +2100 -0
  125. hyperadmin/locale/pl/LC_MESSAGES/messages.mo +0 -0
  126. hyperadmin/locale/pl/LC_MESSAGES/messages.po +2112 -0
  127. hyperadmin/locale/pt_BR/LC_MESSAGES/messages.mo +0 -0
  128. hyperadmin/locale/pt_BR/LC_MESSAGES/messages.po +2098 -0
  129. hyperadmin/locale/ru/LC_MESSAGES/messages.mo +0 -0
  130. hyperadmin/locale/ru/LC_MESSAGES/messages.po +2112 -0
  131. hyperadmin/locale/th/LC_MESSAGES/messages.mo +0 -0
  132. hyperadmin/locale/th/LC_MESSAGES/messages.po +2065 -0
  133. hyperadmin/locale/tr/LC_MESSAGES/messages.mo +0 -0
  134. hyperadmin/locale/tr/LC_MESSAGES/messages.po +2084 -0
  135. hyperadmin/locale/uk/LC_MESSAGES/messages.mo +0 -0
  136. hyperadmin/locale/uk/LC_MESSAGES/messages.po +1889 -0
  137. hyperadmin/locale/vi/LC_MESSAGES/messages.mo +0 -0
  138. hyperadmin/locale/vi/LC_MESSAGES/messages.po +2063 -0
  139. hyperadmin/locale/zh_CN/LC_MESSAGES/messages.mo +0 -0
  140. hyperadmin/locale/zh_CN/LC_MESSAGES/messages.po +2049 -0
  141. hyperadmin/main.py +3 -0
  142. hyperadmin/management/__init__.py +0 -0
  143. hyperadmin/management/commands/__init__.py +0 -0
  144. hyperadmin/management/commands/createsuperuser.py +114 -0
  145. hyperadmin/management/commands/initdb.py +76 -0
  146. hyperadmin/management/commands/plugins.py +31 -0
  147. hyperadmin/management/commands/seed.py +125 -0
  148. hyperadmin/navigation/__init__.py +9 -0
  149. hyperadmin/navigation/pins.py +153 -0
  150. hyperadmin/panels/__init__.py +10 -0
  151. hyperadmin/panels/pdf.py +151 -0
  152. hyperadmin/permissions/__init__.py +59 -0
  153. hyperadmin/permissions/audit.py +109 -0
  154. hyperadmin/permissions/matrix.py +343 -0
  155. hyperadmin/permissions/object_rules.py +143 -0
  156. hyperadmin/realtime/__init__.py +51 -0
  157. hyperadmin/realtime/_debug.py +77 -0
  158. hyperadmin/realtime/config.py +124 -0
  159. hyperadmin/realtime/emitting.py +143 -0
  160. hyperadmin/realtime/events.py +107 -0
  161. hyperadmin/realtime/presence.py +193 -0
  162. hyperadmin/realtime/presence_redis.py +142 -0
  163. hyperadmin/realtime/pubsub.py +129 -0
  164. hyperadmin/realtime/pubsub_redis.py +159 -0
  165. hyperadmin/realtime/registry.py +102 -0
  166. hyperadmin/realtime/sse.py +82 -0
  167. hyperadmin/realtime/ws.py +477 -0
  168. hyperadmin/routing.py +680 -0
  169. hyperadmin/static/css/_accessibility.css +149 -0
  170. hyperadmin/static/css/_alerts.css +147 -0
  171. hyperadmin/static/css/_autocomplete.css +39 -0
  172. hyperadmin/static/css/_banner.css +118 -0
  173. hyperadmin/static/css/_buttons.css +241 -0
  174. hyperadmin/static/css/_card.css +86 -0
  175. hyperadmin/static/css/_dark-mode.css +232 -0
  176. hyperadmin/static/css/_fieldsets.css +71 -0
  177. hyperadmin/static/css/_filter.css +203 -0
  178. hyperadmin/static/css/_fonts.css +25 -0
  179. hyperadmin/static/css/_forms.css +862 -0
  180. hyperadmin/static/css/_inline-cell.css +222 -0
  181. hyperadmin/static/css/_inlines.css +160 -0
  182. hyperadmin/static/css/_layout.css +62 -0
  183. hyperadmin/static/css/_login.css +112 -0
  184. hyperadmin/static/css/_menu.css +156 -0
  185. hyperadmin/static/css/_navbar.css +299 -0
  186. hyperadmin/static/css/_page-header.css +139 -0
  187. hyperadmin/static/css/_pagination.css +125 -0
  188. hyperadmin/static/css/_palette.css +304 -0
  189. hyperadmin/static/css/_panels.css +174 -0
  190. hyperadmin/static/css/_permissions.css +547 -0
  191. hyperadmin/static/css/_pill.css +123 -0
  192. hyperadmin/static/css/_popover.css +170 -0
  193. hyperadmin/static/css/_popup.css +65 -0
  194. hyperadmin/static/css/_progress.css +161 -0
  195. hyperadmin/static/css/_realtime.css +78 -0
  196. hyperadmin/static/css/_reset.css +48 -0
  197. hyperadmin/static/css/_responsive.css +51 -0
  198. hyperadmin/static/css/_rtl.css +23 -0
  199. hyperadmin/static/css/_search.css +67 -0
  200. hyperadmin/static/css/_seg.css +95 -0
  201. hyperadmin/static/css/_sidebar.css +446 -0
  202. hyperadmin/static/css/_sticky.css +54 -0
  203. hyperadmin/static/css/_table.css +776 -0
  204. hyperadmin/static/css/_theme-terminal-type.css +92 -0
  205. hyperadmin/static/css/_theme-terminal.css +330 -0
  206. hyperadmin/static/css/_theme-toggle.css +46 -0
  207. hyperadmin/static/css/_tokens.css +232 -0
  208. hyperadmin/static/css/_utilities.css +133 -0
  209. hyperadmin/static/css/hyperadmin.css +58 -0
  210. hyperadmin/static/fonts/Inter-OFL.txt +93 -0
  211. hyperadmin/static/fonts/InterVariable.woff2 +0 -0
  212. hyperadmin/static/fonts/JetBrainsMono-OFL.txt +93 -0
  213. hyperadmin/static/fonts/JetBrainsMonoVariable.woff2 +0 -0
  214. hyperadmin/static/icons/arrow-down.svg +1 -0
  215. hyperadmin/static/icons/arrow-up.svg +1 -0
  216. hyperadmin/static/icons/bar-chart-3.svg +1 -0
  217. hyperadmin/static/icons/bell.svg +1 -0
  218. hyperadmin/static/icons/bookmark.svg +1 -0
  219. hyperadmin/static/icons/briefcase.svg +1 -0
  220. hyperadmin/static/icons/building-2.svg +1 -0
  221. hyperadmin/static/icons/calendar.svg +1 -0
  222. hyperadmin/static/icons/check.svg +1 -0
  223. hyperadmin/static/icons/chevron-down.svg +1 -0
  224. hyperadmin/static/icons/chevron-left.svg +1 -0
  225. hyperadmin/static/icons/chevron-right.svg +1 -0
  226. hyperadmin/static/icons/circle-check.svg +1 -0
  227. hyperadmin/static/icons/circle-help.svg +1 -0
  228. hyperadmin/static/icons/circle-x.svg +1 -0
  229. hyperadmin/static/icons/clock.svg +1 -0
  230. hyperadmin/static/icons/columns-3.svg +1 -0
  231. hyperadmin/static/icons/command.svg +1 -0
  232. hyperadmin/static/icons/copy.svg +1 -0
  233. hyperadmin/static/icons/credit-card.svg +1 -0
  234. hyperadmin/static/icons/database.svg +1 -0
  235. hyperadmin/static/icons/download.svg +1 -0
  236. hyperadmin/static/icons/ellipsis.svg +1 -0
  237. hyperadmin/static/icons/external-link.svg +1 -0
  238. hyperadmin/static/icons/eye.svg +1 -0
  239. hyperadmin/static/icons/file-text.svg +1 -0
  240. hyperadmin/static/icons/filter.svg +1 -0
  241. hyperadmin/static/icons/folder.svg +1 -0
  242. hyperadmin/static/icons/globe.svg +1 -0
  243. hyperadmin/static/icons/history.svg +1 -0
  244. hyperadmin/static/icons/home.svg +1 -0
  245. hyperadmin/static/icons/image.svg +1 -0
  246. hyperadmin/static/icons/info.svg +1 -0
  247. hyperadmin/static/icons/key-round.svg +1 -0
  248. hyperadmin/static/icons/layers.svg +1 -0
  249. hyperadmin/static/icons/layout-grid.svg +1 -0
  250. hyperadmin/static/icons/list-checks.svg +1 -0
  251. hyperadmin/static/icons/lock.svg +1 -0
  252. hyperadmin/static/icons/log-out.svg +1 -0
  253. hyperadmin/static/icons/mail.svg +1 -0
  254. hyperadmin/static/icons/map-pin.svg +1 -0
  255. hyperadmin/static/icons/menu.svg +1 -0
  256. hyperadmin/static/icons/moon.svg +1 -0
  257. hyperadmin/static/icons/package.svg +1 -0
  258. hyperadmin/static/icons/panel-left-close.svg +1 -0
  259. hyperadmin/static/icons/panel-left-open.svg +1 -0
  260. hyperadmin/static/icons/pencil.svg +1 -0
  261. hyperadmin/static/icons/pin-off.svg +1 -0
  262. hyperadmin/static/icons/pin.svg +1 -0
  263. hyperadmin/static/icons/plus.svg +1 -0
  264. hyperadmin/static/icons/receipt.svg +1 -0
  265. hyperadmin/static/icons/refresh-cw.svg +1 -0
  266. hyperadmin/static/icons/rotate-ccw.svg +1 -0
  267. hyperadmin/static/icons/search.svg +1 -0
  268. hyperadmin/static/icons/settings.svg +1 -0
  269. hyperadmin/static/icons/shield-check.svg +1 -0
  270. hyperadmin/static/icons/shopping-cart.svg +1 -0
  271. hyperadmin/static/icons/sliders-horizontal.svg +1 -0
  272. hyperadmin/static/icons/sparkles.svg +1 -0
  273. hyperadmin/static/icons/store.svg +1 -0
  274. hyperadmin/static/icons/sun.svg +1 -0
  275. hyperadmin/static/icons/tag.svg +1 -0
  276. hyperadmin/static/icons/trash-2.svg +1 -0
  277. hyperadmin/static/icons/triangle-alert.svg +1 -0
  278. hyperadmin/static/icons/truck.svg +1 -0
  279. hyperadmin/static/icons/upload.svg +1 -0
  280. hyperadmin/static/icons/user.svg +1 -0
  281. hyperadmin/static/icons/users.svg +1 -0
  282. hyperadmin/static/icons/wallet.svg +1 -0
  283. hyperadmin/static/icons/x.svg +1 -0
  284. hyperadmin/static/img/hyperadmin-favicon.svg +1 -0
  285. hyperadmin/static/img/hyperadmin-mark-mono.svg +1 -0
  286. hyperadmin/static/img/hyperadmin-mark.svg +1 -0
  287. hyperadmin/static/img/hyperadmin-wordmark-dark.svg +1 -0
  288. hyperadmin/static/img/hyperadmin-wordmark.svg +1 -0
  289. hyperadmin/static/img/terminal/hyperadmin-favicon-16.svg +1 -0
  290. hyperadmin/static/img/terminal/hyperadmin-favicon.svg +1 -0
  291. hyperadmin/static/img/terminal/hyperadmin-mark.svg +1 -0
  292. hyperadmin/static/img/terminal/hyperadmin-wordmark-dark.svg +1 -0
  293. hyperadmin/static/img/terminal/hyperadmin-wordmark.svg +1 -0
  294. hyperadmin/static/js/autocomplete.js +475 -0
  295. hyperadmin/static/js/confirm_delete.js +113 -0
  296. hyperadmin/static/js/error_summary.js +37 -0
  297. hyperadmin/static/js/form_guard.js +77 -0
  298. hyperadmin/static/js/inline_edit.js +97 -0
  299. hyperadmin/static/js/palette.js +292 -0
  300. hyperadmin/static/js/primitives.js +205 -0
  301. hyperadmin/static/js/realtime-status.js +515 -0
  302. hyperadmin/static/js/request_errors.js +85 -0
  303. hyperadmin/static/js/shortcuts.js +175 -0
  304. hyperadmin/static/js/sidebar.js +83 -0
  305. hyperadmin/static/js/vendor/LICENSE-alpinejs.txt +21 -0
  306. hyperadmin/static/js/vendor/LICENSE-htmx.txt +25 -0
  307. hyperadmin/static/js/vendor/alpinejs-3.17.4.min.js +21 -0
  308. hyperadmin/static/js/vendor/alpinejs-focus-3.17.4.min.js +18 -0
  309. hyperadmin/static/js/vendor/htmx-1.9.10.min.js +1 -0
  310. hyperadmin/templates/_base.html +161 -0
  311. hyperadmin/templates/_messages.html +11 -0
  312. hyperadmin/templates/_navbar.html +126 -0
  313. hyperadmin/templates/_sidebar.html +80 -0
  314. hyperadmin/templates/auth/mfa_challenge.html +75 -0
  315. hyperadmin/templates/auth/mfa_settings.html +110 -0
  316. hyperadmin/templates/auth/oauth_link_required.html +24 -0
  317. hyperadmin/templates/auth/oauth_settings.html +55 -0
  318. hyperadmin/templates/base.html +16 -0
  319. hyperadmin/templates/bulk_form.html +18 -0
  320. hyperadmin/templates/bulk_result.html +20 -0
  321. hyperadmin/templates/components/_icons.html +86 -0
  322. hyperadmin/templates/components/_macros.html +27 -0
  323. hyperadmin/templates/components/_nav.html +55 -0
  324. hyperadmin/templates/components/_row_access.html +26 -0
  325. hyperadmin/templates/components/banner.html +77 -0
  326. hyperadmin/templates/components/bulk_form.html +81 -0
  327. hyperadmin/templates/components/bulk_result.html +133 -0
  328. hyperadmin/templates/components/bulk_toolbar.html +63 -0
  329. hyperadmin/templates/components/command_palette.html +59 -0
  330. hyperadmin/templates/components/confirm_delete_dialog.html +26 -0
  331. hyperadmin/templates/components/conflict_dialog.html +42 -0
  332. hyperadmin/templates/components/csrf_reload_banner.html +20 -0
  333. hyperadmin/templates/components/error_summary.html +39 -0
  334. hyperadmin/templates/components/error_toast.html +18 -0
  335. hyperadmin/templates/components/fieldset.html +38 -0
  336. hyperadmin/templates/components/filter_bar.html +50 -0
  337. hyperadmin/templates/components/filter_sidebar.html +31 -0
  338. hyperadmin/templates/components/filters/boolean.html +10 -0
  339. hyperadmin/templates/components/filters/current_period.html +8 -0
  340. hyperadmin/templates/components/filters/date_range.html +26 -0
  341. hyperadmin/templates/components/filters/is_owner.html +8 -0
  342. hyperadmin/templates/components/filters/multi_choice.html +10 -0
  343. hyperadmin/templates/components/filters/multi_relation.html +20 -0
  344. hyperadmin/templates/components/filters/select.html +11 -0
  345. hyperadmin/templates/components/inline_cell.html +23 -0
  346. hyperadmin/templates/components/inline_cell_error.html +51 -0
  347. hyperadmin/templates/components/inline_cell_stale.html +20 -0
  348. hyperadmin/templates/components/inline_editor.html +85 -0
  349. hyperadmin/templates/components/inline_formset.html +34 -0
  350. hyperadmin/templates/components/inline_row.html +49 -0
  351. hyperadmin/templates/components/list_error.html +12 -0
  352. hyperadmin/templates/components/menu.html +74 -0
  353. hyperadmin/templates/components/nav_pinned.html +24 -0
  354. hyperadmin/templates/components/pagination.html +87 -0
  355. hyperadmin/templates/components/panel_document.html +19 -0
  356. hyperadmin/templates/components/panel_states.html +35 -0
  357. hyperadmin/templates/components/panel_tab_strip.html +31 -0
  358. hyperadmin/templates/components/pill.html +15 -0
  359. hyperadmin/templates/components/popover.html +59 -0
  360. hyperadmin/templates/components/presence_banner.html +28 -0
  361. hyperadmin/templates/components/progress.html +72 -0
  362. hyperadmin/templates/components/saved_views.html +61 -0
  363. hyperadmin/templates/components/search_input.html +19 -0
  364. hyperadmin/templates/components/seg.html +38 -0
  365. hyperadmin/templates/components/shortcuts_overlay.html +45 -0
  366. hyperadmin/templates/components/sortable_header.html +23 -0
  367. hyperadmin/templates/components/table.html +45 -0
  368. hyperadmin/templates/components/table_body.html +86 -0
  369. hyperadmin/templates/components/thumbnail.html +8 -0
  370. hyperadmin/templates/components/toast.html +36 -0
  371. hyperadmin/templates/components/tooltip.html +20 -0
  372. hyperadmin/templates/create.html +43 -0
  373. hyperadmin/templates/dashboard.html +8 -0
  374. hyperadmin/templates/detail.html +120 -0
  375. hyperadmin/templates/detail_layout.html +15 -0
  376. hyperadmin/templates/error.html +24 -0
  377. hyperadmin/templates/form_layout.html +26 -0
  378. hyperadmin/templates/list.html +5 -0
  379. hyperadmin/templates/list_layout.html +105 -0
  380. hyperadmin/templates/login.html +79 -0
  381. hyperadmin/templates/permissions/_banner.html +55 -0
  382. hyperadmin/templates/permissions/_diff_row.html +6 -0
  383. hyperadmin/templates/permissions/_group_gone.html +16 -0
  384. hyperadmin/templates/permissions/_macros.html +22 -0
  385. hyperadmin/templates/permissions/matrix.html +408 -0
  386. hyperadmin/templates/permissions/object_popover.html +95 -0
  387. hyperadmin/templates/update.html +69 -0
  388. hyperadmin/templates/widgets/autocomplete.html +100 -0
  389. hyperadmin/templates/widgets/checkbox_input.html +20 -0
  390. hyperadmin/templates/widgets/choices_options.html +3 -0
  391. hyperadmin/templates/widgets/date_input.html +13 -0
  392. hyperadmin/templates/widgets/datetime_input.html +18 -0
  393. hyperadmin/templates/widgets/encoded_textarea.html +4 -0
  394. hyperadmin/templates/widgets/file_input.html +15 -0
  395. hyperadmin/templates/widgets/float_input.html +12 -0
  396. hyperadmin/templates/widgets/image_input.html +108 -0
  397. hyperadmin/templates/widgets/multiselect_input.html +13 -0
  398. hyperadmin/templates/widgets/number_input.html +11 -0
  399. hyperadmin/templates/widgets/popup_form.html +64 -0
  400. hyperadmin/templates/widgets/relation_multiselect_input.html +36 -0
  401. hyperadmin/templates/widgets/relation_select_input.html +38 -0
  402. hyperadmin/templates/widgets/select_input.html +17 -0
  403. hyperadmin/templates/widgets/text_input.html +13 -0
  404. hyperadmin/templates/widgets/textarea.html +4 -0
  405. hyperadmin/uploads/__init__.py +44 -0
  406. hyperadmin/uploads/images.py +272 -0
  407. hyperadmin/uploads/storage.py +265 -0
  408. hyperadmin/uploads/validation.py +37 -0
  409. hyperadmin/views/__init__.py +3 -0
  410. hyperadmin/views/csrf.py +316 -0
  411. hyperadmin/views/dynamic/__init__.py +35 -0
  412. hyperadmin/views/dynamic/actions.py +264 -0
  413. hyperadmin/views/dynamic/base.py +576 -0
  414. hyperadmin/views/dynamic/concurrency.py +138 -0
  415. hyperadmin/views/dynamic/core.py +33 -0
  416. hyperadmin/views/dynamic/create.py +189 -0
  417. hyperadmin/views/dynamic/detail.py +231 -0
  418. hyperadmin/views/dynamic/files.py +233 -0
  419. hyperadmin/views/dynamic/form_data.py +162 -0
  420. hyperadmin/views/dynamic/helpers.py +151 -0
  421. hyperadmin/views/dynamic/inline.py +348 -0
  422. hyperadmin/views/dynamic/list_view.py +612 -0
  423. hyperadmin/views/dynamic/model_view.py +17 -0
  424. hyperadmin/views/dynamic/palette_search.py +78 -0
  425. hyperadmin/views/dynamic/relations.py +544 -0
  426. hyperadmin/views/dynamic/saved_views.py +159 -0
  427. hyperadmin/views/dynamic/update.py +313 -0
  428. hyperadmin/views/error_pages.py +46 -0
  429. hyperadmin/views/forms.py +1294 -0
  430. hyperadmin/views/htmx.py +53 -0
  431. hyperadmin/views/locale.py +113 -0
  432. hyperadmin/views/nav_pins.py +149 -0
  433. hyperadmin/views/navigation.py +143 -0
  434. hyperadmin/views/palette_context.py +91 -0
  435. hyperadmin/views/palette_search.py +103 -0
  436. hyperadmin/views/permissions_matrix.py +490 -0
  437. hyperadmin/views/rate_limit.py +87 -0
  438. hyperadmin/views/route.py +316 -0
  439. hyperadmin/views/static.py +138 -0
  440. hyperadmin/views/template_filters.py +305 -0
  441. hyperadmin/views/uploads.py +92 -0
  442. hyperadmin/views/urls.py +180 -0
@@ -0,0 +1,452 @@
1
+ """Token handoff, bearer login form and bridge logout for bearer-only hosts (SDD B.4).
2
+
3
+ A bearer-only host (``OAuth2PasswordBearer`` plus an SPA) cannot authenticate a
4
+ plain browser navigation to ``/admin``: the browser sends no ``Authorization``
5
+ header. With ``ExternalAuth(token_cookie=TokenCookie())`` the admin stores the
6
+ bearer token in an admin-scoped ``HttpOnly`` cookie, which ``HyperAdminRoute``
7
+ copies back into ``Authorization`` on later admin requests. Two ways in:
8
+
9
+ - ``POST {prefix}/auth/session`` (:func:`token_handoff_view`): an SPA hands over
10
+ the bearer it already holds. The route is guarded by
11
+ ``build_admin_dependency(auth)`` itself, so the host dependency validates the
12
+ token natively, and it is exempt from CSRF (a cross-site page cannot set
13
+ ``Authorization``).
14
+ - ``GET/POST {prefix}/login`` (:func:`bridge_login_view`), opt-in with
15
+ ``TokenCookie(token_endpoint=...)``: credentials are posted **server side** to
16
+ the host's token endpoint (or an ``issue_token`` callable), so a bearer-only
17
+ host needs no frontend change at all.
18
+
19
+ ``POST {prefix}/logout`` (:func:`bridge_logout_view`) clears the cookie and
20
+ redirects to ``ExternalAuth.logout_url``.
21
+
22
+ Every function here takes the per-request admin path as a plain string and
23
+ imports nothing from ``views/`` (CONSTITUTION.md §2); ``core/app.py`` wires them
24
+ into routes.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import base64
30
+ import binascii
31
+ import inspect
32
+ import json
33
+ import logging
34
+ import math
35
+ import time
36
+ import urllib.error
37
+ import urllib.request
38
+ from typing import TYPE_CHECKING, Any
39
+ from urllib.parse import unquote, urlencode, urlsplit
40
+
41
+ from fastapi import HTTPException, Request
42
+ from fastapi.dependencies.utils import get_dependant
43
+ from fastapi.openapi.models import OAuth2
44
+ from fastapi.security import OAuth2PasswordBearer
45
+ from starlette.concurrency import run_in_threadpool
46
+ from starlette.responses import RedirectResponse, Response
47
+
48
+ from hyperadmin.core.settings import CookieSecure, resolve_cookie_secure
49
+
50
+ if TYPE_CHECKING:
51
+ from collections.abc import Callable
52
+
53
+ from fastapi.templating import Jinja2Templates
54
+ from starlette.types import ASGIApp, Message
55
+
56
+ from hyperadmin.auth.bridge import MaybeAwaitable, TokenCookie
57
+
58
+ __all__ = [
59
+ "DISCOVER_TOKEN_URL",
60
+ "MAX_TOKEN_BYTES",
61
+ "bridge_login_view",
62
+ "bridge_logout_view",
63
+ "cookie_max_age",
64
+ "discover_token_url",
65
+ "jwt_expiry",
66
+ "reject_oversized_token",
67
+ "request_token",
68
+ "resolve_token_endpoint",
69
+ "safe_next",
70
+ "token_handoff_view",
71
+ ]
72
+
73
+ logger = logging.getLogger("hyperadmin.auth")
74
+
75
+ #: Largest bearer token the handoff stores. A cookie holds about 4 KB, name and
76
+ #: attributes included; a larger token would be silently dropped by the browser.
77
+ MAX_TOKEN_BYTES = 3800
78
+
79
+ #: ``TokenCookie(token_endpoint="auto")``: post to the ``tokenUrl`` of the
80
+ #: ``OAuth2PasswordBearer`` found in ``ExternalAuth.get_user``'s dependency tree.
81
+ DISCOVER_TOKEN_URL = "auto" # noqa: S105 - a sentinel, not a secret
82
+
83
+ #: Seconds a server-side call to an absolute token URL may take.
84
+ _TOKEN_REQUEST_TIMEOUT = 10.0
85
+
86
+
87
+ # ── Token helpers ──────────────────────────────────────────────────────────
88
+
89
+
90
+ def _credentials(authorization: str | None) -> str:
91
+ """Return the credentials part of an ``Authorization`` header (``""`` when absent)."""
92
+ if not authorization:
93
+ return ""
94
+ return authorization.partition(" ")[2].strip() or authorization.strip()
95
+
96
+
97
+ def _bearer_token(authorization: str | None, scheme: str) -> str | None:
98
+ """Return the token of ``"<scheme> <token>"`` (scheme case-insensitive), else ``None``."""
99
+ if not authorization:
100
+ return None
101
+ given, _, token = authorization.partition(" ")
102
+ token = token.strip()
103
+ if given.lower() != scheme.lower() or not token:
104
+ return None
105
+ return token
106
+
107
+
108
+ def reject_oversized_token(request: Request) -> None:
109
+ """FastAPI dependency: 400 when the bearer token exceeds :data:`MAX_TOKEN_BYTES`.
110
+
111
+ Listed before the admin principal on the handoff route, so an oversized
112
+ token is refused before the host dependency ever sees it.
113
+ """
114
+ credentials = _credentials(request.headers.get("authorization"))
115
+ if len(credentials.encode("utf-8")) > MAX_TOKEN_BYTES:
116
+ raise HTTPException(status_code=400, detail="Token too large for the admin cookie")
117
+
118
+
119
+ def jwt_expiry(token: str) -> float | None:
120
+ """Return the ``exp`` claim of a JWT, read **without** verifying its signature.
121
+
122
+ Used only to size the cookie lifetime; the host dependency still verifies
123
+ every request's token. Returns ``None`` for an opaque token, a malformed
124
+ payload or a missing, non-numeric or non-finite (``NaN``/``Infinity``) ``exp``.
125
+ """
126
+ parts = token.split(".")
127
+ if len(parts) != 3: # noqa: PLR2004 - header.payload.signature
128
+ return None
129
+ payload = parts[1]
130
+ try:
131
+ raw = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))
132
+ claims = json.loads(raw)
133
+ except (binascii.Error, ValueError):
134
+ return None
135
+ exp = claims.get("exp") if isinstance(claims, dict) else None
136
+ if isinstance(exp, bool) or not isinstance(exp, (int, float)) or not math.isfinite(exp):
137
+ return None
138
+ return float(exp)
139
+
140
+
141
+ def cookie_max_age(token: str, max_age: int | None, *, now: float | None = None) -> int | None:
142
+ """Return the token cookie's ``Max-Age``: ``min(max_age, exp - now)`` (SDD B.4).
143
+
144
+ An opaque token keeps ``max_age``; with neither, the cookie is a session
145
+ cookie (``None``). Never negative.
146
+ """
147
+ exp = jwt_expiry(token)
148
+ if exp is None:
149
+ return max_age
150
+ remaining = max(0, int(exp - (time.time() if now is None else now)))
151
+ return remaining if max_age is None else min(max_age, remaining)
152
+
153
+
154
+ def _set_token_cookie(
155
+ response: Response,
156
+ request: Request,
157
+ cookie: TokenCookie,
158
+ token: str,
159
+ *,
160
+ admin_path: str,
161
+ cookie_secure: CookieSecure,
162
+ ) -> None:
163
+ response.set_cookie(
164
+ cookie.name,
165
+ token,
166
+ max_age=cookie_max_age(token, cookie.max_age),
167
+ path=admin_path or "/",
168
+ httponly=True,
169
+ samesite="lax",
170
+ secure=resolve_cookie_secure(cookie_secure, request.url.scheme),
171
+ )
172
+
173
+
174
+ # ── next validation ────────────────────────────────────────────────────────
175
+
176
+
177
+ def safe_next(value: str | None, admin_path: str) -> str:
178
+ """Return ``value`` when it is a safe in-admin redirect target, else the dashboard.
179
+
180
+ Safe means a relative path starting with ``admin_path + "/"``, with no
181
+ scheme or authority, no ``//`` prefix, no backslash, no control or
182
+ whitespace character and no ``.``/``..`` segment (encoded or not) that a
183
+ browser would resolve outside the admin (SDD B.4).
184
+ """
185
+ dashboard = f"{admin_path}/"
186
+ if not value or "\\" in value or value.startswith("//"):
187
+ return dashboard
188
+ if any(ord(char) < 0x21 or ord(char) == 0x7F for char in value): # noqa: PLR2004
189
+ return dashboard
190
+ parts = urlsplit(value)
191
+ if parts.scheme or parts.netloc or not value.startswith(dashboard):
192
+ return dashboard
193
+ segments = unquote(parts.path).split("/")
194
+ if any(segment in {".", ".."} for segment in segments):
195
+ return dashboard
196
+ return value
197
+
198
+
199
+ # ── Token endpoint ─────────────────────────────────────────────────────────
200
+
201
+
202
+ def discover_token_url(get_user: Callable[..., Any]) -> str | None:
203
+ """Return the ``tokenUrl`` of the first ``OAuth2PasswordBearer`` in ``get_user``'s tree."""
204
+ stack = [get_dependant(path="", call=get_user)]
205
+ while stack:
206
+ dependant = stack.pop()
207
+ call = dependant.call
208
+ model = call.model if isinstance(call, OAuth2PasswordBearer) else None
209
+ if isinstance(model, OAuth2) and model.flows.password is not None:
210
+ return model.flows.password.tokenUrl
211
+ stack.extend(dependant.dependencies)
212
+ return None
213
+
214
+
215
+ def resolve_token_endpoint(
216
+ endpoint: str | Callable[[str, str], MaybeAwaitable[str | None]],
217
+ get_user: Callable[..., Any],
218
+ ) -> str | Callable[[str, str], MaybeAwaitable[str | None]]:
219
+ """Resolve ``TokenCookie.token_endpoint``, expanding ``"auto"`` (:data:`DISCOVER_TOKEN_URL`).
220
+
221
+ Raises:
222
+ ValueError: ``"auto"`` was given but ``get_user`` depends on no
223
+ ``OAuth2PasswordBearer``.
224
+ """
225
+ if endpoint != DISCOVER_TOKEN_URL:
226
+ return endpoint
227
+ url = discover_token_url(get_user)
228
+ if url is None:
229
+ msg = (
230
+ 'TokenCookie(token_endpoint="auto") found no OAuth2PasswordBearer tokenUrl in '
231
+ "ExternalAuth.get_user's dependencies; pass the token URL or an "
232
+ "issue_token(username, password) callable instead."
233
+ )
234
+ raise ValueError(msg)
235
+ return url
236
+
237
+
238
+ def _post_url(url: str, body: bytes) -> tuple[int, bytes]:
239
+ """POST a form to an absolute http(s) URL (runs in a worker thread)."""
240
+ outgoing = urllib.request.Request( # noqa: S310 - scheme checked by the caller
241
+ url,
242
+ data=body,
243
+ headers={
244
+ "Content-Type": "application/x-www-form-urlencoded",
245
+ "Accept": "application/json",
246
+ },
247
+ method="POST",
248
+ )
249
+ try:
250
+ with urllib.request.urlopen(outgoing, timeout=_TOKEN_REQUEST_TIMEOUT) as reply: # noqa: S310
251
+ return reply.status, reply.read()
252
+ except urllib.error.HTTPError as exc:
253
+ return exc.code, b""
254
+ except (urllib.error.URLError, OSError):
255
+ logger.warning("HyperAdmin bridge login: token endpoint %s is unreachable", url)
256
+ return 0, b""
257
+
258
+
259
+ async def _post_in_process(app: ASGIApp, url: str, body: bytes) -> tuple[int, bytes]:
260
+ """POST a form to a path of the host app, in process (no network, no server)."""
261
+ parts = urlsplit(url)
262
+ path = "/" + parts.path.lstrip("/")
263
+ scope: dict[str, Any] = {
264
+ "type": "http",
265
+ "asgi": {"version": "3.0"},
266
+ "http_version": "1.1",
267
+ "method": "POST",
268
+ "scheme": "http",
269
+ "path": path,
270
+ "raw_path": path.encode("latin-1"),
271
+ "root_path": "",
272
+ "query_string": parts.query.encode("latin-1"),
273
+ "headers": [
274
+ (b"host", b"hyperadmin.internal"),
275
+ (b"content-type", b"application/x-www-form-urlencoded"),
276
+ (b"content-length", str(len(body)).encode("latin-1")),
277
+ (b"accept", b"application/json"),
278
+ ],
279
+ "client": ("127.0.0.1", 0),
280
+ "server": ("hyperadmin.internal", 80),
281
+ }
282
+ sent = False
283
+ status = 0
284
+ chunks: list[bytes] = []
285
+
286
+ async def receive() -> Message:
287
+ nonlocal sent
288
+ if sent:
289
+ return {"type": "http.disconnect"}
290
+ sent = True
291
+ return {"type": "http.request", "body": body, "more_body": False}
292
+
293
+ async def send(message: Message) -> None:
294
+ nonlocal status
295
+ if message["type"] == "http.response.start":
296
+ status = int(message["status"])
297
+ elif message["type"] == "http.response.body":
298
+ chunks.append(message.get("body", b""))
299
+
300
+ try:
301
+ await app(scope, receive, send)
302
+ except Exception:
303
+ logger.exception("HyperAdmin bridge login: the host token endpoint %s failed", url)
304
+ return 0, b""
305
+ return status, b"".join(chunks)
306
+
307
+
308
+ async def request_token(
309
+ endpoint: str | Callable[[str, str], MaybeAwaitable[str | None]],
310
+ username: str,
311
+ password: str,
312
+ *,
313
+ host_app: ASGIApp,
314
+ ) -> str | None:
315
+ """Exchange credentials for an access token, server side; ``None`` on failure.
316
+
317
+ ``endpoint`` is an ``issue_token(username, password)`` callable (sync or
318
+ async), an absolute ``http(s)`` URL, or a path on ``host_app`` (called in
319
+ process). URLs get an OAuth2 password-grant form and must answer 200 with a
320
+ JSON ``access_token``.
321
+ """
322
+ if callable(endpoint):
323
+ issued = endpoint(username, password)
324
+ if inspect.isawaitable(issued):
325
+ issued = await issued
326
+ return issued or None
327
+ body = urlencode({"grant_type": "password", "username": username, "password": password})
328
+ if urlsplit(endpoint).scheme in {"http", "https"}:
329
+ status, payload = await run_in_threadpool(_post_url, endpoint, body.encode())
330
+ else:
331
+ status, payload = await _post_in_process(host_app, endpoint, body.encode())
332
+ if status != 200: # noqa: PLR2004
333
+ return None
334
+ try:
335
+ data = json.loads(payload)
336
+ except ValueError:
337
+ return None
338
+ token = data.get("access_token") if isinstance(data, dict) else None
339
+ return token if isinstance(token, str) and token else None
340
+
341
+
342
+ # ── Views ──────────────────────────────────────────────────────────────────
343
+
344
+
345
+ async def token_handoff_view(
346
+ request: Request,
347
+ *,
348
+ cookie: TokenCookie,
349
+ admin_path: str,
350
+ cookie_secure: CookieSecure,
351
+ next_param: str,
352
+ ) -> Response:
353
+ """``POST {prefix}/auth/session``: store the (already validated) bearer in the cookie.
354
+
355
+ The host dependency has accepted the request's ``Authorization`` header by
356
+ the time this runs. Returns 204, or 303 to a validated ``next``; 400 when
357
+ the header does not carry a ``TokenCookie.scheme`` token.
358
+ """
359
+ token = _bearer_token(request.headers.get("authorization"), cookie.scheme)
360
+ if token is None:
361
+ raise HTTPException(
362
+ status_code=400, detail=f"Expected an 'Authorization: {cookie.scheme} <token>' header"
363
+ )
364
+ next_value = request.query_params.get(next_param)
365
+ response: Response
366
+ if next_value is None:
367
+ response = Response(status_code=204)
368
+ else:
369
+ response = RedirectResponse(safe_next(next_value, admin_path), status_code=303)
370
+ _set_token_cookie(
371
+ response, request, cookie, token, admin_path=admin_path, cookie_secure=cookie_secure
372
+ )
373
+ return response
374
+
375
+
376
+ async def bridge_logout_view(
377
+ request: Request,
378
+ *,
379
+ cookie: TokenCookie | None,
380
+ admin_path: str,
381
+ logout_url: str | None,
382
+ cookie_secure: CookieSecure,
383
+ ) -> Response:
384
+ """``POST {prefix}/logout``: clear the token cookie, then 303 to ``logout_url or "/"``."""
385
+ response = RedirectResponse(logout_url or "/", status_code=303)
386
+ if cookie is not None:
387
+ response.delete_cookie(
388
+ cookie.name,
389
+ path=admin_path or "/",
390
+ httponly=True,
391
+ samesite="lax",
392
+ secure=resolve_cookie_secure(cookie_secure, request.url.scheme),
393
+ )
394
+ return response
395
+
396
+
397
+ async def bridge_login_view( # noqa: PLR0913 - one view, its wiring passed explicitly
398
+ request: Request,
399
+ *,
400
+ templates: Jinja2Templates,
401
+ cookie: TokenCookie,
402
+ endpoint: str | Callable[[str, str], MaybeAwaitable[str | None]],
403
+ host_app: ASGIApp,
404
+ admin_path: str,
405
+ cookie_secure: CookieSecure,
406
+ next_param: str,
407
+ ) -> Response:
408
+ """``GET/POST {prefix}/login``: the opt-in admin login form for bearer hosts (SDD B.4).
409
+
410
+ GET renders ``login.html``; POST exchanges the credentials for a token
411
+ through :func:`request_token` and stores it in the cookie, then 303s to the
412
+ validated ``next``. Wrong credentials re-render the form with an error.
413
+ """
414
+ error: str | None = None
415
+ next_value = request.query_params.get(next_param)
416
+ if request.method == "POST":
417
+ form = await request.form()
418
+ posted_next = form.get(next_param)
419
+ next_value = posted_next if isinstance(posted_next, str) else next_value
420
+ token = await request_token(
421
+ endpoint,
422
+ str(form.get("username", "")),
423
+ str(form.get("password", "")),
424
+ host_app=host_app,
425
+ )
426
+ if token is None:
427
+ error = "Invalid username or password."
428
+ elif len(token.encode("utf-8")) > MAX_TOKEN_BYTES:
429
+ # A browser silently drops an oversized cookie: storing it would
430
+ # loop the user back to this form with no explanation.
431
+ logger.warning(
432
+ "HyperAdmin bridge login: the issued token exceeds %d bytes and cannot be "
433
+ "stored in the admin cookie",
434
+ MAX_TOKEN_BYTES,
435
+ )
436
+ error = "The sign-in token is too large for the admin cookie."
437
+ else:
438
+ response = RedirectResponse(safe_next(next_value, admin_path), status_code=303)
439
+ _set_token_cookie(
440
+ response, request, cookie, token, admin_path=admin_path, cookie_secure=cookie_secure
441
+ )
442
+ return response
443
+ target = safe_next(next_value, admin_path)
444
+ context: dict[str, Any] = {
445
+ "request": request,
446
+ "error": error,
447
+ "admin_prefix": admin_path,
448
+ "next_param": next_param,
449
+ # Only a validated, explicit target is round-tripped through the form.
450
+ "next_url": target if next_value and target == next_value else None,
451
+ }
452
+ return templates.TemplateResponse(request, "login.html", context)
@@ -0,0 +1,222 @@
1
+ """Per-worker TTL cache for the authenticated user and its permission set.
2
+
3
+ Opt-in through ``HyperAdminSettings.user_cache_ttl``. The cache lives in one
4
+ process: a write on this worker drops the affected entries at commit, while other
5
+ workers may serve a stale entry for up to the TTL (see the production notes).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import functools
12
+ import time
13
+ import weakref
14
+ from collections import OrderedDict
15
+ from typing import TYPE_CHECKING, Any, NamedTuple
16
+
17
+ from sqlalchemy import event
18
+ from sqlalchemy import inspect as sa_inspect
19
+ from sqlalchemy.orm import Session
20
+ from sqlalchemy.orm.attributes import set_committed_value
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Callable
24
+
25
+ from sqlalchemy.orm import ORMExecuteState
26
+
27
+ #: Upper bound on cached users per middleware instance; the oldest entry is evicted first.
28
+ DEFAULT_MAX_ENTRIES = 1024
29
+
30
+ _DIRTY_KEY = "hyperadmin_user_cache_dirty"
31
+ #: Marker meaning "every entry may be affected" (group or permission rows changed).
32
+ _ALL = object()
33
+
34
+
35
+ class CachedUser(NamedTuple):
36
+ """A user snapshot with its permission codenames (``None`` = unrestricted).
37
+
38
+ ``user`` is private to the cache: hand out :func:`clone_user` copies, never this
39
+ object, so no request can change what another one is served.
40
+ """
41
+
42
+ user: Any
43
+ permissions: frozenset[str] | None
44
+
45
+
46
+ def clone_user(user: Any) -> Any | None:
47
+ """Return a fresh detached copy of a mapped ``user``'s loaded columns.
48
+
49
+ ``None`` when ``user`` is not an ORM instance (it is then not cacheable). The copy
50
+ is transient with no pending changes; relationships stay empty, unloaded columns read
51
+ as ``None`` and nested column values (JSON) are deep-copied.
52
+ """
53
+ state = sa_inspect(user, raiseerr=False)
54
+ if state is None:
55
+ return None
56
+ mapper = state.mapper
57
+ clone = mapper.class_manager.new_instance()
58
+ for attr in mapper.column_attrs:
59
+ if attr.key in state.dict:
60
+ set_committed_value(clone, attr.key, copy.deepcopy(state.dict[attr.key]))
61
+ return clone
62
+
63
+
64
+ class UserCache:
65
+ """Bounded TTL cache keyed by session user id."""
66
+
67
+ def __init__(
68
+ self,
69
+ ttl: float,
70
+ *,
71
+ clock: Callable[[], float] = time.monotonic,
72
+ max_entries: int = DEFAULT_MAX_ENTRIES,
73
+ ) -> None:
74
+ self.ttl = ttl
75
+ self._clock = clock
76
+ self._max_entries = max_entries
77
+ self._entries: OrderedDict[Any, tuple[float, CachedUser]] = OrderedDict()
78
+ self._generation = 0
79
+ _CACHES.add(self)
80
+ _ensure_listeners()
81
+
82
+ def get(self, key: Any) -> CachedUser | None:
83
+ """Return the live entry for ``key``, or ``None`` when missing or expired."""
84
+ item = self._entries.get(key)
85
+ if item is None:
86
+ return None
87
+ expires_at, value = item
88
+ if self._clock() >= expires_at:
89
+ del self._entries[key]
90
+ return None
91
+ return value
92
+
93
+ @property
94
+ def generation(self) -> int:
95
+ """Counter bumped by every invalidation; read it before loading a value to cache."""
96
+ return self._generation
97
+
98
+ def set(self, key: Any, value: CachedUser, generation: int) -> None:
99
+ """Store ``value`` for ``key`` for ``ttl`` seconds, evicting the oldest when full.
100
+
101
+ ``generation`` is the :attr:`generation` read before ``value`` was loaded. When an
102
+ invalidation ran since, the value may predate a committed write and is dropped.
103
+ """
104
+ if generation != self._generation:
105
+ return
106
+ self._entries.pop(key, None)
107
+ self._entries[key] = (self._clock() + self.ttl, value)
108
+ while len(self._entries) > self._max_entries:
109
+ self._entries.popitem(last=False)
110
+
111
+ def invalidate(self, key: Any) -> None:
112
+ """Drop the entry for ``key`` if present, and veto fills that started earlier."""
113
+ self._generation += 1
114
+ self._entries.pop(key, None)
115
+
116
+ def clear(self) -> None:
117
+ """Drop every entry, and veto fills that started earlier."""
118
+ self._generation += 1
119
+ self._entries.clear()
120
+
121
+
122
+ _CACHES: weakref.WeakSet[UserCache] = weakref.WeakSet()
123
+
124
+
125
+ def invalidate_user(user_id: Any) -> None:
126
+ """Drop ``user_id`` from every cache in this process."""
127
+ for cache in list(_CACHES):
128
+ cache.invalidate(user_id)
129
+
130
+
131
+ def invalidate_all() -> None:
132
+ """Drop every entry from every cache in this process."""
133
+ for cache in list(_CACHES):
134
+ cache.clear()
135
+
136
+
137
+ def _collect(session: Session, _flush_context: Any) -> None:
138
+ """Record which cache entries this flush makes stale (applied on commit)."""
139
+ from hyperadmin.auth.models import ( # noqa: PLC0415 - lazy: keeps auth tables unregistered on import
140
+ Group,
141
+ GroupPermission,
142
+ Permission,
143
+ User,
144
+ UserGroup,
145
+ UserPermission,
146
+ )
147
+
148
+ if not _CACHES:
149
+ return
150
+ dirty: set[Any] = session.info.setdefault(_DIRTY_KEY, set())
151
+ for obj in (*session.new, *session.dirty, *session.deleted):
152
+ owner: Any
153
+ if isinstance(obj, User):
154
+ owner = obj.id
155
+ elif isinstance(obj, UserGroup | UserPermission):
156
+ owner = obj.user_id
157
+ elif isinstance(obj, Group | GroupPermission | Permission):
158
+ owner = _ALL
159
+ else:
160
+ continue
161
+ if owner is not None: # a brand-new user has no id yet and no entry to drop
162
+ dirty.add(owner)
163
+
164
+
165
+ @functools.cache
166
+ def _auth_table_names() -> frozenset[str]:
167
+ from hyperadmin.auth.models import ( # noqa: PLC0415 - lazy: keeps auth tables unregistered on import
168
+ Group,
169
+ GroupPermission,
170
+ Permission,
171
+ User,
172
+ UserGroup,
173
+ UserPermission,
174
+ )
175
+
176
+ models = (User, Group, Permission, UserGroup, UserPermission, GroupPermission)
177
+ return frozenset(model.__table__.name for model in models) # type: ignore[union-attr]
178
+
179
+
180
+ def _collect_bulk(state: ORMExecuteState) -> None:
181
+ """Treat a bulk INSERT/UPDATE/DELETE on an auth table as touching every entry.
182
+
183
+ These statements skip the unit of work, so ``_collect`` never sees them.
184
+ """
185
+ if not _CACHES or not (state.is_insert or state.is_update or state.is_delete):
186
+ return
187
+ table = getattr(state.statement, "table", None)
188
+ if getattr(table, "name", None) in _auth_table_names():
189
+ state.session.info.setdefault(_DIRTY_KEY, set()).add(_ALL)
190
+
191
+
192
+ def _apply(session: Session) -> None:
193
+ dirty = session.info.pop(_DIRTY_KEY, None)
194
+ if not dirty:
195
+ return
196
+ if _ALL in dirty:
197
+ invalidate_all()
198
+ return
199
+ for user_id in dirty:
200
+ invalidate_user(user_id)
201
+
202
+
203
+ def _discard(session: Session) -> None:
204
+ session.info.pop(_DIRTY_KEY, None)
205
+
206
+
207
+ _listening = False
208
+
209
+
210
+ def _ensure_listeners() -> None:
211
+ """Install the write hooks once, when the first cache is built.
212
+
213
+ Done lazily so importing the auth middleware stays free of side effects.
214
+ """
215
+ global _listening # noqa: PLW0603
216
+ if _listening:
217
+ return
218
+ event.listen(Session, "after_flush", _collect)
219
+ event.listen(Session, "do_orm_execute", _collect_bulk)
220
+ event.listen(Session, "after_commit", _apply)
221
+ event.listen(Session, "after_rollback", _discard)
222
+ _listening = True