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,386 @@
1
+ module ReactiveAdmin
2
+ module Mcp
3
+ # The tool set is generic: a dozen tools that take a resource key, not one tool per operation, so
4
+ # the list stays small however many resources the host registers. Each tool is a thin translation
5
+ # onto an API route; what the caller may see or do is decided there.
6
+ module Tools
7
+ Tool = Data.define(:name, :title, :description, :properties, :required, :annotations, :write, :fit, :offered, :handler) do
8
+ def schema = {type: "object", properties:, required:, additionalProperties: false}
9
+
10
+ # Whether some resource's MCP mode leaves this tool anything to do.
11
+ def offered? = offered.nil? || offered.call
12
+
13
+ def definition = {name:, title:, description:, inputSchema: schema, annotations:}
14
+ end
15
+
16
+ # What a handler works with: the API, and the paths and limits derived from the registry.
17
+ class Context
18
+ attr_reader :api
19
+
20
+ def initialize(api) = @api = api
21
+
22
+ def limit = ReactiveAdmin.config.mcp.max_response_bytes
23
+
24
+ # A resource left out of MCP is answered exactly like one that doesn't exist.
25
+ def config_for(args)
26
+ config = Registry.find(args["resource"].to_s)
27
+ return config if config && Access.visible?(config)
28
+
29
+ raise ToolError.new("Unknown resource #{args["resource"].to_s.first(60).inspect}. Call list_resources for the valid keys.", code: "unknown_resource")
30
+ end
31
+
32
+ # What the resource's MCP mode leaves out is unknown to this tool, as a tool the caller isn't offered is.
33
+ # `verbs`: some declared verb must pass the mode (before the call's own verb is known); `verb`: that verb must.
34
+ def permit!(args, *names, verb: nil, verbs: nil)
35
+ config = config_for(args)
36
+ return config if verbs ? Access.allows_any?(config, names, verbs) : Access.allows?(config, names, verb:)
37
+
38
+ raise ToolError.new("Unknown resource #{args["resource"].to_s.first(60).inspect} for this tool. Call list_resources for the valid keys and what each allows (`can`).", code: "unknown_resource")
39
+ end
40
+
41
+ def path(rest = nil) = Paths.api(File.join("/", ReactiveAdmin.config.namespace.to_s, rest.to_s))
42
+
43
+ def collection_path(args)
44
+ config = config_for(args)
45
+ parent = args["parent_id"].presence&.to_s
46
+ raise ToolError.new("#{args["resource"]} is nested under #{Registry.route_key(config.belongs_to_config.target)}; pass parent_id.", code: "parent_required") if Paths.nested?(config) && !parent
47
+
48
+ Paths.api(Paths.collection(config, parent_id: (encode(parent) if parent)))
49
+ end
50
+
51
+ def member_path(args) = File.join(collection_path(args), encode(args["id"].presence || raise(ToolError, "id is required")))
52
+
53
+ def page_path(args)
54
+ page = Registry.find_page(args["page"].to_s)&.then { it if Access.visible?(it) } || raise(ToolError.new("Unknown page #{args["page"].to_s.first(60).inspect}. Call list_resources for the valid keys.", code: "unknown_page"))
55
+ return path("_pages/#{page.underscored_resource_name}") unless Paths.nested?(page)
56
+
57
+ parent = args["parent_id"].presence || raise(ToolError, "#{args["page"]} is nested; pass parent_id.")
58
+ path("#{Registry.route_key(page.belongs_to_config.target)}/#{encode(parent)}/_pages/#{page.underscored_resource_name}")
59
+ end
60
+
61
+ def param_key(args) = config_for(args).param_key
62
+
63
+ def encode(value) = ERB::Util.url_encode(value.to_s)
64
+ end
65
+
66
+ TYPES = {"string" => String, "integer" => Integer, "boolean" => [true, false], "object" => Hash, "array" => Array}.freeze
67
+ RESOURCE = {type: "string", description: "Resource key from list_resources, e.g. \"posts\"."}.freeze
68
+ ID = {type: "string", description: "Record id."}.freeze
69
+ PARENT = {type: "string", description: "Parent record id, only for resources listed as nested_under another."}.freeze
70
+ CONFIRM = {type: "boolean", description: "Must be true. Without it the call only explains what it would do."}.freeze
71
+ QUERY = {type: "object", description: "Values for the GET form's fields (`query_fields`), nested by each field's `param`: {\"simulation\": {\"date\": \"2026-10-01\"}}. Only declared fields; the response shows the results."}.freeze
72
+ LOCK = {type: "object", description: "The `lock` object from get_form, passed back unchanged. The update is refused if the record changed since."}.freeze
73
+
74
+ READABLE = -> { Access.any_visible?(Registry.resources) }
75
+ DRY_RUN = {type: "boolean", description: "Validate only: returns what would change (attribute to {from, to}) and saves nothing."}.freeze
76
+
77
+ @tools = {}
78
+
79
+ class << self
80
+ attr_reader :tools
81
+
82
+ def all = tools.values
83
+
84
+ def find(name) = tools[name.to_s]
85
+
86
+ # Tools a caller's scopes allow and some MCP mode offers: a token without the write scope isn't
87
+ # offered writes, nor is anyone when no resource takes them.
88
+ def visible(identity)
89
+ write_scope = ReactiveAdmin.config.mcp.write_scope
90
+ all.select { (!it.write || identity.allows?(write_scope)) && it.offered? }
91
+ end
92
+
93
+ def call(tool, args, context)
94
+ validate!(tool, args)
95
+ payload = tool.handler.call(context, args)
96
+ Output.render(payload, limit: context.limit, **tool.fit)
97
+ end
98
+
99
+ def define(name, title:, description:, properties: {}, required: [], write: false, destructive: false, idempotent: false, fit: {}, offered: READABLE, &handler)
100
+ annotations = write ? {readOnlyHint: false, destructiveHint: destructive, idempotentHint: idempotent, openWorldHint: false} : {readOnlyHint: true, openWorldHint: false}
101
+ tools[name.to_s] = Tool.new(name: name.to_s, title:, description:, properties:, required: required.map(&:to_s), annotations:, write:, fit:, offered:, handler:)
102
+ end
103
+
104
+ private
105
+
106
+ def validate!(tool, args)
107
+ raise ToolError, "Arguments must be an object." unless args.is_a?(Hash)
108
+
109
+ missing = tool.required - args.keys
110
+ raise ToolError, "Missing required argument#{"s" if missing.size > 1}: #{missing.join(", ")}." if missing.any?
111
+
112
+ args.each do |key, value|
113
+ spec = tool.properties[key.to_sym] or raise ToolError, "Unknown argument #{key.to_s.first(40).inspect}. This tool takes: #{tool.properties.keys.join(", ")}."
114
+ expected = TYPES.fetch(spec[:type])
115
+ raise ToolError, "Argument #{key} must be a #{spec[:type]}." unless Array(expected).any? { |type| type.is_a?(Module) ? value.is_a?(type) : value == type }
116
+ raise ToolError, "Argument #{key} must be one of: #{spec[:enum].join(", ")}." if spec[:enum]&.exclude?(value)
117
+ end
118
+ end
119
+ end
120
+
121
+ ACTION_NAME = /\A\w+\z/
122
+ QUERY_LIMIT = 50
123
+ FILTER_NAME = /\A\w+\z/
124
+
125
+ define :list_resources, title: "List admin resources", fit: {rows: :resources}, offered: nil,
126
+ description: "Lists the resources (record types) and pages this user may open, with what they can do (index, show, create, update, destroy). Start here." do |ctx, _|
127
+ Shapes.resources(ctx.api.get!(ctx.path("_manifest")))
128
+ end
129
+
130
+ define :describe_resource, title: "Describe a resource",
131
+ description: "Columns, filters (with the exact filter params to use in list_records), scopes, sorting, batch and collection actions, and the create form for one resource. Fetches one row to learn the columns and discards it; pass columns: false to skip that.",
132
+ properties: {resource: RESOURCE, parent_id: PARENT, columns: {type: "boolean", description: "Default true."}}, required: [:resource] do |ctx, args|
133
+ base = ctx.collection_path(args)
134
+ meta = ctx.api.get!(File.join(base, "_meta"))
135
+ can = Shapes.can(meta["permissions"], meta.dig("api_denied", "actions"))
136
+ columns = optional { ctx.api.get!(base, per_page: 1)["columns"] } if can.include?("index") && args["columns"] != false
137
+ form = optional { Shapes.form(ctx.api.get!(File.join(base, "new"))) } if can.include?("create")
138
+ Shapes.meta(meta, columns:, form:)
139
+ end
140
+
141
+ define :list_records, title: "List records", fit: {rows: :records},
142
+ description: "Lists records of a resource, newest per the default order. filters is an object of declared filter params to values, e.g. {\"title_cont\": \"smith\", \"created_at_gteq\": \"2026-01-01\"}; describe_resource lists them (undeclared ones are rejected). Results are paged: follow `next`.",
143
+ properties: {resource: RESOURCE, parent_id: PARENT, filters: {type: "object", description: "Declared filter params to values."},
144
+ scope: {type: "string", description: "Scope id from describe_resource."}, order: {type: "string", description: "<sort>_asc or <sort>_desc, e.g. created_at_desc."},
145
+ page: {type: "integer", description: "1-based."}, per_page: {type: "integer", description: "Capped by the server."}}, required: [:resource] do |ctx, args|
146
+ filters = args.fetch("filters", {})
147
+ bad = filters.keys.grep_v(FILTER_NAME)
148
+ raise ToolError, "Invalid filter name #{bad.first.to_s.first(40).inspect}." if bad.any?
149
+
150
+ per_page = [args["per_page"].to_i.positive? ? args["per_page"] : 10, ReactiveAdmin.config.mcp.max_per_page].min
151
+ query = {q: filters.presence, scope: args["scope"], order: args["order"], page: args["page"], per_page:}
152
+ Shapes.index(ctx.api.get!(ctx.collection_path(args), query))
153
+ end
154
+
155
+ define :get_record, title: "Get a record", fit: {text: :sections},
156
+ description: "One record's fields and sections as text, plus the custom actions available on it. Large json or text values are summarized; call reveal_value with their expand_path to read them.",
157
+ properties: {resource: RESOURCE, id: ID, parent_id: PARENT}, required: %i[resource id] do |ctx, args|
158
+ Shapes.show(ctx.api.get!(ctx.member_path(args)))
159
+ end
160
+
161
+ define :get_page, title: "Get a page", fit: {text: :sections}, offered: -> { Access.any_visible?(Registry.pages) },
162
+ description: "A custom admin page (dashboards, reports) as text. Page keys are listed by list_resources. A page with a filter form lists its fields as `query_fields`; pass `query` to see the results for them.",
163
+ properties: {page: {type: "string", description: "Page key."}, parent_id: PARENT, query: QUERY}, required: [:page] do |ctx, args|
164
+ Shapes.page(read_view(ctx, ctx.page_path(args), args["query"]))
165
+ end
166
+
167
+ define :get_form, title: "Get a form", offered: -> { Access.anywhere?("new", "edit") },
168
+ description: "The fields of the new-record form (omit id) or the edit form (pass id): each field's `key` (what create_record and update_record take in values), control, whether it is required, its current value and options. The edit form's `lock` is needed by update_record.",
169
+ properties: {resource: RESOURCE, id: {type: "string", description: "Record id for the edit form; omit for the new form."}, parent_id: PARENT}, required: [:resource] do |ctx, args|
170
+ ctx.permit!(args, args["id"].present? ? "edit" : "new")
171
+ path = args["id"].present? ? File.join(ctx.member_path(args), "edit") : File.join(ctx.collection_path(args), "new")
172
+ Shapes.form(ctx.api.get!(path)).merge(mode: args["id"].present? ? "edit" : "new")
173
+ end
174
+
175
+ define :create_record, title: "Create a record", write: true, offered: -> { Access.anywhere?("create") },
176
+ description: "Creates a record. values is an object keyed by the `key` of each field from get_form (nested rows go under the key of their section, as an array of objects). Fields the form doesn't offer are rejected.",
177
+ properties: {resource: RESOURCE, parent_id: PARENT, values: {type: "object", description: "Field key to value."}}, required: %i[resource values] do |ctx, args|
178
+ ctx.permit!(args, "create")
179
+ written ctx.api.call!("POST", ctx.collection_path(args), body: {ctx.param_key(args) => args["values"]}), args
180
+ end
181
+
182
+ define :update_record, title: "Update a record", write: true, idempotent: true, offered: -> { Access.anywhere?("update") },
183
+ description: "Changes fields of one record. Send only the fields to change, keyed as in get_form, plus the `lock` from the same get_form call. A stale lock is refused: reload with get_form and review before retrying. Pass dry_run: true to validate and see each field's from and to without saving anything.",
184
+ properties: {resource: RESOURCE, id: ID, parent_id: PARENT, values: {type: "object", description: "Field key to new value."}, lock: LOCK,
185
+ lock_version: {type: "string", description: "Shorthand for the lock of a model with lock_version."}, dry_run: DRY_RUN}, required: %i[resource id values] do |ctx, args|
186
+ ctx.permit!(args, "update")
187
+ lock = args["lock"] || ({field: "lock_version", value: args["lock_version"]} if args["lock_version"])
188
+ body = {ctx.param_key(args) => args["values"], :lock => lock, :dry_run => (true if args["dry_run"])}.compact
189
+ args["dry_run"] ? dry_run_result(ctx, args, body) : written(ctx.api.call!("PATCH", ctx.member_path(args), body:), args)
190
+ end
191
+
192
+ define :delete_record, title: "Delete a record", write: true, destructive: true, idempotent: true, offered: -> { Access.anywhere?("destroy") },
193
+ description: "Deletes one record. Requires confirm: true. Hard to undo: confirm with the user first.",
194
+ properties: {resource: RESOURCE, id: ID, parent_id: PARENT, confirm: CONFIRM}, required: %i[resource id] do |ctx, args|
195
+ ctx.permit!(args, "destroy")
196
+ path = ctx.member_path(args)
197
+ unconfirmed!(args, "delete #{args["resource"]}/#{args["id"]} (DELETE #{path}), which may not be reversible.")
198
+ written ctx.api.call!("DELETE", path), args
199
+ end
200
+
201
+ define :run_action, title: "Run an action", write: true, destructive: true, offered: -> { Access.any_runnable? },
202
+ description: "Runs a custom action: kind member (needs id), collection, or batch (needs ids and a key from describe_resource's batch_actions). Action keys come from get_record, get_page or describe_resource. inputs is sent as the JSON body exactly as given; for actions with a form, read it first with method: get and nest values under the param names it shows. A GET action with a filter form takes `query` (see `query_fields`). Anything but a GET requires confirm: true.",
203
+ properties: {resource: RESOURCE, action: {type: "string", description: "Action key."}, kind: {type: "string", enum: %w[member collection batch]}, id: ID, ids: {type: "array", description: "Record ids for kind batch (at most 100)."},
204
+ parent_id: PARENT, inputs: {type: "object", description: "Request body."}, query: QUERY, method: {type: "string", enum: %w[get post put patch delete], description: "Defaults to the action's own method."},
205
+ confirm: CONFIRM}, required: %i[resource action kind] do |ctx, args|
206
+ run_action(ctx, args)
207
+ end
208
+
209
+ define :field_options, title: "Search a field's options", fit: {rows: :options},
210
+ description: "Typeahead for a filter or form field that has `search`: finds options by term, or resolves known values to labels. Pass the field's `search` value as field.",
211
+ properties: {resource: RESOURCE, field: {type: "string", description: "The `search` value of a filter or form field."}, context: {type: "string", enum: %w[filter form], description: "Default filter."},
212
+ term: {type: "string"}, value: {type: "array", description: "Values to resolve to labels."}, id: {type: "string", description: "Record id when searching an edit form's field."},
213
+ limit: {type: "integer"}, parent_id: PARENT}, required: %i[resource field] do |ctx, args|
214
+ ctx.permit!(args, args["id"].present? ? "edit" : "new") if args["context"] == "form"
215
+ query = {field: args["field"], context: args.fetch("context", "filter"), term: args["term"], value: args["value"]&.join(","), id: args["id"],
216
+ limit: [args["limit"] || 10, ReactiveAdmin.config.mcp.max_per_page].min}
217
+ body = ctx.api.get!(File.join(ctx.collection_path(args), "_options"), query)
218
+ {options: body["options"].map { it.slice("value", "label") }, truncated: body["truncated"] || nil}.compact
219
+ end
220
+
221
+ define :reveal_value, title: "Reveal a summarized value",
222
+ description: "Reads the full value behind an `expand_path` returned by get_record, get_form or list_records (a long text or a json value shown only as a summary). Each reveal is audited as a view of that field. path reads one nested key, e.g. \"allergies.0\".",
223
+ properties: {expand_path: {type: "string", description: "The expand_path exactly as returned."}, path: {type: "string", description: "Nested key, dotted."}}, required: [:expand_path] do |ctx, args|
224
+ reveal(ctx, args)
225
+ end
226
+
227
+ class << self
228
+ private
229
+
230
+ def optional
231
+ yield
232
+ rescue ToolError
233
+ nil
234
+ end
235
+
236
+ def written(body, args)
237
+ {ok: true, record: ("#{args["resource"]}/#{body["id"] || args["id"]}" if body["id"] || args["id"]), message: body["message"]}.compact
238
+ end
239
+
240
+ # A failed validation is the answer a dry run exists to give, not a failure of the tool.
241
+ def dry_run_result(ctx, args, body)
242
+ result = ctx.api.call!("PATCH", ctx.member_path(args), body:)
243
+ {ok: true, dry_run: true, saved: false, record: "#{args["resource"]}/#{args["id"]}", changes: result["changes"], nested: result["nested"],
244
+ note: "Nothing was saved. Call again without dry_run to apply."}.compact
245
+ rescue ToolError => e
246
+ raise unless e.status == 422 && e.code == "invalid"
247
+
248
+ {ok: false, dry_run: true, saved: false, problems: e.message.delete_prefix("Validation failed: "), note: "Nothing was saved."}
249
+ end
250
+
251
+ def unconfirmed!(args, what)
252
+ return if args["confirm"] == true
253
+
254
+ raise ToolError.new("Not done: this would #{what} Nothing was changed. Ask the user to confirm, then call again with confirm: true.", code: "confirmation_required")
255
+ end
256
+
257
+ def run_action(ctx, args)
258
+ name = args["action"]
259
+ raise ToolError, "action must be a plain key like \"archive\"." unless ACTION_NAME.match?(name)
260
+
261
+ kind = args["kind"]
262
+ config = ctx.config_for(args)
263
+ verbs = declared_verbs(config, name, kind)
264
+ names = (kind == "batch") ? ["batch_action", name] : [name]
265
+ ctx.permit!(args, *names, verbs:)
266
+ base = ctx.collection_path(args)
267
+ known = action_info(ctx, args, base, name, kind)
268
+ asked = (args["method"] || known["method"])&.upcase
269
+ verb = verbs.include?(asked) ? asked : verbs.first
270
+ ctx.permit!(args, *names, verb:)
271
+ path = action_path(ctx, args, base, name, kind)
272
+ body = args["inputs"]
273
+ query = args["query"]
274
+ raise ToolError, "query is for GET actions; pass inputs for the others." if query && verb != "GET"
275
+ raise ToolError, "Pass query or inputs, not both." if query && body
276
+ raise ToolError, "A GET action that writes can't take a query: reading its form would run it twice." if query && !ActionSafety.read?(config, name, verb)
277
+ if kind == "batch"
278
+ ids = args["ids"]&.map(&:to_s) || raise(ToolError, "kind batch needs ids.")
279
+ raise ToolError, "A batch takes at most 100 ids." if ids.size > 100
280
+
281
+ body = {batch_action: name, collection_selection: ids, batch_action_inputs: args["inputs"]}.compact
282
+ end
283
+ unless ActionSafety.read?(config, name, verb) || reserved?(ctx, args, kind, name)
284
+ ask = known["confirm"] ? " The app asks: #{known["confirm"].to_s.first(200).inspect}" : ""
285
+ unconfirmed!(args, "run #{kind} action #{name} on #{args["resource"]}#{" (#{args["ids"].size} records)" if kind == "batch"} (#{verb} #{path}).#{ask}")
286
+ end
287
+ action_result(query ? read_view(ctx, path, query) : ctx.api.call!(verb, path, body:))
288
+ end
289
+
290
+ # A read with a query is held to the fields of the GET forms the same view declares without one.
291
+ def read_view(ctx, path, query)
292
+ body = ctx.api.get!(path)
293
+ return body if query.blank?
294
+
295
+ declared = Layout.query_fields(body).map { it["param"].delete_suffix("[]") }
296
+ raise ToolError.new("This has no GET form, so it takes no query.", code: "no_query") if declared.empty?
297
+
298
+ unknown = flatten_query(query).keys - declared
299
+ raise ToolError, "Unknown query field #{unknown.first.first(60).inspect}. The form takes: #{declared.join(", ")}." if unknown.any?
300
+
301
+ ctx.api.get!(path, query)
302
+ end
303
+
304
+ def flatten_query(value, prefix = nil)
305
+ pairs = value.flat_map do |key, nested|
306
+ name = prefix ? "#{prefix}[#{key}]" : key.to_s
307
+ case nested
308
+ when Hash then flatten_query(nested, name).to_a
309
+ when Array, String, Numeric, true, false, nil then [[name.delete_suffix("[]"), nested]]
310
+ else raise ToolError, "Query values are strings, numbers, booleans or lists of them."
311
+ end
312
+ end
313
+ raise ToolError, "A query takes at most #{QUERY_LIMIT} fields." if pairs.size > QUERY_LIMIT
314
+
315
+ pairs.to_h
316
+ end
317
+
318
+ # The methods the action declares, which a caller can choose among but not add to. Only declared actions
319
+ # run: any other path under the resource is the API's own, which the other tools cover.
320
+ def declared_verbs(config, name, kind)
321
+ if kind == "batch"
322
+ return ["POST"] if AA.batch_actions(config).any? { it.sym.to_s == name }
323
+ else
324
+ declaration = ((kind == "member") ? config.member_actions : config.collection_actions).find { it.name.to_s == name }
325
+ return Array.wrap(declaration.http_verb).map { it.to_s.upcase } if declaration
326
+ end
327
+ raise ToolError.new("No #{kind} action #{name.inspect} on #{Registry.route_key(config)}. Action keys come from get_record, get_page or describe_resource.", code: "unknown_action")
328
+ end
329
+
330
+ # Not asked to confirm what can't run: the call goes on to the API, which refuses it with a pointer to the classic admin.
331
+ def reserved?(ctx, args, kind, name)
332
+ ApiGuards.denies?(ctx.config_for(args), *((kind == "batch") ? ["batch_action", name] : [name]))
333
+ end
334
+
335
+ def action_path(ctx, args, base, name, kind)
336
+ case kind
337
+ when "member" then File.join(ctx.member_path(args), name)
338
+ when "collection" then File.join(base, name)
339
+ else File.join(base, "batch_action")
340
+ end
341
+ end
342
+
343
+ # What the app says about the action (its method, its confirmation text), from the same API the UI reads.
344
+ def action_info(ctx, args, base, name, kind)
345
+ return {} if args["confirm"] == true && (args["method"] || kind == "batch")
346
+
347
+ found = case kind
348
+ when "member" then ctx.api.get!(ctx.member_path(args)).then { [*it["actions"], *Layout.actions(it["layout"])] }
349
+ when "collection" then ctx.api.get!(File.join(base, "_meta"))["action_items"]
350
+ else ctx.api.get!(File.join(base, "_meta"))["batch_actions"]
351
+ end
352
+ Array(found).find { it["key"] == name } || {}
353
+ rescue ToolError
354
+ {}
355
+ end
356
+
357
+ def action_result(body)
358
+ return Shapes.form(body, with_params: true) if body.is_a?(Hash) && body["form"]
359
+ return Shapes.page(body) if body.is_a?(Hash) && body["layout"]
360
+
361
+ {ok: body["ok"], message: body["message"], location: body.dig("location", "url")}.compact
362
+ end
363
+
364
+ def reveal(ctx, args)
365
+ uri = URI.parse(args["expand_path"])
366
+ root = ctx.path.chomp("/")
367
+ valid = uri.host.nil? && uri.path.start_with?("#{root}/") && uri.path.end_with?("/_value") && uri.path.exclude?("..") && uri.path.exclude?("//")
368
+ raise ToolError, "expand_path must be a path returned by a previous result, unchanged." unless valid
369
+
370
+ ctx.permit!({"resource" => uri.path.delete_prefix("#{root}/").split("/")[-3]}, "show")
371
+ query = Rack::Utils.parse_query(uri.query).slice("field", "token").merge("path" => args["path"])
372
+ value = ctx.api.get!(uri.path, query)["value"]
373
+ size = JSON.generate(value).bytesize
374
+ return {value:} if size <= ctx.limit - 500
375
+
376
+ {truncated: "The value is #{size} bytes, over the #{ctx.limit} byte limit. Pass path to read part of it.", kind: value.class.name.downcase,
377
+ keys: (value.keys.first(20) if value.is_a?(Hash)), length: (value.size if value.is_a?(Array))}.compact
378
+ rescue URI::InvalidURIError
379
+ raise ToolError, "expand_path is not a valid path."
380
+ end
381
+ end
382
+
383
+ require "reactive_admin/mcp/count_tool"
384
+ end
385
+ end
386
+ end
@@ -0,0 +1,53 @@
1
+ module ReactiveAdmin
2
+ # A Model Context Protocol server (Streamable HTTP, stateless JSON responses) over the admin API.
3
+ #
4
+ # It is hand-rolled rather than built on the `mcp` gem: the surface is four methods
5
+ # (initialize, ping, tools/list, tools/call), every response is a single JSON document, and the
6
+ # tool list depends on the caller's token, which a hand-rolled server makes trivial. That avoids a
7
+ # pre-1.0 runtime dependency (and its json-schema dependency) in a gem that guards sensitive data.
8
+ #
9
+ # Tools never touch models. Each one dispatches an internal request through the host's Rack stack
10
+ # to the same API routes the React client uses, with the caller's Authorization header, so the
11
+ # controllers' authorization, masking, audit events and rate limits all apply unchanged.
12
+ module Mcp
13
+ autoload :Server, "reactive_admin/mcp/server"
14
+ autoload :Api, "reactive_admin/mcp/api"
15
+ autoload :Tools, "reactive_admin/mcp/tools"
16
+ autoload :Prompts, "reactive_admin/mcp/prompts"
17
+ autoload :Output, "reactive_admin/mcp/output"
18
+ autoload :Layout, "reactive_admin/mcp/layout"
19
+ autoload :Shapes, "reactive_admin/mcp/shapes"
20
+ autoload :Access, "reactive_admin/mcp/access"
21
+
22
+ PROTOCOL_VERSIONS = %w[2025-06-18 2025-03-26 2024-11-05].freeze
23
+ # What a client that sends no MCP-Protocol-Version header is assumed to speak (per the spec).
24
+ DEFAULT_PROTOCOL_VERSION = "2025-03-26".freeze
25
+
26
+ # A tool failure the agent can act on. `message` is shown to the model, so it names the next step and
27
+ # never carries record data.
28
+ class ToolError < StandardError
29
+ attr_reader :status, :code
30
+
31
+ def initialize(message, status: nil, code: nil)
32
+ super(message)
33
+ @status = status
34
+ @code = code
35
+ end
36
+ end
37
+
38
+ module_function
39
+
40
+ def protocol_version_supported?(request)
41
+ version = request.headers["MCP-Protocol-Version"]
42
+ version.blank? || PROTOCOL_VERSIONS.include?(version)
43
+ end
44
+
45
+ # The origin of a browser request, which an MCP endpoint must check against DNS rebinding.
46
+ def origin_allowed?(request)
47
+ origin = request.headers["Origin"]
48
+ return true if origin.blank?
49
+
50
+ [request.base_url, *Array(ReactiveAdmin.config.mcp.allowed_origins)].any? { it.to_s.chomp("/").casecmp?(origin) }
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,34 @@
1
+ module ReactiveAdmin
2
+ # Images and PDFs the HTML policy lets load, as typed nodes the client shows with a lightbox or viewer. What
3
+ # this doesn't take (data: images, other embeds, off-site media) stays with HtmlPolicy's html and link rules.
4
+ module MediaNodes
5
+ MAX_DIMENSION = 10_000
6
+
7
+ module_function
8
+
9
+ def for(el, host:)
10
+ src = HtmlPolicy.source(el)
11
+ return unless web_url?(src) && HtmlPolicy.same_origin?(src, host)
12
+
13
+ (el.name == "img") ? image(el, src) : document(el, src)
14
+ end
15
+
16
+ def image(el, src)
17
+ {type: "image", src:, alt: el["alt"].to_s.strip, width_px: dimension(el["width"]), height_px: dimension(el["height"])}.compact
18
+ end
19
+
20
+ def document(el, src)
21
+ return unless (el.name == "iframe") ? HtmlPolicy.pdf_path?(src) : HtmlPolicy.pdf?(el, src)
22
+
23
+ {type: "document", src:, mime: "application/pdf", title: el["title"].to_s.strip.presence}.compact
24
+ end
25
+
26
+ # A relative path is the request's own site; a scheme must be http(s). Never data: or protocol-relative.
27
+ def web_url?(src) = src.match?(%r{\Ahttps?://}i) || (src.start_with?("/") && !src.start_with?("//"))
28
+
29
+ def dimension(value)
30
+ size = Integer(value.to_s.strip, 10, exception: false)
31
+ size if size&.between?(1, MAX_DIMENSION)
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,90 @@
1
+ module ReactiveAdmin
2
+ # AA's navigation menus (default and utility), filtered and resolved for the current user.
3
+ class Menu
4
+ UNEXPOSED = :unexposed
5
+
6
+ # AA's menu procs (`if:`, label, url) are instance_exec'd in a view that responds to these.
7
+ def initialize(view, authorizer, resource_keys, user: authorizer.user)
8
+ @view = view
9
+ @resource_keys = resource_keys
10
+ AA.prepare_menu_view(view, namespace: Registry.namespace, user:, authorizer:)
11
+ end
12
+
13
+ def as_json(*) = menu(AA.default_menu)
14
+
15
+ def menu(name)
16
+ nodes = AA.menu_entries(Registry.namespace, name, @view).filter_map { node(it) }
17
+ if name == AA.default_menu
18
+ MenuOverlay.record_audit
19
+ nodes = MenuOverlay::Layout.new(nodes, evaluate: method(:evaluate), build: method(:overlay_node)).call
20
+ end
21
+ finish(nodes)
22
+ end
23
+
24
+ def self.page_key(config) = config.underscored_resource_name
25
+
26
+ private
27
+
28
+ def node(entry)
29
+ return unless entry.display?
30
+
31
+ url = entry.url.presence
32
+ destination = destination(url)
33
+ return if destination == UNEXPOSED
34
+
35
+ url = nil if (destination&.key?(:resource) && !destination[:api_denied]) || url == "#"
36
+ node = {id: entry.id, label: entry.label.to_s, kind: kind(destination, url), resource: nil, **destination.to_h, url:, priority: entry.priority,
37
+ children: entry.children.filter_map { node(it) }}
38
+ verb = entry.http_method
39
+ verb ? node.merge(method: verb.to_s) : node
40
+ rescue => e
41
+ Rails.logger.warn("[reactiveadmin] skipped menu item #{entry.id}: #{e.class} at #{e.backtrace&.first}")
42
+ Degradation.record(kind: :menu_item_dropped, where: "menu/item[#{entry.id}]", reason: "Menu item raised #{e.class}; left out")
43
+ nil
44
+ end
45
+
46
+ def overlay_node(config) = node(AA.menu_entry_for(config, @view))
47
+
48
+ def kind(destination, url)
49
+ if destination&.key?(:api_denied) then "link"
50
+ elsif destination&.key?(:resource) then "resource"
51
+ elsif destination then "page"
52
+ elsif url then "link"
53
+ else
54
+ "group"
55
+ end
56
+ end
57
+
58
+ # Each level is ordered by priority, then overlay order, then label; emptied groups go.
59
+ def finish(nodes, depth = 1)
60
+ nodes.sort_by { [it[:priority], it[:seq] || MenuOverlay::UNSEQUENCED, it[:label]] }.filter_map do |node|
61
+ MenuOverlay.check_depth!(depth, node[:label])
62
+ children = finish(node[:children], depth + 1)
63
+ node.except(:seq).merge(children:) unless node[:kind] == "group" && children.empty?
64
+ end
65
+ end
66
+
67
+ def evaluate(value) = AA.render_in_context(@view, @view, value)
68
+
69
+ def destination(url)
70
+ return unless url&.start_with?("/")
71
+
72
+ route = Rails.application.routes.recognize_path(url)
73
+ return unless route[:action] == "index"
74
+
75
+ if (config = Registry.for_controller_path(route[:controller]))
76
+ key = Registry.route_key(config)
77
+ return UNEXPOSED unless Exposure.allowed?(config)
78
+ return {resource: key, api_denied: true} if ApiGuards.denies?(config, "index")
79
+
80
+ {resource: key} if @resource_keys.include?(key)
81
+ elsif (page = Registry.page_for_controller_path(route[:controller]))
82
+ return UNEXPOSED unless Exposure.allowed?(page)
83
+
84
+ {page: Menu.page_key(page), **({api_denied: true} if ApiGuards.denies?(page, "index")).to_h}
85
+ end
86
+ rescue ActionController::RoutingError
87
+ nil
88
+ end
89
+ end
90
+ end