reactiveadmin 0.2.0

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 (260) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +88 -0
  3. data/LICENSE +21 -0
  4. data/README.md +81 -0
  5. data/app/assets/reactive_admin/bridge.js +89 -0
  6. data/app/controllers/reactive_admin/api_controller.rb +30 -0
  7. data/app/controllers/reactive_admin/client_errors_controller.rb +38 -0
  8. data/app/controllers/reactive_admin/manifest_controller.rb +10 -0
  9. data/app/controllers/reactive_admin/mcp_controller.rb +48 -0
  10. data/app/controllers/reactive_admin/openapi_controller.rb +13 -0
  11. data/app/controllers/reactive_admin/session_controller.rb +11 -0
  12. data/app/views/layouts/reactive_admin/embed.html.erb +30 -0
  13. data/lib/generators/reactiveadmin/install/install_generator.rb +341 -0
  14. data/lib/generators/reactiveadmin/install/templates/menu.rb.tt +25 -0
  15. data/lib/generators/reactiveadmin/install/templates/reactive_admin.rb.tt +53 -0
  16. data/lib/generators/reactiveadmin/install/templates/reactive_admin_annotated.rb.tt +110 -0
  17. data/lib/reactive_admin/aa/v3/controller.rb +76 -0
  18. data/lib/reactive_admin/aa/v3/forms.rb +29 -0
  19. data/lib/reactive_admin/aa/v3/inputs/filters/typeahead_input.rb +51 -0
  20. data/lib/reactive_admin/aa/v3/inputs/typeahead_input.rb +8 -0
  21. data/lib/reactive_admin/aa/v3/install.rb +36 -0
  22. data/lib/reactive_admin/aa/v3/menu.rb +67 -0
  23. data/lib/reactive_admin/aa/v3/presenters.rb +102 -0
  24. data/lib/reactive_admin/aa/v3/registry.rb +78 -0
  25. data/lib/reactive_admin/aa/v3/views.rb +63 -0
  26. data/lib/reactive_admin/aa/v3.rb +23 -0
  27. data/lib/reactive_admin/aa/v4.rb +59 -0
  28. data/lib/reactive_admin/aa.rb +46 -0
  29. data/lib/reactive_admin/action_items.rb +39 -0
  30. data/lib/reactive_admin/action_links.rb +197 -0
  31. data/lib/reactive_admin/action_safety.rb +19 -0
  32. data/lib/reactive_admin/actions.rb +95 -0
  33. data/lib/reactive_admin/api_errors.rb +116 -0
  34. data/lib/reactive_admin/api_fallback.rb +15 -0
  35. data/lib/reactive_admin/api_guards.rb +445 -0
  36. data/lib/reactive_admin/audit.rb +72 -0
  37. data/lib/reactive_admin/auth/guard.rb +68 -0
  38. data/lib/reactive_admin/auth/token_requests.rb +15 -0
  39. data/lib/reactive_admin/auth.rb +135 -0
  40. data/lib/reactive_admin/authorizer.rb +47 -0
  41. data/lib/reactive_admin/background_requests.rb +33 -0
  42. data/lib/reactive_admin/batch_actions.rb +57 -0
  43. data/lib/reactive_admin/choices.rb +289 -0
  44. data/lib/reactive_admin/client_error.rb +70 -0
  45. data/lib/reactive_admin/composite_keys.rb +12 -0
  46. data/lib/reactive_admin/configuration.rb +221 -0
  47. data/lib/reactive_admin/controller_extension.rb +229 -0
  48. data/lib/reactive_admin/csv_injection.rb +26 -0
  49. data/lib/reactive_admin/date_bound.rb +31 -0
  50. data/lib/reactive_admin/degradation.rb +72 -0
  51. data/lib/reactive_admin/diagnostics.rb +16 -0
  52. data/lib/reactive_admin/doctor.rb +466 -0
  53. data/lib/reactive_admin/dry_run.rb +147 -0
  54. data/lib/reactive_admin/dry_run_flag.rb +18 -0
  55. data/lib/reactive_admin/embed.rb +73 -0
  56. data/lib/reactive_admin/engine.rb +47 -0
  57. data/lib/reactive_admin/error_keys.rb +23 -0
  58. data/lib/reactive_admin/exposure.rb +86 -0
  59. data/lib/reactive_admin/filters.rb +165 -0
  60. data/lib/reactive_admin/fixtures/scrubber.rb +1075 -0
  61. data/lib/reactive_admin/fixtures.rb +161 -0
  62. data/lib/reactive_admin/form_content.rb +78 -0
  63. data/lib/reactive_admin/form_field.rb +279 -0
  64. data/lib/reactive_admin/form_has_many.rb +116 -0
  65. data/lib/reactive_admin/form_lock.rb +71 -0
  66. data/lib/reactive_admin/form_payload.rb +57 -0
  67. data/lib/reactive_admin/form_recorder.rb +192 -0
  68. data/lib/reactive_admin/form_schema.rb +160 -0
  69. data/lib/reactive_admin/frame.rb +97 -0
  70. data/lib/reactive_admin/html_nodes.rb +390 -0
  71. data/lib/reactive_admin/html_policy.rb +338 -0
  72. data/lib/reactive_admin/html_rich.rb +186 -0
  73. data/lib/reactive_admin/implicit_defaults.rb +102 -0
  74. data/lib/reactive_admin/index_options.rb +41 -0
  75. data/lib/reactive_admin/index_payload.rb +259 -0
  76. data/lib/reactive_admin/index_recorder.rb +115 -0
  77. data/lib/reactive_admin/index_views.rb +85 -0
  78. data/lib/reactive_admin/inline_style.rb +125 -0
  79. data/lib/reactive_admin/labels_payload.rb +34 -0
  80. data/lib/reactive_admin/ladder.rb +268 -0
  81. data/lib/reactive_admin/layout_classes.rb +167 -0
  82. data/lib/reactive_admin/legacy_inventory.rb +547 -0
  83. data/lib/reactive_admin/location.rb +22 -0
  84. data/lib/reactive_admin/lookup_audit.rb +30 -0
  85. data/lib/reactive_admin/lookup_payload.rb +41 -0
  86. data/lib/reactive_admin/manifest.rb +36 -0
  87. data/lib/reactive_admin/masked_json.rb +62 -0
  88. data/lib/reactive_admin/masking.rb +100 -0
  89. data/lib/reactive_admin/mcp/access.rb +111 -0
  90. data/lib/reactive_admin/mcp/api.rb +123 -0
  91. data/lib/reactive_admin/mcp/count_tool.rb +22 -0
  92. data/lib/reactive_admin/mcp/layout.rb +175 -0
  93. data/lib/reactive_admin/mcp/output.rb +46 -0
  94. data/lib/reactive_admin/mcp/prompts.rb +111 -0
  95. data/lib/reactive_admin/mcp/server.rb +134 -0
  96. data/lib/reactive_admin/mcp/shapes.rb +164 -0
  97. data/lib/reactive_admin/mcp/tools.rb +386 -0
  98. data/lib/reactive_admin/mcp.rb +53 -0
  99. data/lib/reactive_admin/media_nodes.rb +34 -0
  100. data/lib/reactive_admin/menu.rb +90 -0
  101. data/lib/reactive_admin/menu_overlay.rb +291 -0
  102. data/lib/reactive_admin/node_registry.rb +47 -0
  103. data/lib/reactive_admin/open_api/builder.rb +156 -0
  104. data/lib/reactive_admin/open_api/context.rb +46 -0
  105. data/lib/reactive_admin/open_api/core.rb +51 -0
  106. data/lib/reactive_admin/open_api/operation_ids.rb +18 -0
  107. data/lib/reactive_admin/open_api/page_doc.rb +75 -0
  108. data/lib/reactive_admin/open_api/parts.rb +86 -0
  109. data/lib/reactive_admin/open_api/resource_doc.rb +423 -0
  110. data/lib/reactive_admin/open_api/security.rb +55 -0
  111. data/lib/reactive_admin/open_api/write_schema.rb +104 -0
  112. data/lib/reactive_admin/open_api.rb +41 -0
  113. data/lib/reactive_admin/option_source.rb +36 -0
  114. data/lib/reactive_admin/option_sources.rb +14 -0
  115. data/lib/reactive_admin/options_payload.rb +61 -0
  116. data/lib/reactive_admin/page_controller_extension.rb +112 -0
  117. data/lib/reactive_admin/page_forms.rb +181 -0
  118. data/lib/reactive_admin/page_payload.rb +120 -0
  119. data/lib/reactive_admin/param_normalizer.rb +89 -0
  120. data/lib/reactive_admin/paths.rb +63 -0
  121. data/lib/reactive_admin/permissions.rb +31 -0
  122. data/lib/reactive_admin/provenance.rb +57 -0
  123. data/lib/reactive_admin/query_guard.rb +108 -0
  124. data/lib/reactive_admin/ransack_guard.rb +107 -0
  125. data/lib/reactive_admin/rate_limit.rb +59 -0
  126. data/lib/reactive_admin/reactive_dsl.rb +99 -0
  127. data/lib/reactive_admin/readiness.rb +189 -0
  128. data/lib/reactive_admin/registry.rb +69 -0
  129. data/lib/reactive_admin/resource_meta.rb +120 -0
  130. data/lib/reactive_admin/resource_summary.rb +41 -0
  131. data/lib/reactive_admin/routes.rb +60 -0
  132. data/lib/reactive_admin/row_errors.rb +29 -0
  133. data/lib/reactive_admin/rspec.rb +116 -0
  134. data/lib/reactive_admin/scrubbed_error.rb +22 -0
  135. data/lib/reactive_admin/search.rb +79 -0
  136. data/lib/reactive_admin/server_timing.rb +31 -0
  137. data/lib/reactive_admin/show_payload.rb +88 -0
  138. data/lib/reactive_admin/sidebars.rb +34 -0
  139. data/lib/reactive_admin/site.rb +55 -0
  140. data/lib/reactive_admin/style_report.rb +129 -0
  141. data/lib/reactive_admin/style_sources.rb +83 -0
  142. data/lib/reactive_admin/template_actions.rb +126 -0
  143. data/lib/reactive_admin/template_content.rb +49 -0
  144. data/lib/reactive_admin/template_form.rb +442 -0
  145. data/lib/reactive_admin/test_support.rb +31 -0
  146. data/lib/reactive_admin/typeahead.rb +33 -0
  147. data/lib/reactive_admin/ui/assets.rb +91 -0
  148. data/lib/reactive_admin/ui/client_build.rb +47 -0
  149. data/lib/reactive_admin/ui/helper.rb +24 -0
  150. data/lib/reactive_admin/ui/packaged_client.rb +67 -0
  151. data/lib/reactive_admin/ui/shell.rb +81 -0
  152. data/lib/reactive_admin/ui/switch.rb +38 -0
  153. data/lib/reactive_admin/ui.rb +43 -0
  154. data/lib/reactive_admin/value_payload.rb +147 -0
  155. data/lib/reactive_admin/value_token.rb +36 -0
  156. data/lib/reactive_admin/values.rb +43 -0
  157. data/lib/reactive_admin/version.rb +3 -0
  158. data/lib/reactive_admin/write_audit.rb +60 -0
  159. data/lib/reactive_admin/write_guards.rb +142 -0
  160. data/lib/reactive_admin.rb +153 -0
  161. data/lib/reactiveadmin.rb +1 -0
  162. data/lib/tasks/reactiveadmin.rake +36 -0
  163. data/lib/tasks/reactiveadmin_client.rake +11 -0
  164. data/lib/tasks/reactiveadmin_legacy.rake +7 -0
  165. data/lib/tasks/reactiveadmin_styles.rake +6 -0
  166. data/openapi/core.yaml +1643 -0
  167. data/vendor/client/assets/ActionPage-XUYorI8E.js +1 -0
  168. data/vendor/client/assets/ActionView-BsZFcsgp.js +1 -0
  169. data/vendor/client/assets/CommandPalette-C59HT1ip.js +1 -0
  170. data/vendor/client/assets/DatePicker-DuaK0iMg.js +1 -0
  171. data/vendor/client/assets/DateRangeCalendar-B2BDsG-X.js +1 -0
  172. data/vendor/client/assets/DegradedNotice-DiH5n2DO.js +1 -0
  173. data/vendor/client/assets/FormDialog-pmYl8Eov.js +1 -0
  174. data/vendor/client/assets/FormSkeleton-DuSBZO3C.js +1 -0
  175. data/vendor/client/assets/FrameView-2X8cFvUt.css +1 -0
  176. data/vendor/client/assets/FrameView-zmUeDO8d.js +1 -0
  177. data/vendor/client/assets/GroupOverview-DI5T3k5K.js +1 -0
  178. data/vendor/client/assets/InlineForm-CMEIMgeh.js +1 -0
  179. data/vendor/client/assets/JsonDiff-o7JWr7CH.js +3 -0
  180. data/vendor/client/assets/JsonEditor-D4VXdlEx.js +1 -0
  181. data/vendor/client/assets/JsonView-BrJLDmSN.js +1 -0
  182. data/vendor/client/assets/MobileMenu-GAeFOeEb.js +1 -0
  183. data/vendor/client/assets/Node-SQl61V4K.js +2 -0
  184. data/vendor/client/assets/PageView-C-laNEPZ.js +1 -0
  185. data/vendor/client/assets/ResourceForm-BPjsoCY6.js +1 -0
  186. data/vendor/client/assets/ResourceIndex-COezAw5t.js +3 -0
  187. data/vendor/client/assets/ResourceOrPage-CRZGCY84.js +1 -0
  188. data/vendor/client/assets/ResourceShow-DweRXn18.js +1 -0
  189. data/vendor/client/assets/Segmented-BE9TCbph.js +1 -0
  190. data/vendor/client/assets/Sidebars-CsB9rFqX.js +1 -0
  191. data/vendor/client/assets/breadcrumb-DSA3Tlyd.js +1 -0
  192. data/vendor/client/assets/button-CvZ4_DFC.js +1 -0
  193. data/vendor/client/assets/calendar-BoyMpJIf.js +1 -0
  194. data/vendor/client/assets/check-C5A3J16N.js +1 -0
  195. data/vendor/client/assets/command-CMuk0oAt.js +1 -0
  196. data/vendor/client/assets/dist-CqEI82S_.js +1 -0
  197. data/vendor/client/assets/dist-IW4yX942.js +1 -0
  198. data/vendor/client/assets/editor-yqRLzgsJ.js +2 -0
  199. data/vendor/client/assets/external-link-C2aR4slL.js +1 -0
  200. data/vendor/client/assets/frames-C9gPCc3N.js +1 -0
  201. data/vendor/client/assets/humanize-DtU_Kpr4.js +1 -0
  202. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  203. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  204. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  205. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  206. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  207. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  208. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  209. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  210. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  211. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  212. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  213. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  214. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  215. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  216. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  217. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  218. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  219. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  220. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  221. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  222. data/vendor/client/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  223. data/vendor/client/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  224. data/vendor/client/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  225. data/vendor/client/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  226. data/vendor/client/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  227. data/vendor/client/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  228. data/vendor/client/assets/index-B51aUaAY.js +43 -0
  229. data/vendor/client/assets/index-Cs9rCoWM.css +2 -0
  230. data/vendor/client/assets/input-DByFmQPa.js +1 -0
  231. data/vendor/client/assets/json-De3PN-R6.css +1 -0
  232. data/vendor/client/assets/json-oTp7Q-d-.js +5 -0
  233. data/vendor/client/assets/media-D4a_En8R.js +1 -0
  234. data/vendor/client/assets/plus-CfJ9vo8X.js +1 -0
  235. data/vendor/client/assets/popover-CDtI9R8Q.js +1 -0
  236. data/vendor/client/assets/purify-G7QKJyJq.js +1 -0
  237. data/vendor/client/assets/query-CCsZN2fa.js +1 -0
  238. data/vendor/client/assets/recent-BrzLwL0D.js +1 -0
  239. data/vendor/client/assets/rich-BQc_q5T7.js +1 -0
  240. data/vendor/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  241. data/vendor/client/assets/select-C43qDA3k.js +1 -0
  242. data/vendor/client/assets/sheet-BPl2n-4n.js +1 -0
  243. data/vendor/client/assets/textarea-BnOphXry.js +1 -0
  244. data/vendor/client/assets/uiMode-z0ZbRV49.js +1 -0
  245. data/vendor/client/assets/uiToggle-DwnRQTH1.js +1 -0
  246. data/vendor/client/assets/useRecordForm-X_DExEP2.js +1 -0
  247. data/vendor/client/assets/useRecordVisit-BRtfMi-q.js +1 -0
  248. data/vendor/client/assets/utils-DwBGbDkG.js +1 -0
  249. data/vendor/client/assets/vendor-calendar-nTZiq9oY.js +1 -0
  250. data/vendor/client/assets/vendor-datefns-BoC6MCnl.js +1 -0
  251. data/vendor/client/assets/vendor-forms-D0h8hG_S.js +55 -0
  252. data/vendor/client/assets/vendor-purify-BXoPR7WT.js +3 -0
  253. data/vendor/client/assets/vendor-query-DZ6APRNI.js +1 -0
  254. data/vendor/client/assets/vendor-react-C1iE8mnY.js +9 -0
  255. data/vendor/client/assets/vendor-router-CI6Vh4k_.js +1 -0
  256. data/vendor/client/assets/vendor-table-DuQ835by.js +4 -0
  257. data/vendor/client/index.html +24 -0
  258. data/vendor/client/manifest.json +867 -0
  259. data/vendor/client/reactiveadmin-client.json +4 -0
  260. metadata +350 -0
@@ -0,0 +1,338 @@
1
+ module ReactiveAdmin
2
+ # The one sanitizer policy for server-rendered HTML. `display` is for html nodes inside content;
3
+ # `interactive` is for frame nodes (forms allowed); `neutralize_frame` hardens the body of a frame
4
+ # response. `rake reactiveadmin:html_policy` prints `export` so the client configures DOMPurify
5
+ # from the same lists instead of keeping its own.
6
+ module HtmlPolicy
7
+ VERSION = 6
8
+ # Nokogiri raises past its tree depth, and stored markup can be arbitrarily large: parse under caps and
9
+ # degrade instead of failing the whole response.
10
+ MAX_TREE_DEPTH = 256
11
+ MAX_NODES = 2_000
12
+ MAX_BYTES = 100.kilobytes
13
+ TOO_COMPLEX = "This content is too complex to display".freeze
14
+ URI_SCHEMES = %w[http https mailto tel].freeze
15
+ DISPLAY_TAGS = %w[a abbr acronym address b big blockquote br caption cite code dd del details dfn div dl dt em embed
16
+ h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark object ol p pre samp small span strong sub summary sup table tbody td tfoot
17
+ th thead time tr tt ul var].freeze
18
+ # No class: stored markup must not borrow the host's Tailwind classes to overlay the app.
19
+ DISPLAY_ATTRIBUTES = %w[abbr alt cite data datetime height href lang loading referrerpolicy rel src style
20
+ target title type width xml:lang].freeze
21
+ FORM_TAGS = %w[button datalist fieldset form input label legend optgroup option select textarea].freeze
22
+ FORM_ATTRIBUTES = %w[action autocomplete checked cols data-confirm data-disable-with data-method data-remote disabled
23
+ enctype for id list max maxlength method min minlength multiple novalidate pattern placeholder readonly required rows
24
+ selected step value].freeze
25
+ FRAME_TAGS = (DISPLAY_TAGS + FORM_TAGS).freeze
26
+ # `class` is stripped from frames, so the classic widgets the client replaces are marked with this
27
+ # attribute (value => selector, matched before the strip) instead of being found by class.
28
+ WIDGET_ATTRIBUTE = "data-reactiveadmin-widget".freeze
29
+ WIDGETS = {"date" => "input.datepicker"}.freeze
30
+ FRAME_ATTRIBUTES = (DISPLAY_ATTRIBUTES + FORM_ATTRIBUTES + %w[name] + [WIDGET_ATTRIBUTE]).freeze
31
+ # `name` submits a value only from a form control; anywhere else it is a DOM clobbering hook.
32
+ NAMED_TAGS = %w[button input select textarea].freeze
33
+ # Named access on document and form elements shadows their own properties, so these names are unusable.
34
+ CLOBBERED_NAMES = %w[action body cookie defaultView document domain elements forms head location reset submit URL window].freeze
35
+
36
+ # Tag => the attribute holding its URL. Only the same site (or a configured trusted host) may load them.
37
+ MEDIA = {"img" => "src", "embed" => "src", "object" => "data", "iframe" => "src"}.freeze
38
+ MEDIA_LABELS = {"img" => "External image", "embed" => "External document", "object" => "External document", "iframe" => "External page"}.freeze
39
+ # A same-site embed must declare a safe type and have a matching path; otherwise a same-site HTML page
40
+ # (an admin screen, say) would render inside the frame.
41
+ EMBED_TYPES = %w[application/pdf].freeze
42
+ EMBED_EXTENSIONS = %w[.pdf].freeze
43
+ FORCED_ATTRIBUTES = {"img" => {"referrerpolicy" => "no-referrer", "loading" => "lazy"}}.freeze
44
+ DATA_IMAGE = %r{\Adata:image/(?:png|jpe?g|gif|webp|bmp);base64,[A-Za-z0-9+/=\s]+\z}i
45
+ FRAME_REMOVED_TAGS = %w[script base].freeze
46
+ FRAME_TARGET_ATTRIBUTES = %w[action formaction].freeze
47
+ UNSAFE_URL = /\A(?:javascript|vbscript):/i
48
+ UNSAFE_NAVIGATION_URL = /\A(?:javascript|vbscript|data):/i
49
+
50
+ # Inline styles are held to layout properties with a closed value grammar; each pattern must match the whole
51
+ # value, which is lowercased with whitespace collapsed first. No colors, positioning, stacking, images or url():
52
+ # those turn style into UI redressing or a request channel. The client applies the same table from `export`.
53
+ # No negative lengths (a negative margin pulls content over its neighbours) and no viewport units (vw/vh
54
+ # overlay the page). The digit cap keeps a value from sizing a block past any screen.
55
+ NUMBER = '(?:\d{1,4}(?:\.\d*)?|\.\d+)'
56
+ LENGTH = "(?:0|#{NUMBER}(?:px|em|rem|ch|%))"
57
+ SPACING = "(?:#{LENGTH}|auto)(?: (?:#{LENGTH}|auto)){0,3}"
58
+ PADDING = "#{LENGTH}(?: #{LENGTH}){0,3}"
59
+ GAP = "(?:#{LENGTH}|normal)(?: (?:#{LENGTH}|normal))?"
60
+ ALIGNMENT = "(?:stretch|center|flex-start|flex-end|start|end|baseline|normal)"
61
+ DECORATION = "(?:underline|overline|line-through)"
62
+ STYLE_PROPERTIES = {
63
+ "display" => "(?:block|inline|inline-block|flex|inline-flex|grid|none)",
64
+ "text-align" => "(?:left|right|center|justify|start|end)",
65
+ "vertical-align" => "(?:baseline|top|middle|bottom|text-top|text-bottom|sub|super)",
66
+ "white-space" => "(?:normal|nowrap|pre|pre-wrap|pre-line|break-spaces)",
67
+ "font-weight" => "(?:normal|bold|bolder|lighter|[1-9]00)",
68
+ "font-style" => "(?:normal|italic|oblique)",
69
+ "text-decoration" => "(?:none|#{DECORATION}(?: #{DECORATION}){0,2})",
70
+ "gap" => GAP, "row-gap" => GAP, "column-gap" => GAP,
71
+ "flex" => "(?:none|auto|initial|#{NUMBER}(?: #{NUMBER})?(?: (?:#{LENGTH}|auto|content))?)",
72
+ "flex-direction" => "(?:row|row-reverse|column|column-reverse)",
73
+ "flex-wrap" => "(?:nowrap|wrap|wrap-reverse)",
74
+ "flex-grow" => NUMBER, "flex-shrink" => NUMBER,
75
+ "flex-basis" => "(?:#{LENGTH}|auto|content)",
76
+ "align-items" => ALIGNMENT,
77
+ "align-self" => "(?:auto|#{ALIGNMENT})",
78
+ "justify-content" => "(?:flex-start|flex-end|start|end|center|space-between|space-around|space-evenly|normal)",
79
+ "list-style-type" => "(?:none|disc|circle|square|decimal|lower-alpha|upper-alpha|lower-roman|upper-roman|lower-latin|upper-latin)",
80
+ "border-collapse" => "(?:collapse|separate)",
81
+ "float" => "(?:left|right|none)",
82
+ "clear" => "(?:none|left|right|both)"
83
+ }.merge(
84
+ %w[margin margin-top margin-right margin-bottom margin-left].to_h { [it, SPACING] },
85
+ %w[padding padding-top padding-right padding-bottom padding-left].to_h { [it, PADDING] },
86
+ %w[width min-width max-width height min-height max-height].to_h { [it, "(?:#{LENGTH}|auto|none)"] }
87
+ ).freeze
88
+ STYLE_FORBIDDEN_VALUES = ["url(", "expression", "@import", "\\", "javascript:", "behavior", "-moz-binding", "/*"].freeze
89
+ STYLE_PATTERNS = STYLE_PROPERTIES.transform_values { Regexp.new("\\A(?:#{it})\\z") }.freeze
90
+
91
+ # Scrubs style with the table above instead of Loofah's CSS cleaner, which would let color through and drop gap.
92
+ class StyleScrubber < Rails::HTML::PermitScrubber
93
+ def scrub_css_attribute(node)
94
+ return unless (attribute = node.attribute_nodes.find { it.name == "style" })
95
+
96
+ style = HtmlPolicy.style(attribute.value)
97
+ style.empty? ? attribute.remove : attribute.value = style
98
+ end
99
+ end
100
+
101
+ module_function
102
+
103
+ # Keeps only the allowlisted declarations, normalized to "prop: value; prop: value".
104
+ def style(css)
105
+ css.to_s.split(";").filter_map { style_declaration(it) }.join("; ")
106
+ end
107
+
108
+ def style_declaration(declaration)
109
+ property, value = declaration.split(":", 2)
110
+ return unless value
111
+
112
+ property = tidy(property)
113
+ value = tidy(value)
114
+ return unless STYLE_PATTERNS[property]&.match?(value) && STYLE_FORBIDDEN_VALUES.none? { value.include?(it) }
115
+
116
+ "#{property}: #{value}"
117
+ end
118
+
119
+ # ASCII-only whitespace on purpose: the client must trim exactly the same characters.
120
+ def tidy(text) = text.downcase.gsub(/[ \t\r\n\f]+/, " ").delete_prefix(" ").delete_suffix(" ")
121
+
122
+ def display(html, host: nil, where: nil)
123
+ fragment = parse(html, where:) or return TOO_COMPLEX
124
+ fragment.css("script, style").remove
125
+ restrict_media(fragment, host:, where:)
126
+ allow(fragment.to_html, DISPLAY_TAGS, DISPLAY_ATTRIBUTES)
127
+ end
128
+
129
+ def interactive(html, host: nil, where: nil)
130
+ fragment = parse(html, where:) or return TOO_COMPLEX
131
+ neutralize_frame(fragment, host:, where:)
132
+ allow(fragment.to_html, FRAME_TAGS, FRAME_ATTRIBUTES)
133
+ end
134
+
135
+ # For a whole classic response, which is not cut down to an allowlist: the client sanitizes it again.
136
+ def frame_body(html, host: nil, where: nil)
137
+ fragment = parse(html, where:) or return TOO_COMPLEX
138
+ neutralize_frame(fragment, host:, where:)
139
+ fragment.css("[style]").each { restyle(it) }
140
+ fragment.to_html
141
+ end
142
+
143
+ # nil when the markup is too deep to parse; callers show TOO_COMPLEX instead.
144
+ def parse(html, where: nil)
145
+ truncate_nodes(Nokogiri::HTML5.fragment(truncate_bytes(html.to_s, where:), max_tree_depth: MAX_TREE_DEPTH), where:)
146
+ rescue ArgumentError
147
+ degrade(:html_too_deep, "Markup nests deeper than #{MAX_TREE_DEPTH} elements; not shown", where:)
148
+ nil
149
+ end
150
+
151
+ def truncate_bytes(html, where:)
152
+ return html if html.bytesize <= MAX_BYTES
153
+
154
+ degrade(:html_truncated, "Truncated html beyond #{MAX_BYTES} bytes", where:)
155
+ html.byteslice(0, MAX_BYTES).scrub("")
156
+ end
157
+
158
+ def truncate_nodes(fragment, where:)
159
+ extra = fragment.xpath(".//*").drop(MAX_NODES)
160
+ return fragment if extra.empty?
161
+
162
+ extra.each(&:remove)
163
+ degrade(:html_truncated, "Kept the first #{MAX_NODES} elements of html", where:)
164
+ fragment
165
+ end
166
+
167
+ # What the client needs to build the same DOMPurify configuration; see the rake task.
168
+ def export
169
+ {
170
+ version: VERSION,
171
+ style: {properties: STYLE_PROPERTIES, forbidden_values: STYLE_FORBIDDEN_VALUES},
172
+ display: {
173
+ tags: DISPLAY_TAGS, attributes: DISPLAY_ATTRIBUTES, uri_schemes: URI_SCHEMES, trusted_hosts: trusted_hosts,
174
+ embed: {types: EMBED_TYPES, extensions: EMBED_EXTENSIONS},
175
+ media: MEDIA.to_h { |tag, attribute| [tag, {attribute:, same_origin: true, data_image: tag == "img", forced_attributes: FORCED_ATTRIBUTES[tag]}.compact] }
176
+ },
177
+ frame: {
178
+ tags: FRAME_TAGS, attributes: FRAME_ATTRIBUTES, uri_schemes: URI_SCHEMES, trusted_hosts: trusted_hosts,
179
+ removed_tags: FRAME_REMOVED_TAGS, same_origin_attributes: FRAME_TARGET_ATTRIBUTES,
180
+ named_tags: NAMED_TAGS, clobbered_names: CLOBBERED_NAMES,
181
+ widget_attribute: WIDGET_ATTRIBUTE, widgets: WIDGETS,
182
+ media_tags: MEDIA.keys, forced_attributes: FORCED_ATTRIBUTES
183
+ }
184
+ }
185
+ end
186
+
187
+ # Relative URLs and the request's own host (and configured trusted hosts) count as the same site. A scheme
188
+ # must be followed by a host (`https:evil.test` and `http:/evil.test` are not relative), and `//` is
189
+ # protocol-relative, so neither can be same-site.
190
+ def same_origin?(url, host)
191
+ url = url.to_s.strip
192
+ return false if url.match?(/[\u0000- \u007f\\]/)
193
+
194
+ uri = URI.parse(url)
195
+ if uri.scheme
196
+ %w[http https].include?(uri.scheme.downcase) && uri.host.present? && trusted_host?(uri.host, host)
197
+ else
198
+ !url.start_with?("//")
199
+ end
200
+ rescue URI::InvalidURIError
201
+ false
202
+ end
203
+
204
+ def trusted_host?(hostname, host) = [host, *trusted_hosts].compact.any? { hostname.casecmp?(it) }
205
+
206
+ def trusted_hosts
207
+ hosts = ReactiveAdmin.config.html_trusted_hosts
208
+ Array(hosts.respond_to?(:call) ? hosts.call : hosts).map(&:to_s)
209
+ end
210
+
211
+ # :keep, :drop, or [label, href] for a link that stands in for the element. A same-site
212
+ # iframe is also a link here; HtmlNodes turns one into an iframe node instead.
213
+ def media(el, host:)
214
+ src = source(el)
215
+ return ["Embedded page", src] if el.name == "iframe" && same_origin?(src, host)
216
+ return :keep if loadable?(el, src, host)
217
+
218
+ src.match?(%r{\A(?:https?:)?//[^\s]+\z}i) ? [MEDIA_LABELS[el.name], src] : :drop
219
+ end
220
+
221
+ def source(el) = el[MEDIA.fetch(el.name)].to_s.strip
222
+
223
+ def loadable?(el, src, host)
224
+ case el.name
225
+ when "img" then src.match?(DATA_IMAGE) || same_origin?(src, host)
226
+ when "embed", "object" then same_origin?(src, host) && pdf?(el, src)
227
+ else same_origin?(src, host)
228
+ end
229
+ end
230
+
231
+ # A configured trusted host may serve a PDF from an extensionless URL (signed CDN links); same-site paths may not.
232
+ def pdf?(el, src)
233
+ EMBED_TYPES.include?(el["type"].to_s.strip.downcase) && (pdf_path?(src) || trusted_url?(src))
234
+ end
235
+
236
+ def pdf_path?(src) = EMBED_EXTENSIONS.any? { src.split(/[?#]/).first.to_s.downcase.end_with?(it) }
237
+
238
+ # Absolute http(s) on a configured trusted host, as opposed to this site's own.
239
+ def trusted_url?(url) = url.to_s.strip.match?(%r{\Ahttps?://}i) && same_origin?(url, nil)
240
+
241
+ def restrict_media(fragment, host:, where:)
242
+ fragment.xpath("descendant-or-self::*[not(self::img)]/@referrerpolicy | descendant-or-self::*[not(self::img)]/@loading").remove
243
+ fragment.css(MEDIA.keys.join(",")).each do |el|
244
+ case (decision = media(el, host:))
245
+ when :keep then force(el, FORCED_ATTRIBUTES.fetch(el.name, {}))
246
+ when :drop then el.remove
247
+ else
248
+ el.replace(external_link(el.document, *decision))
249
+ degrade(:external_media_blocked, "Replaced an external image or document with a link", where:)
250
+ end
251
+ end
252
+ end
253
+
254
+ def force(el, attributes) = attributes.each { |name, value| el[name] = value }
255
+
256
+ def external_link(document, label, href)
257
+ Nokogiri::XML::Node.new("a", document).tap do |a|
258
+ a["href"] = href
259
+ a["target"] = "_blank"
260
+ a["rel"] = "noopener noreferrer"
261
+ a.content = label
262
+ end
263
+ end
264
+
265
+ def neutralize_frame(fragment, host:, where:)
266
+ fragment.css(FRAME_REMOVED_TAGS.join(",")).remove
267
+ fragment.css("meta[http-equiv]").remove
268
+ fragment.xpath(".//@*[starts-with(local-name(), 'on')] | .//@srcdoc").remove
269
+ fragment.xpath(".//@*").each { it.remove if unsafe_url?(it) }
270
+ clobbering_names(fragment)
271
+ mark_widgets(fragment)
272
+ offsite_targets(fragment, host:, where:)
273
+ fragment.css("img").each { force(it, FORCED_ATTRIBUTES.fetch("img")) }
274
+ end
275
+
276
+ # Markup can't claim a widget itself: the attribute is dropped everywhere, then set from the table.
277
+ def mark_widgets(fragment)
278
+ fragment.xpath(".//@#{WIDGET_ATTRIBUTE}").remove
279
+ WIDGETS.each { |widget, selector| fragment.css(selector).each { it[WIDGET_ATTRIBUTE] = widget } }
280
+ end
281
+
282
+ def clobbering_names(fragment)
283
+ fragment.css("[name]").each { it.remove_attribute("name") unless NAMED_TAGS.include?(it.name) }
284
+ fragment.css("[name], [id]").each do |el|
285
+ %w[name id].each do |attribute|
286
+ el.remove_attribute(attribute) if CLOBBERED_NAMES.any? { |name| name.casecmp?(el[attribute].to_s) }
287
+ end
288
+ end
289
+ end
290
+
291
+ def unsafe_url?(attribute)
292
+ return false unless %w[href src action formaction data poster].include?(attribute.name)
293
+
294
+ # Browsers ignore whitespace and control characters inside a scheme.
295
+ value = attribute.value.to_s.gsub(/[\u0000- ]/, "")
296
+ value.match?(%w[href action formaction].include?(attribute.name) ? UNSAFE_NAVIGATION_URL : UNSAFE_URL)
297
+ end
298
+
299
+ # Links to other sites stay (a click is the user's choice); what submits or loads is held to this site.
300
+ def offsite_targets(fragment, host:, where:)
301
+ fragment.xpath(".//@action | .//@formaction | descendant-or-self::*[not(self::a)]/@href").each do |attribute|
302
+ next if same_origin?(attribute.value, host)
303
+
304
+ attribute.value = "#"
305
+ degrade(:frame_offsite_target, "Replaced a form or link target that points off this site", where:)
306
+ end
307
+ fragment.css("iframe, embed, object").each do |el|
308
+ next if loadable?(el, source(el), host)
309
+
310
+ el.remove
311
+ degrade(:frame_offsite_target, "Removed embedded content that points off this site", where:)
312
+ end
313
+ fragment.css("input[src]").each do |el|
314
+ next if same_origin?(el["src"], host)
315
+
316
+ el.remove_attribute("src")
317
+ degrade(:frame_offsite_target, "Removed an image button source that points off this site", where:)
318
+ end
319
+ fragment.css("a[href]").each { it["rel"] = "noopener noreferrer" unless same_origin?(it["href"], host) }
320
+ end
321
+
322
+ def allow(html, tags, attributes)
323
+ scrubber = StyleScrubber.new
324
+ scrubber.tags = tags
325
+ scrubber.attributes = attributes
326
+ Rails::HTML5::SafeListSanitizer.new.sanitize(html, scrubber:).to_s
327
+ end
328
+
329
+ def restyle(el)
330
+ css = style(el["style"])
331
+ css.empty? ? el.remove_attribute("style") : el["style"] = css
332
+ end
333
+
334
+ def degrade(kind, reason, where: nil)
335
+ Degradation.record(kind:, where: Degradation.where(where.presence).presence, reason:)
336
+ end
337
+ end
338
+ end
@@ -0,0 +1,186 @@
1
+ module ReactiveAdmin
2
+ # Rich-text HTML as typed nodes: headings, paragraphs with inline marks, rules, quotes, disclosures,
3
+ # lists and definition lists. Mixed into HtmlNodes, which owns the walk and the sanitized fallback.
4
+ module HtmlRich
5
+ MARKS = {
6
+ "b" => "strong", "strong" => "strong", "i" => "em", "em" => "em", "u" => "underline", "ins" => "underline",
7
+ "s" => "strike", "strike" => "strike", "del" => "strike", "code" => "code", "kbd" => "code", "samp" => "code",
8
+ "mark" => "mark", "small" => "small", "sub" => "sub", "sup" => "sup"
9
+ }.freeze
10
+ HEADINGS = %w[h1 h2 h3 h4 h5 h6].freeze
11
+ BLOCKS = (HEADINGS + %w[hr dl blockquote details ul ol li]).freeze
12
+ SPACE = /[ \t\r\n\f]+/
13
+
14
+ private
15
+
16
+ # A lone `<code>` is a code node, and a `<p>` with plain text or layout classes is a text or box node.
17
+ def rich?(el)
18
+ case el.name
19
+ when "p" then el.element_children.any? && layout_hints(el).empty?
20
+ when "code" then false
21
+ else BLOCKS.include?(el.name) || MARKS.key?(el.name) || el.name == "abbr"
22
+ end
23
+ end
24
+
25
+ def rich(el)
26
+ if el.name == "hr" then {type: "divider"}
27
+ elsif HEADINGS.include?(el.name) then inline_container("heading", el, level: el.name[1].to_i)
28
+ elsif el.name == "p" then inline_container("paragraph", el)
29
+ elsif el.name == "blockquote" then {type: "blockquote", children: nodes(el.inner_html)}
30
+ elsif el.name == "details" then disclosure(el)
31
+ elsif el.name == "dl" then definition_list(el)
32
+ elsif el.name == "li" then list(false, [[el, 0]])
33
+ elsif %w[ul ol].include?(el.name) then list(el.name == "ol", el.children.each_with_index.to_a)
34
+ else run([[el, 0]])
35
+ end
36
+ end
37
+
38
+ def inline_container(type, el, **attrs)
39
+ children = tidy(inline(el.children.each_with_index.to_a))
40
+ {type:, **attrs, children:} if children.any?
41
+ end
42
+
43
+ def disclosure(el)
44
+ summary = el.element_children.find { it.name == "summary" }
45
+ title = summary ? tidy(inline(summary.children.each_with_index.to_a)) : []
46
+ body = el.children.reject { it == summary }
47
+ {type: "disclosure", summary_nodes: title.presence || [{type: "text", text: "Details"}], open: el.key?("open"), children: nodes(body.map(&:to_html).join)}
48
+ end
49
+
50
+ def definition_list(el)
51
+ rows = []
52
+ each_term_or_detail(el) do |child|
53
+ rows << {label: "", value: []} if rows.empty? || child.name == "dt"
54
+ (child.name == "dt") ? rows.last[:label] = child.text.squish : rows.last[:value].concat(nodes(child.inner_html))
55
+ end
56
+ return if rows.empty?
57
+
58
+ {type: "definition_list", rows: rows.map { it.merge(value: it[:value].presence || [{type: "empty"}]) }}
59
+ end
60
+
61
+ def each_term_or_detail(el, &)
62
+ el.element_children.each do |child|
63
+ (child.name == "div") ? each_term_or_detail(child, &) : (yield child if %w[dt dd].include?(child.name))
64
+ end
65
+ end
66
+
67
+ # Anything under ul/ol becomes an item, so stray non-li children still render.
68
+ def list(ordered, children)
69
+ items = children.filter_map do |child, index|
70
+ next if child.comment? || (child.text? && child.text.strip.empty?)
71
+
72
+ at("#{child.name}[#{index}]") do
73
+ content = (child.name == "li") ? nodes(child.inner_html) : [node(child)].compact
74
+ {type: "list_item", children: content}
75
+ end
76
+ end
77
+ {type: "list", ordered:, children: items}
78
+ end
79
+
80
+ # Siblings in document order. Inline runs that carry formatting become paragraphs; loose `li`s are gathered into
81
+ # a list; everything else is walked one node at a time.
82
+ def siblings(children)
83
+ groups(children.each_with_index.reject { |el, _| el.comment? }).flat_map do |kind, items|
84
+ case kind
85
+ when :run then run(items)
86
+ when :li then list(false, items)
87
+ else at("#{items.first.first.name}[#{items.first.last}]") { node(items.first.first) }
88
+ end
89
+ end.compact
90
+ end
91
+
92
+ def groups(items)
93
+ items.each_with_object([]) do |item, groups|
94
+ el = item.first
95
+ kind = if el.text? && el.text.strip.empty? then :blank
96
+ elsif el.element? && el.name == "li" then :li
97
+ elsif inline?(el) then :run
98
+ else :other
99
+ end
100
+ last = groups.last
101
+ if kind == :blank
102
+ last&.last&.push(item) if last&.first&.in?(%i[run li])
103
+ elsif last && last.first == kind && kind != :other
104
+ last.last << item
105
+ else
106
+ groups << [kind, [item]]
107
+ end
108
+ end
109
+ end
110
+
111
+ def inline?(el)
112
+ return true if el.text? || el.cdata?
113
+ return false unless el.element?
114
+
115
+ MARKS.key?(el.name) || %w[abbr br].include?(el.name) || (el.name == "a" && !ActionLinks.control?(el)) ||
116
+ (el.name == "span" && el["class"].blank? && el["style"].blank? && !ActionLinks.control?(el))
117
+ end
118
+
119
+ # A run with no formatting keeps the plain per-node output. A lone `<code>` stays a code node.
120
+ def run(items)
121
+ tags = items.map(&:first).select(&:element?).map(&:name)
122
+ surrounded = items.any? { |el, _| el.text? ? el.text.strip.present? : el.element? && el.name != "code" }
123
+ formatted = tags.any? { (MARKS.key?(it) && it != "code") || it == "abbr" } || (tags.include?("code") && surrounded)
124
+ return items.filter_map { |el, index| at("#{el.name}[#{index}]") { node(el) } } unless formatted
125
+
126
+ list = tidy(inline(items))
127
+ (list.size == 1 && list.first[:type] == "text") ? list : [paragraph(list)].compact
128
+ end
129
+
130
+ def paragraph(children) = ({type: "paragraph", children:} if children.any?)
131
+
132
+ def inline(items, marks: [], title: nil)
133
+ items.flat_map do |el, index|
134
+ if el.text? || el.cdata? then segment(el.text, marks, title)
135
+ elsif !el.element? then []
136
+ elsif el.name == "br" then [{type: "break"}]
137
+ elsif MARKS.key?(el.name) then inline(indexed(el), marks: (marks + [MARKS[el.name]]).uniq, title:)
138
+ elsif el.name == "abbr" then inline(indexed(el), marks:, title: el["title"].presence || title)
139
+ elsif el.name == "span" && el["class"].blank? && el["style"].blank? then inline(indexed(el), marks:, title:)
140
+ else
141
+ typed = at("#{el.name}[#{index}]") { node(el) }
142
+ (typed && typed[:type] == "text" && marks.any?) ? [typed.merge(marks:)] : [typed].compact
143
+ end
144
+ end
145
+ end
146
+
147
+ def indexed(el) = el.children.each_with_index.to_a
148
+
149
+ def segment(string, marks, title)
150
+ string = string.gsub(SPACE, " ")
151
+ string.empty? ? [] : [{type: "text", text: string, marks: marks.presence, title:}.compact]
152
+ end
153
+
154
+ # Spacing inside a run collapses like HTML's: no leading, trailing or doubled spaces, none around a break.
155
+ def tidy(list)
156
+ space = true
157
+ list.each_with_object([]) do |node, out|
158
+ if node[:type] == "text"
159
+ text = space ? node[:text].delete_prefix(" ") : node[:text]
160
+ next if text.empty?
161
+
162
+ space = text.end_with?(" ")
163
+ node = node.merge(text:)
164
+ last = out.last
165
+ if last && last[:type] == "text" && last.except(:text) == node.except(:text)
166
+ out[-1] = last.merge(text: last[:text] + text)
167
+ else
168
+ out << node
169
+ end
170
+ else
171
+ trim_end(out) if node[:type] == "break"
172
+ space = node[:type] == "break"
173
+ out << node
174
+ end
175
+ end.tap { trim_end(it) }
176
+ end
177
+
178
+ def trim_end(out)
179
+ last = out.last
180
+ return unless last && last[:type] == "text" && last[:text].end_with?(" ")
181
+
182
+ trimmed = last[:text].chomp(" ")
183
+ trimmed.empty? ? out.pop : out[-1] = last.merge(text: trimmed)
184
+ end
185
+ end
186
+ end
@@ -0,0 +1,102 @@
1
+ module ReactiveAdmin
2
+ # The columns a resource shows when it declares no `index`/`show` block. AA would render every
3
+ # content column; under `config.implicit_defaults = :secure` credentials and binary data stay out,
4
+ # and json and free text, which may hold sensitive data, are shown the way explicit json is: summarized or
5
+ # truncated, with the full value one audited `_value` call away. An explicit block is the host's
6
+ # deliberate choice and is never filtered.
7
+ module ImplicitDefaults
8
+ HIDDEN_TYPES = %i[binary].freeze
9
+ TEXT_PREVIEW = 120
10
+ REASON = "column hidden by secure defaults".freeze
11
+
12
+ # Extended onto the show view: rows of default text columns become truncated text nodes.
13
+ module Display
14
+ attr_writer :reactiveadmin_implicit_text
15
+
16
+ def format_attribute(resource, attr)
17
+ config = @reactiveadmin_value_config
18
+ return super unless @reactiveadmin_implicit_text&.include?(attr.to_s) && resource.instance_of?(config.resource_class)
19
+
20
+ value = AA.find_value(self, resource, attr)
21
+ return super unless value.is_a?(String)
22
+
23
+ reactiveadmin_attributes << attr.to_s
24
+ source = ValuePayload::Source.new(config:, record: resource, field: attr.to_s, controller:, via: "show")
25
+ NodeRegistry.marker(ImplicitDefaults.text_node(value, source, inline: true))
26
+ end
27
+ end
28
+
29
+ class << self
30
+ def secure? = ReactiveAdmin.config.implicit_defaults == :secure
31
+
32
+ def strict? = ReactiveAdmin.config.strict_defaults
33
+
34
+ # [visible columns, [[name, kind]] hidden], as AA's `resource_columns` would list them.
35
+ def split(config)
36
+ columns = config.resource_columns
37
+ return [columns, []] unless secure?
38
+
39
+ hidden = columns.filter_map { |key| (kind = kind(config, key)) && [key.to_s, kind] }
40
+ [columns.reject { |key| hidden.assoc(key.to_s) }, hidden]
41
+ end
42
+
43
+ # The visible default columns; every hidden one is recorded as degraded for `where` (index or
44
+ # show), except those the host masked on purpose: that is a decision, not a gap.
45
+ def columns(config, where:)
46
+ columns, hidden = split(config)
47
+ hidden.reject { |name, _| Masking.explicit?(name, config) }.each { |name, kind| record(where, "#{kind} #{REASON}: #{name}") }
48
+ columns
49
+ end
50
+
51
+ def hidden?(config, key) = secure? && !!kind(config, key)
52
+
53
+ # Names of the visible text columns that secure defaults show truncated.
54
+ def text_columns(config)
55
+ return [] unless secure?
56
+
57
+ split(config).first.map(&:to_s).select { text_column?(config, it) }
58
+ end
59
+
60
+ # A plain text column: the only kind `_value` returns as a string.
61
+ def text_column?(config, field) = config.resource_class.columns_hash[field.to_s]&.type == :text && kind(config, field).nil?
62
+
63
+ # The text a default column shows: all of it when short enough (on show, up to
64
+ # `inline_text_limit`; anywhere, up to the preview), else the start and a way to the rest.
65
+ def text_node(value, source, inline:)
66
+ text = value.to_s
67
+ return {type: "empty"} if text.strip.empty?
68
+ return {type: "text", text:} if text.length <= TEXT_PREVIEW || (inline && text.bytesize <= ReactiveAdmin.config.inline_text_limit)
69
+
70
+ {type: "text", text: text.first(TEXT_PREVIEW), truncated: true, expand_path: ValuePayload.expand_path(source)}.compact
71
+ end
72
+
73
+ def blocked(where) = record(where, "no #{where} block declared and strict_defaults is on", kind: "implicit_view_blocked")
74
+
75
+ # Hidden column names per section that falls back to defaults, for `doctor`. An API export without a `csv`
76
+ # block takes a table index's columns, so it falls back only when the index does too.
77
+ def audit(config)
78
+ index = IndexViews.new(config)
79
+ {index: !index.presenter&.block, show: !AA.page_presenter(config, :show)&.block, csv: AA.default_csv?(config) && !IndexViews.table_with_block(config)}
80
+ .select { |_, implicit| implicit }
81
+ .transform_values { split(config).last.map(&:first) }
82
+ end
83
+
84
+ private
85
+
86
+ def kind(config, key)
87
+ name = key.to_s
88
+ klass = config.resource_class
89
+ type = klass.columns_hash[name]&.type
90
+ if Array(klass.try(:encrypted_attributes)).map(&:to_s).include?(name) then "encrypted"
91
+ elsif AA.filter_attributes.map(&:to_s).include?(name) then "filtered"
92
+ elsif Masking.attribute?(name, config) then "masked"
93
+ elsif HIDDEN_TYPES.include?(type) then type.to_s
94
+ end
95
+ end
96
+
97
+ def record(where, reason, kind: "implicit_column_hidden")
98
+ Degradation.record(kind:, where:, reason:)
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,41 @@
1
+ module ReactiveAdmin
2
+ # Which index options a resource uses, for the doctor: what its registration declares, and
3
+ # what a sampled index response shows of the index block (which only a run reveals).
4
+ module IndexOptions
5
+ PRESENTER_OPTIONS = %i[title blank_slate_link row_class per_page paginator download_links pagination_total scope_count].freeze
6
+
7
+ module_function
8
+
9
+ def declared(config)
10
+ presenters = presenters(config)
11
+ sidebars = AA.sidebar_sections(config).reject { Sidebars::BUILT_IN.include?(it.name) }
12
+ {
13
+ scope_groups: AA.scopes(config).filter_map(&:group).uniq.size,
14
+ sidebars: sidebars.size,
15
+ extra_views: (presenters.size - 1 if presenters.size > 1),
16
+ custom_index_as: presenters.count { IndexViews.custom?(it[:as]) },
17
+ check_boxes_filters: AA.filters(config).count { |_, opts| opts[:as] == :check_boxes },
18
+ order_by: config.ordering.size,
19
+ **PRESENTER_OPTIONS.to_h { |option| [option, presenters.count { it.has_key?(option) }] }
20
+ }.reject { |_, count| count.to_i.zero? }
21
+ end
22
+
23
+ def sampled(payload)
24
+ meta = payload["meta"]
25
+ columns = payload["columns"]
26
+ {
27
+ default_actions_off: (1 if meta["default_row_actions"] == false && meta["view"] == "table"),
28
+ row_actions_menu: (1 if meta["row_actions_dropdown"]),
29
+ index_column: columns.count { it["kind"] == "index" },
30
+ column_classes: columns.count { it["class_name"] },
31
+ aligned_columns: columns.count { it["align"] },
32
+ row_tones: payload["rows"].count { it["tone"] }
33
+ }.reject { |_, count| count.to_i.zero? }
34
+ end
35
+
36
+ def presenters(config)
37
+ list = AA.index_presenters(config)
38
+ list.is_a?(Hash) ? list.values : Array(list)
39
+ end
40
+ end
41
+ end