@mastra/server 1.83.0-alpha.8 → 1.83.0-alpha.9

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 (301) hide show
  1. package/dist/{a2a-Cu87JDM2.cjs → a2a-DIcMx6x-.cjs} +4 -4
  2. package/dist/{a2a-Cu87JDM2.cjs.map → a2a-DIcMx6x-.cjs.map} +1 -1
  3. package/dist/{a2a-BnWFvgiU.js → a2a-DTTGA2Xg.js} +4 -4
  4. package/dist/{a2a-BnWFvgiU.js.map → a2a-DTTGA2Xg.js.map} +1 -1
  5. package/dist/{agent-builder-BP3doUBF.cjs → agent-builder-BXBfs0w4.cjs} +5 -5
  6. package/dist/{agent-builder-BP3doUBF.cjs.map → agent-builder-BXBfs0w4.cjs.map} +1 -1
  7. package/dist/{agent-builder-tQdzjW0P.js → agent-builder-DtBRYFZ3.js} +5 -5
  8. package/dist/{agent-builder-tQdzjW0P.js.map → agent-builder-DtBRYFZ3.js.map} +1 -1
  9. package/dist/{agents-BA-MmcJN.js → agents-CTgjTASj.js} +4 -4
  10. package/dist/{agents-BA-MmcJN.js.map → agents-CTgjTASj.js.map} +1 -1
  11. package/dist/{agents-BMxHcsO7.cjs → agents-DjpBmwhv.cjs} +5 -5
  12. package/dist/{agents-BMxHcsO7.cjs.map → agents-DjpBmwhv.cjs.map} +1 -1
  13. package/dist/{api-schema-manifest-BE06Ub4o.js → api-schema-manifest-B8s3TuPU.js} +3 -3
  14. package/dist/{api-schema-manifest-BE06Ub4o.js.map → api-schema-manifest-B8s3TuPU.js.map} +1 -1
  15. package/dist/{api-schema-manifest-DR4f61oH.cjs → api-schema-manifest-Czr4Bmrw.cjs} +3 -3
  16. package/dist/{api-schema-manifest-DR4f61oH.cjs.map → api-schema-manifest-Czr4Bmrw.cjs.map} +1 -1
  17. package/dist/{background-tasks-S__xU_pa.js → background-tasks-CYvlxFz3.js} +2 -2
  18. package/dist/{background-tasks-S__xU_pa.js.map → background-tasks-CYvlxFz3.js.map} +1 -1
  19. package/dist/{background-tasks-CIXrANYT.cjs → background-tasks-Dv9o8cR7.cjs} +2 -2
  20. package/dist/{background-tasks-CIXrANYT.cjs.map → background-tasks-Dv9o8cR7.cjs.map} +1 -1
  21. package/dist/{builder-registry-Dd7pbJ5A.js → builder-registry-BmrttdGj.js} +3 -3
  22. package/dist/{builder-registry-Dd7pbJ5A.js.map → builder-registry-BmrttdGj.js.map} +1 -1
  23. package/dist/{builder-registry-DrBUA6EZ.cjs → builder-registry-CmbtZzbE.cjs} +3 -3
  24. package/dist/{builder-registry-DrBUA6EZ.cjs.map → builder-registry-CmbtZzbE.cjs.map} +1 -1
  25. package/dist/{channels-DbfSH5O2.cjs → channels-CXwFVxi2.cjs} +2 -2
  26. package/dist/{channels-DbfSH5O2.cjs.map → channels-CXwFVxi2.cjs.map} +1 -1
  27. package/dist/{channels-B6hwVMbV.js → channels-KHhb7hAm.js} +2 -2
  28. package/dist/{channels-B6hwVMbV.js.map → channels-KHhb7hAm.js.map} +1 -1
  29. package/dist/{conversations-CsyE18Yj.cjs → conversations-BFqmDglO.cjs} +3 -3
  30. package/dist/{conversations-CsyE18Yj.cjs.map → conversations-BFqmDglO.cjs.map} +1 -1
  31. package/dist/{conversations-DtbEa1l_.js → conversations-BkX00xDs.js} +3 -3
  32. package/dist/{conversations-DtbEa1l_.js.map → conversations-BkX00xDs.js.map} +1 -1
  33. package/dist/{dist-DlH7rr5l.cjs → dist-BRBLnUAY.cjs} +1 -1
  34. package/dist/{dist-C3cKdDos.js → dist-DHiTIWvp.js} +6 -6
  35. package/dist/{dist-C3cKdDos.js.map → dist-DHiTIWvp.js.map} +1 -1
  36. package/dist/{dist-bVYV7beH.cjs → dist-DLzcAC-F.cjs} +11 -11
  37. package/dist/{dist-bVYV7beH.cjs.map → dist-DLzcAC-F.cjs.map} +1 -1
  38. package/dist/dist-tbh2LUPc.js +1 -0
  39. package/dist/docs/SKILL.md +1 -1
  40. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  41. package/dist/docs/references/reference-observability-tracing-advanced-queries.md +2 -1
  42. package/dist/{dynamic-workflows-CyaZLmHX.js → dynamic-workflows-CYtakeIQ.js} +2 -2
  43. package/dist/{dynamic-workflows-CyaZLmHX.js.map → dynamic-workflows-CYtakeIQ.js.map} +1 -1
  44. package/dist/{dynamic-workflows-ZmzWJXxG.cjs → dynamic-workflows-QgKLYkiC.cjs} +2 -2
  45. package/dist/{dynamic-workflows-ZmzWJXxG.cjs.map → dynamic-workflows-QgKLYkiC.cjs.map} +1 -1
  46. package/dist/{editor-builder-B4-g7fu_.js → editor-builder-C4H2l6tz.js} +3 -3
  47. package/dist/{editor-builder-B4-g7fu_.js.map → editor-builder-C4H2l6tz.js.map} +1 -1
  48. package/dist/{editor-builder-BTi2EIB1.cjs → editor-builder-Cqw1npOK.cjs} +3 -3
  49. package/dist/{editor-builder-BTi2EIB1.cjs.map → editor-builder-Cqw1npOK.cjs.map} +1 -1
  50. package/dist/{helpers-D7d2R3LL.cjs → helpers-0LJI4DxR.cjs} +3 -4
  51. package/dist/{helpers-D7d2R3LL.cjs.map → helpers-0LJI4DxR.cjs.map} +1 -1
  52. package/dist/{helpers-C3dENOkQ.js → helpers-C9QZKOhz.js} +3 -4
  53. package/dist/{helpers-C3dENOkQ.js.map → helpers-C9QZKOhz.js.map} +1 -1
  54. package/dist/{knowledge-Q_SCnD9m.cjs → knowledge-CRkWkTBC.cjs} +2 -2
  55. package/dist/{knowledge-Q_SCnD9m.cjs.map → knowledge-CRkWkTBC.cjs.map} +1 -1
  56. package/dist/{knowledge-Cd2cCq-Y.js → knowledge-Dfe_CFtt.js} +2 -2
  57. package/dist/{knowledge-Cd2cCq-Y.js.map → knowledge-Dfe_CFtt.js.map} +1 -1
  58. package/dist/{logs-DWIbFIw6.cjs → logs-B2ov1yZQ.cjs} +2 -2
  59. package/dist/{logs-DWIbFIw6.cjs.map → logs-B2ov1yZQ.cjs.map} +1 -1
  60. package/dist/{logs-C5L6gRGr.js → logs-Dg2AWexF.js} +2 -2
  61. package/dist/{logs-C5L6gRGr.js.map → logs-Dg2AWexF.js.map} +1 -1
  62. package/dist/{mcp-CKvOVfHn.cjs → mcp-Bon4eIV1.cjs} +2 -2
  63. package/dist/{mcp-CKvOVfHn.cjs.map → mcp-Bon4eIV1.cjs.map} +1 -1
  64. package/dist/{mcp-CntC59iU.js → mcp-bsPRIGFX.js} +2 -2
  65. package/dist/{mcp-CntC59iU.js.map → mcp-bsPRIGFX.js.map} +1 -1
  66. package/dist/{memory-BfabRYCo.cjs → memory-BRE3ofvI.cjs} +21 -7
  67. package/dist/memory-BRE3ofvI.cjs.map +1 -0
  68. package/dist/{memory-B_qwCpu5.js → memory-Dw7xG5nn.js} +21 -7
  69. package/dist/memory-Dw7xG5nn.js.map +1 -0
  70. package/dist/{observability-C2p6Cm2o.js → observability-BYIy4kPf.js} +3 -3
  71. package/dist/{observability-C2p6Cm2o.js.map → observability-BYIy4kPf.js.map} +1 -1
  72. package/dist/{observability-CsNcAGbL.cjs → observability-DHJ7mzoE.cjs} +3 -3
  73. package/dist/{observability-CsNcAGbL.cjs.map → observability-DHJ7mzoE.cjs.map} +1 -1
  74. package/dist/{observability-new-endpoints--h0vACab.cjs → observability-new-endpoints-BOe3wej1.cjs} +24 -6
  75. package/dist/observability-new-endpoints-BOe3wej1.cjs.map +1 -0
  76. package/dist/{observability-new-endpoints-B42gwVg4.js → observability-new-endpoints-COy7lpeR.js} +26 -8
  77. package/dist/observability-new-endpoints-COy7lpeR.js.map +1 -0
  78. package/dist/{plans-BLqnqqE0.js → plans-D_GKFz2x.js} +3 -3
  79. package/dist/{plans-BLqnqqE0.js.map → plans-D_GKFz2x.js.map} +1 -1
  80. package/dist/{plans-LbsK1Bj0.cjs → plans-_nR8lqgD.cjs} +3 -3
  81. package/dist/{plans-LbsK1Bj0.cjs.map → plans-_nR8lqgD.cjs.map} +1 -1
  82. package/dist/{probe-image-size-0dhxcl8e.cjs → probe-image-size-CN-PYGus.cjs} +2 -2
  83. package/dist/{probe-image-size-0dhxcl8e.cjs.map → probe-image-size-CN-PYGus.cjs.map} +1 -1
  84. package/dist/{probe-image-size-fFwPOWWg.js → probe-image-size-DbJ3ZfUz.js} +2 -2
  85. package/dist/{probe-image-size-fFwPOWWg.js.map → probe-image-size-DbJ3ZfUz.js.map} +1 -1
  86. package/dist/{responses-DYPwRZ7Z.js → responses-C_OEJoxU.js} +3 -3
  87. package/dist/{responses-DYPwRZ7Z.js.map → responses-C_OEJoxU.js.map} +1 -1
  88. package/dist/{responses-7obXjZaq.cjs → responses-CdWbS4jA.cjs} +3 -3
  89. package/dist/{responses-7obXjZaq.cjs.map → responses-CdWbS4jA.cjs.map} +1 -1
  90. package/dist/{route-builder-DHqDrSSy.cjs → route-builder-B9C5vT54.cjs} +4 -4
  91. package/dist/{route-builder-DHqDrSSy.cjs.map → route-builder-B9C5vT54.cjs.map} +1 -1
  92. package/dist/{route-builder-BKEzjw_M.js → route-builder-DfDT1g4L.js} +2 -2
  93. package/dist/{route-builder-BKEzjw_M.js.map → route-builder-DfDT1g4L.js.map} +1 -1
  94. package/dist/{routes-D8NOiXGB.js → routes-Cu4-Al-k.js} +26 -26
  95. package/dist/{routes-D8NOiXGB.js.map → routes-Cu4-Al-k.js.map} +1 -1
  96. package/dist/{routes-DZDn2nLE.cjs → routes-D3T0BV1r.cjs} +26 -26
  97. package/dist/{routes-DZDn2nLE.cjs.map → routes-D3T0BV1r.cjs.map} +1 -1
  98. package/dist/{schedules-CvWX2yKR.cjs → schedules-BQvnAe1j.cjs} +50 -12
  99. package/dist/schedules-BQvnAe1j.cjs.map +1 -0
  100. package/dist/{schedules-D9CKB18-.js → schedules-BcAIELfB.js} +50 -12
  101. package/dist/schedules-BcAIELfB.js.map +1 -0
  102. package/dist/{schema-Bf12g7KC-5EUrrnSf.js → schema-xsUy1mlm-CAPin6jE.js} +303 -6
  103. package/dist/{schema-Bf12g7KC-5EUrrnSf.js.map → schema-xsUy1mlm-CAPin6jE.js.map} +1 -1
  104. package/dist/{schema-Bf12g7KC-C5XzpQxe.cjs → schema-xsUy1mlm-pvZI8YC0.cjs} +303 -6
  105. package/dist/{schema-Bf12g7KC-C5XzpQxe.cjs.map → schema-xsUy1mlm-pvZI8YC0.cjs.map} +1 -1
  106. package/dist/{scores-DxLiiwPT.cjs → scores-DEvPN0kz.cjs} +3 -3
  107. package/dist/{scores-DxLiiwPT.cjs.map → scores-DEvPN0kz.cjs.map} +1 -1
  108. package/dist/{scores-qTduRPeX.js → scores-Dm0yu1Pt.js} +3 -3
  109. package/dist/{scores-qTduRPeX.js.map → scores-Dm0yu1Pt.js.map} +1 -1
  110. package/dist/server/auth/helpers.d.ts.map +1 -1
  111. package/dist/server/auth/index.cjs +1 -1
  112. package/dist/server/auth/index.js +1 -1
  113. package/dist/server/handlers/a2a.cjs +1 -1
  114. package/dist/server/handlers/a2a.js +1 -1
  115. package/dist/server/handlers/agent-builder.cjs +1 -1
  116. package/dist/server/handlers/agent-builder.js +1 -1
  117. package/dist/server/handlers/agent-controller.cjs +13 -5
  118. package/dist/server/handlers/agent-controller.cjs.map +1 -1
  119. package/dist/server/handlers/agent-controller.d.ts.map +1 -1
  120. package/dist/server/handlers/agent-controller.js +13 -5
  121. package/dist/server/handlers/agent-controller.js.map +1 -1
  122. package/dist/server/handlers/agent-versions.cjs +2 -2
  123. package/dist/server/handlers/agent-versions.js +2 -2
  124. package/dist/server/handlers/agents.cjs +1 -1
  125. package/dist/server/handlers/agents.js +1 -1
  126. package/dist/server/handlers/auth.cjs +2 -2
  127. package/dist/server/handlers/auth.js +2 -2
  128. package/dist/server/handlers/background-tasks.cjs +1 -1
  129. package/dist/server/handlers/background-tasks.js +1 -1
  130. package/dist/server/handlers/builder-registry.cjs +1 -1
  131. package/dist/server/handlers/builder-registry.js +1 -1
  132. package/dist/server/handlers/channels.cjs +1 -1
  133. package/dist/server/handlers/channels.js +1 -1
  134. package/dist/server/handlers/conversations.cjs +1 -1
  135. package/dist/server/handlers/conversations.js +1 -1
  136. package/dist/server/handlers/datasets.cjs +1 -1
  137. package/dist/server/handlers/datasets.js +1 -1
  138. package/dist/server/handlers/dynamic-workflows.cjs +1 -1
  139. package/dist/server/handlers/dynamic-workflows.js +1 -1
  140. package/dist/server/handlers/editor-builder.cjs +1 -1
  141. package/dist/server/handlers/editor-builder.js +1 -1
  142. package/dist/server/handlers/favorites-enrichment.cjs +1 -1
  143. package/dist/server/handlers/favorites-enrichment.js +1 -1
  144. package/dist/server/handlers/knowledge.cjs +1 -1
  145. package/dist/server/handlers/knowledge.js +1 -1
  146. package/dist/server/handlers/logs.cjs +1 -1
  147. package/dist/server/handlers/logs.js +1 -1
  148. package/dist/server/handlers/mcp-client-versions.cjs +2 -2
  149. package/dist/server/handlers/mcp-client-versions.js +2 -2
  150. package/dist/server/handlers/mcp.cjs +1 -1
  151. package/dist/server/handlers/mcp.js +1 -1
  152. package/dist/server/handlers/memory.cjs +1 -1
  153. package/dist/server/handlers/memory.d.ts.map +1 -1
  154. package/dist/server/handlers/memory.js +1 -1
  155. package/dist/server/handlers/observability-export.cjs.map +1 -1
  156. package/dist/server/handlers/observability-export.d.ts +2 -2
  157. package/dist/server/handlers/observability-export.d.ts.map +1 -1
  158. package/dist/server/handlers/observability-export.js.map +1 -1
  159. package/dist/server/handlers/observability-new-endpoints.cjs +1 -1
  160. package/dist/server/handlers/observability-new-endpoints.d.ts +8 -2
  161. package/dist/server/handlers/observability-new-endpoints.d.ts.map +1 -1
  162. package/dist/server/handlers/observability-new-endpoints.js +1 -1
  163. package/dist/server/handlers/observability-shared.cjs +7 -1
  164. package/dist/server/handlers/observability-shared.cjs.map +1 -1
  165. package/dist/server/handlers/observability-shared.d.ts +4 -0
  166. package/dist/server/handlers/observability-shared.d.ts.map +1 -1
  167. package/dist/server/handlers/observability-shared.js +7 -2
  168. package/dist/server/handlers/observability-shared.js.map +1 -1
  169. package/dist/server/handlers/observability.cjs +2 -2
  170. package/dist/server/handlers/observability.js +2 -2
  171. package/dist/server/handlers/plans.cjs +1 -1
  172. package/dist/server/handlers/plans.js +1 -1
  173. package/dist/server/handlers/processor-providers.cjs +1 -1
  174. package/dist/server/handlers/processor-providers.js +1 -1
  175. package/dist/server/handlers/processors.cjs +1 -1
  176. package/dist/server/handlers/processors.js +1 -1
  177. package/dist/server/handlers/prompt-block-versions.cjs +2 -2
  178. package/dist/server/handlers/prompt-block-versions.js +2 -2
  179. package/dist/server/handlers/responses.cjs +1 -1
  180. package/dist/server/handlers/responses.js +1 -1
  181. package/dist/server/handlers/schedules.cjs +1 -1
  182. package/dist/server/handlers/schedules.d.ts +88 -28
  183. package/dist/server/handlers/schedules.d.ts.map +1 -1
  184. package/dist/server/handlers/schedules.js +1 -1
  185. package/dist/server/handlers/scorer-versions.cjs +2 -2
  186. package/dist/server/handlers/scorer-versions.js +2 -2
  187. package/dist/server/handlers/scores.cjs +1 -1
  188. package/dist/server/handlers/scores.js +1 -1
  189. package/dist/server/handlers/stored-agent-favorites.cjs +3 -3
  190. package/dist/server/handlers/stored-agent-favorites.js +3 -3
  191. package/dist/server/handlers/stored-agents.cjs +3 -3
  192. package/dist/server/handlers/stored-agents.js +3 -3
  193. package/dist/server/handlers/stored-mcp-clients.cjs +2 -2
  194. package/dist/server/handlers/stored-mcp-clients.js +2 -2
  195. package/dist/server/handlers/stored-prompt-blocks.cjs +2 -2
  196. package/dist/server/handlers/stored-prompt-blocks.js +2 -2
  197. package/dist/server/handlers/stored-scorers.cjs +2 -2
  198. package/dist/server/handlers/stored-scorers.js +2 -2
  199. package/dist/server/handlers/stored-skill-favorites.cjs +3 -3
  200. package/dist/server/handlers/stored-skill-favorites.js +3 -3
  201. package/dist/server/handlers/stored-skills.cjs +3 -3
  202. package/dist/server/handlers/stored-skills.js +3 -3
  203. package/dist/server/handlers/stored-workspaces.cjs +2 -2
  204. package/dist/server/handlers/stored-workspaces.js +2 -2
  205. package/dist/server/handlers/system.cjs +3 -3
  206. package/dist/server/handlers/system.d.ts +2 -0
  207. package/dist/server/handlers/system.d.ts.map +1 -1
  208. package/dist/server/handlers/system.js +3 -3
  209. package/dist/server/handlers/tool-providers.cjs +1 -1
  210. package/dist/server/handlers/tool-providers.js +1 -1
  211. package/dist/server/handlers/tools.cjs +1 -1
  212. package/dist/server/handlers/tools.js +1 -1
  213. package/dist/server/handlers/validate-agent-instructions.cjs +1 -1
  214. package/dist/server/handlers/validate-agent-instructions.js +1 -1
  215. package/dist/server/handlers/vector.cjs +1 -1
  216. package/dist/server/handlers/vector.js +1 -1
  217. package/dist/server/handlers/workflow-builder.cjs +1 -1
  218. package/dist/server/handlers/workflow-builder.js +1 -1
  219. package/dist/server/handlers/workflows.cjs +1 -1
  220. package/dist/server/handlers/workflows.js +1 -1
  221. package/dist/server/handlers/workspace.cjs +1 -1
  222. package/dist/server/handlers/workspace.js +1 -1
  223. package/dist/server/handlers.cjs +16 -16
  224. package/dist/server/handlers.js +16 -16
  225. package/dist/server/schemas/index.cjs +1 -1
  226. package/dist/server/schemas/index.js +1 -1
  227. package/dist/server/schemas/schedules.d.ts +26 -8
  228. package/dist/server/schemas/schedules.d.ts.map +1 -1
  229. package/dist/server/schemas/system.d.ts +2 -0
  230. package/dist/server/schemas/system.d.ts.map +1 -1
  231. package/dist/server/server-adapter/api-schema-manifest.d.ts +1 -1
  232. package/dist/server/server-adapter/index.cjs +4 -4
  233. package/dist/server/server-adapter/index.js +4 -4
  234. package/dist/server/server-adapter/openapi-utils.d.ts +1 -1
  235. package/dist/server/server-adapter/routes/observability.d.ts +4 -1
  236. package/dist/server/server-adapter/routes/observability.d.ts.map +1 -1
  237. package/dist/server/server-adapter/routes/system.d.ts +2 -0
  238. package/dist/server/server-adapter/routes/system.d.ts.map +1 -1
  239. package/dist/{system-sUWFGBbT.js → system-DlW760k2.js} +2 -1
  240. package/dist/system-DlW760k2.js.map +1 -0
  241. package/dist/{system-C7u6PhUj.cjs → system-zL047vEq.cjs} +2 -1
  242. package/dist/system-zL047vEq.cjs.map +1 -0
  243. package/dist/{tools-DeHsVuWZ.js → tools-BJFq9JKF.js} +5 -5
  244. package/dist/{tools-DeHsVuWZ.js.map → tools-BJFq9JKF.js.map} +1 -1
  245. package/dist/{tools-DszNVjKC.cjs → tools-Daot5Zgz.cjs} +6 -6
  246. package/dist/{tools-DszNVjKC.cjs.map → tools-Daot5Zgz.cjs.map} +1 -1
  247. package/dist/{utils-CL-m2SWZ.cjs → utils-DptI_ERr.cjs} +5 -5
  248. package/dist/{utils-CL-m2SWZ.cjs.map → utils-DptI_ERr.cjs.map} +1 -1
  249. package/dist/{utils-y-cW3mQU.js → utils-yedETkNk.js} +2 -2
  250. package/dist/{utils-y-cW3mQU.js.map → utils-yedETkNk.js.map} +1 -1
  251. package/dist/{vector-BWFSDXvg.js → vector-CZ26vo6u.js} +2 -2
  252. package/dist/{vector-BWFSDXvg.js.map → vector-CZ26vo6u.js.map} +1 -1
  253. package/dist/{vector-6k7Ft7EX.cjs → vector-DBe45tnv.cjs} +2 -2
  254. package/dist/{vector-6k7Ft7EX.cjs.map → vector-DBe45tnv.cjs.map} +1 -1
  255. package/dist/{workflow-builder-BUQfzD4L.js → workflow-builder-C5ufahUw.js} +2 -2
  256. package/dist/{workflow-builder-BUQfzD4L.js.map → workflow-builder-C5ufahUw.js.map} +1 -1
  257. package/dist/{workflow-builder-C6J_1s56.cjs → workflow-builder-CkrdTcoM.cjs} +2 -2
  258. package/dist/{workflow-builder-C6J_1s56.cjs.map → workflow-builder-CkrdTcoM.cjs.map} +1 -1
  259. package/dist/{workflows-CHUG5jh4.cjs → workflows-B5uWFrJ1.cjs} +3 -3
  260. package/dist/{workflows-CHUG5jh4.cjs.map → workflows-B5uWFrJ1.cjs.map} +1 -1
  261. package/dist/{workflows-BkTNzH-i.js → workflows-C_Mqj_80.js} +3 -3
  262. package/dist/{workflows-BkTNzH-i.js.map → workflows-C_Mqj_80.js.map} +1 -1
  263. package/dist/{workspace-CYwDvH0G.js → workspace-BwlPQO3M.js} +2 -2
  264. package/dist/{workspace-CYwDvH0G.js.map → workspace-BwlPQO3M.js.map} +1 -1
  265. package/dist/{workspace-C7PytFzz.cjs → workspace-CD9pQ61P.cjs} +2 -2
  266. package/dist/{workspace-C7PytFzz.cjs.map → workspace-CD9pQ61P.cjs.map} +1 -1
  267. package/package.json +5 -5
  268. package/dist/dist-CDQ0dDmK.js +0 -1
  269. package/dist/memory-B_qwCpu5.js.map +0 -1
  270. package/dist/memory-BfabRYCo.cjs.map +0 -1
  271. package/dist/observability-new-endpoints--h0vACab.cjs.map +0 -1
  272. package/dist/observability-new-endpoints-B42gwVg4.js.map +0 -1
  273. package/dist/schedules-CvWX2yKR.cjs.map +0 -1
  274. package/dist/schedules-D9CKB18-.js.map +0 -1
  275. package/dist/system-C7u6PhUj.cjs.map +0 -1
  276. package/dist/system-sUWFGBbT.js.map +0 -1
  277. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/_types/@internal_ai-sdk-v4@0.0.95/dist/index.d.ts +0 -0
  278. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/_types/@internal_ai-sdk-v5@0.0.95/dist/index.d.ts +0 -0
  279. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/_types/@internal_ai-v6@0.0.95/dist/index.d.ts +0 -0
  280. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/_types/@standard-schema_spec@1.1.0/dist/index.d.ts +0 -0
  281. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/_types/@types_json-schema@7.0.15/index.d.ts +0 -0
  282. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/index.d.ts +0 -0
  283. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/null-to-undefined.d.ts +0 -0
  284. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/provider-compats/anthropic.d.ts +0 -0
  285. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/provider-compats/deepseek.d.ts +0 -0
  286. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/provider-compats/google.d.ts +0 -0
  287. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/provider-compats/meta.d.ts +0 -0
  288. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/provider-compats/openai-reasoning.d.ts +0 -0
  289. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/provider-compats/openai.d.ts +0 -0
  290. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/schema-compatibility-v3.d.ts +0 -0
  291. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/schema-compatibility-v4.d.ts +0 -0
  292. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/schema-compatibility.d.ts +0 -0
  293. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/schema.d.ts +0 -0
  294. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/schema.types.d.ts +0 -0
  295. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/standard-schema/standard-schema.d.ts +0 -0
  296. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/standard-schema/standard-schema.types.d.ts +0 -0
  297. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/standard-schema-compat.d.ts +0 -0
  298. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/types.d.ts +0 -0
  299. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/utils.d.ts +0 -0
  300. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/dist/zod-to-json.d.ts +0 -0
  301. /package/dist/_types/{@mastra_schema-compat@1.3.18-alpha.0 → @mastra_schema-compat@1.4.0-alpha.1}/package.json +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"editor-builder-BTi2EIB1.cjs","names":["agentFeaturesSchema","HTTPException","createRoute","builderSettingsResponseSchema","handleError","builderAvailableModelsResponseSchema","buildProvidersList","infrastructureStatusResponseSchema"],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAC9C,OA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O;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"editor-builder-Cqw1npOK.cjs","names":["agentFeaturesSchema","HTTPException","createRoute","builderSettingsResponseSchema","handleError","builderAvailableModelsResponseSchema","buildProvidersList","infrastructureStatusResponseSchema"],"sources":["../src/server/utils/resolve-builder-model-policy.ts","../src/server/handlers/editor-builder.ts"],"sourcesContent":["import type { BuilderModelPolicy } from '@mastra/core/agent-builder/ee';\nimport type { IMastraEditor } from '@mastra/core/editor';\n\n/**\n * Server-side wrapper around `builderToModelPolicy`.\n *\n * Handles the optional `IMastraEditor` builder API surface (older / OSS editors\n * may not implement `hasEnabledBuilderConfig` / `resolveBuilder`) and returns\n * a uniform `BuilderModelPolicy` to every call site.\n *\n * Returns `{ active: false }` whenever:\n * - no editor is configured,\n * - the editor doesn't expose builder methods,\n * - the builder config is disabled, or\n * - resolving the builder fails / yields nothing.\n *\n * The `@mastra/core/agent-builder/ee` subpath is loaded lazily so this module\n * remains importable on `@mastra/core` versions that pre-date the subpath\n * (the subpath was added in core 1.34.0). The dynamic import is only reached\n * once an editor is actually configured, by which point a compatible core is\n * guaranteed.\n */\nexport async function resolveBuilderModelPolicy(editor: IMastraEditor | undefined): Promise<BuilderModelPolicy> {\n if (!editor) return { active: false };\n if (typeof editor.resolveBuilder !== 'function') return { active: false };\n if (typeof editor.hasEnabledBuilderConfig === 'function' && !editor.hasEnabledBuilderConfig()) {\n return { active: false };\n }\n\n // Degrade to inactive on builder-resolution failure rather than letting the\n // rejection escape: agent execution routes seed this on every request, so a\n // transient failure must not 500 the entire route.\n try {\n const builder = await editor.resolveBuilder();\n const { builderToModelPolicy } = await import('@mastra/core/agent-builder/ee');\n return builderToModelPolicy(builder);\n } catch {\n return { active: false };\n }\n}\n","import type { Mastra } from '@mastra/core';\nimport type { ChannelProvider } from '@mastra/core/channels';\n\nimport { HTTPException } from '../http-exception';\nimport {\n agentFeaturesSchema,\n builderAvailableModelsResponseSchema,\n builderSettingsResponseSchema,\n infrastructureStatusResponseSchema,\n} from '../schemas/editor-builder';\nimport type { AgentFeatures, InfrastructureStatus } from '../schemas/editor-builder';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { resolveBuilderModelPolicy } from '../utils/resolve-builder-model-policy';\nimport { buildProvidersList } from './agents';\nimport { handleError } from './error';\n\n/**\n * Resolve the active builder feature flags. Returns `null` when the editor is\n * absent, the builder is disabled, or no features are configured.\n */\nasync function resolveBuilderFeatures(mastra: Mastra): Promise<AgentFeatures | null> {\n const editor = mastra.getEditor();\n if (!editor || typeof editor.resolveBuilder !== 'function') return null;\n if (!editor.hasEnabledBuilderConfig?.()) return null;\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) return null;\n const features = builder.getFeatures?.()?.agent;\n if (!features) return null;\n // Validate the shape so unknown keys cannot smuggle through.\n const parsed = agentFeaturesSchema.safeParse(features);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Returns whether a given agent-builder feature is enabled. Used by list /\n * get-by-id handlers to soft-gate response enrichment (omit fields, ignore\n * favoritedOnly / pinFavoritedFor params) when the feature is off.\n */\nexport async function isBuilderFeatureEnabled(mastra: Mastra, feature: keyof AgentFeatures): Promise<boolean> {\n const features = await resolveBuilderFeatures(mastra);\n return features?.[feature] === true;\n}\n\n/**\n * Hard-gate helper for mutation routes that must not exist when the feature\n * is off. Throws `HTTPException(404)` so we don't leak the existence of the\n * feature surface (matches behavior of unregistered routes).\n */\nexport async function requireBuilderFeature(mastra: Mastra, feature: keyof AgentFeatures): Promise<void> {\n if (!(await isBuilderFeatureEnabled(mastra, feature))) {\n throw new HTTPException(404, { message: 'Not Found' });\n }\n}\n\n/**\n * GET /editor/builder/settings\n *\n * Returns the agent builder settings configured by the admin.\n * Used by frontend to determine which features to display.\n */\nexport const GET_EDITOR_BUILDER_SETTINGS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/settings',\n responseType: 'json',\n responseSchema: builderSettingsResponseSchema,\n summary: 'Get agent builder settings',\n description: 'Returns the agent builder feature flags and configuration for UI gating',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n const editor = mastra.getEditor();\n\n // No editor configured\n if (!editor) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Editor doesn't support builder (older version or OSS)\n if (typeof editor.resolveBuilder !== 'function') {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Check if builder is enabled in config\n if (!editor.hasEnabledBuilderConfig?.()) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n // Resolve the builder instance\n const builder = await editor.resolveBuilder();\n if (!builder || !builder.enabled) {\n return { enabled: false, modelPolicy: { active: false } };\n }\n\n const baseWarnings = builder.getModelPolicyWarnings?.() ?? [];\n const configuration = builder.getConfiguration();\n\n // Picker allowlists are written against entity `.id` (what users see in\n // the UI, URLs, traces). The client filters list responses by their\n // response keys, which are not always `.id`:\n // - GET /agents keys by `agent.id`\n // - GET /tools keys by registration key (values include `id`)\n // - GET /workflows keys by registration key (values omit `id`)\n // To keep the client filter simple, we accept `.id` (fallback to\n // registration key) for matching, but emit visible IDs as response keys\n // so `Object.keys(data)` lines up.\n type AliasPair = { id: string; key: string };\n const collectAliases = (registry: Record<string, unknown>): AliasPair[] =>\n Object.entries(registry).map(([key, entity]) => ({\n id: (entity as { id?: string }).id || key,\n key,\n }));\n\n const toolAliases = collectAliases(mastra.listTools() ?? {});\n const agentAliases = collectAliases(mastra.listAgents() ?? {});\n const workflowAliases = collectAliases(mastra.listWorkflows() ?? {});\n\n // Tools/workflows responses are keyed by registration key. Agents\n // response is keyed by `.id`.\n const toResponseKey = (aliases: AliasPair[], byId: 'id' | 'key') => {\n const map = new Map<string, string>();\n for (const a of aliases) {\n map.set(a.id, byId === 'id' ? a.id : a.key);\n map.set(a.key, byId === 'id' ? a.id : a.key);\n }\n return map;\n };\n const toolKeyMap = toResponseKey(toolAliases, 'key');\n const agentKeyMap = toResponseKey(agentAliases, 'id');\n const workflowKeyMap = toResponseKey(workflowAliases, 'key');\n\n // Lazy-load the EE subpath so this module remains importable on\n // `@mastra/core` versions that pre-date it (added in core 1.34.0).\n // We only reach here after `builder.enabled` is true, which guarantees\n // a compatible core.\n const { builderToModelPolicy, resolvePickerVisibility } = await import('@mastra/core/agent-builder/ee');\n\n const picker = resolvePickerVisibility({\n config: configuration?.agent,\n registeredToolIds: toolAliases.flatMap(a => [a.id, a.key]),\n registeredAgentIds: agentAliases.flatMap(a => [a.id, a.key]),\n registeredWorkflowIds: workflowAliases.flatMap(a => [a.id, a.key]),\n });\n\n const normalize = (visible: string[] | null, map: Map<string, string>): string[] | null => {\n if (visible === null) return null;\n const out: string[] = [];\n const seen = new Set<string>();\n for (const id of visible) {\n const mapped = map.get(id);\n if (mapped && !seen.has(mapped)) {\n seen.add(mapped);\n out.push(mapped);\n }\n }\n return out;\n };\n\n const modelPolicyWarnings = [...baseWarnings, ...picker.warnings];\n\n return {\n enabled: true,\n features: builder.getFeatures(),\n configuration,\n modelPolicy: builderToModelPolicy(builder),\n picker: {\n visibleTools: normalize(picker.visibleTools, toolKeyMap),\n visibleAgents: normalize(picker.visibleAgents, agentKeyMap),\n visibleWorkflows: normalize(picker.visibleWorkflows, workflowKeyMap),\n },\n ...(modelPolicyWarnings.length > 0 ? { modelPolicyWarnings } : {}),\n };\n } catch (error) {\n return handleError(error, 'Error getting builder settings');\n }\n },\n});\n\n/**\n * GET /editor/builder/models/available\n *\n * Returns the configured AI providers/models the agent builder may use. The\n * server is the single authority: it scopes the list to providers with a\n * configured API key (`connected`) and applies the active builder model\n * policy via `isModelAllowed`, so the Studio surfaces can render the response\n * verbatim without importing any EE matcher into the browser.\n *\n * - Providers without a configured API key are always omitted — the builder\n * decides the agent's model from this list, so an unconnected provider would\n * produce an agent that can never run.\n * - Policy inactive (or no allowlist) ⇒ all connected providers are returned.\n * - Policy active with an allowlist ⇒ each connected provider's models are\n * filtered, and providers left with no allowed models are omitted entirely.\n */\nexport const GET_EDITOR_BUILDER_AVAILABLE_MODELS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/models/available',\n responseType: 'json',\n responseSchema: builderAvailableModelsResponseSchema,\n summary: 'List builder-available AI models',\n description: 'Returns AI providers/models filtered by the active agent-builder model policy.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'stored-agents:read',\n handler: async ({ mastra }) => {\n try {\n // Only surface providers whose API key is configured (`connected`). The\n // agent builder decides the agent's model from this list, so including\n // providers without a key lets it pick a model that can never run. We\n // scope to connected providers so every choice is actually usable.\n const providers = (await buildProvidersList(mastra)).filter(provider => provider.connected);\n const policy = await resolveBuilderModelPolicy(mastra.getEditor());\n\n // Inactive policy (or no allowlist) ⇒ no allowlist filtering to apply.\n if (!policy.active || !policy.allowed || policy.allowed.length === 0) {\n return { providers };\n }\n\n // Lazy-load the EE matcher (server-only); mirrors the convention used by\n // resolve-builder-model-policy and the settings handler.\n const { isModelAllowed } = await import('@mastra/core/agent-builder/ee');\n\n const filtered = providers\n .map(provider => ({\n ...provider,\n models: provider.models.filter(modelId => isModelAllowed(policy.allowed, { provider: provider.id, modelId })),\n }))\n .filter(provider => provider.models.length > 0);\n\n return { providers: filtered };\n } catch (error) {\n return handleError(error, 'Error fetching available models');\n }\n },\n});\n\n/**\n * GET /editor/builder/infrastructure\n *\n * Returns the runtime status of Mastra-opinionated primitives (channels,\n * browser providers, workspaces). Admin-only; surfaced in Studio Settings so\n * admins can sanity-check what's wired up to the running server.\n */\nexport const GET_INFRASTRUCTURE_STATUS_ROUTE = createRoute({\n method: 'GET',\n path: '/editor/builder/infrastructure',\n responseType: 'json',\n responseSchema: infrastructureStatusResponseSchema,\n summary: 'Get infrastructure status',\n description: 'Agent Builder infrastructure configuration and lightweight runtime status.',\n tags: ['Editor'],\n requiresAuth: true,\n requiresPermission: 'infrastructure:read',\n handler: async ({ mastra }) => {\n try {\n const formatConfigValue = (value: unknown): string => {\n if (value === null || value === undefined) return 'not set';\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;\n return value.constructor?.name && value.constructor.name !== 'Object' ? value.constructor.name : 'configured';\n };\n\n const getProviderName = (value: unknown): string | null => {\n if (!value) return null;\n if (typeof value === 'object' && 'provider' in value && typeof value.provider === 'string')\n return value.provider;\n if (typeof value === 'object' && 'constructor' in value) {\n const name = (value as { constructor?: { name?: string } }).constructor?.name;\n return name && name !== 'Object' ? name : 'configured';\n }\n return null;\n };\n\n const getConfigEntries = (config: Record<string, unknown>, omittedKeys: string[] = []) =>\n Object.entries(config)\n .filter(([key, value]) => !omittedKeys.includes(key) && value !== undefined && value !== null)\n .map(([key, value]) => ({ key, value: formatConfigValue(value) }));\n\n // Prefer resolveChannels() so a live channels resolver (e.g. @mastra/connect's\n // channels()) reports connections added after boot; older cores lack the method.\n const mastraWithResolver = mastra as typeof mastra & {\n resolveChannels?: () => Promise<Record<string, ChannelProvider>>;\n };\n const channelProviders =\n typeof mastraWithResolver.resolveChannels === 'function'\n ? await mastraWithResolver.resolveChannels()\n : (mastra.getChannelProviders() ?? {});\n const channels: InfrastructureStatus['channels'] = {\n providers: Object.entries(channelProviders)\n .map(([id, provider]) => {\n const info = provider.getInfo?.();\n const routes = provider.getRoutes?.() ?? [];\n return {\n id: info?.id ?? id,\n name: info?.name ?? id,\n isConfigured: info?.isConfigured ?? false,\n routeCount: routes.length,\n };\n })\n .filter(provider => provider.isConfigured),\n };\n\n const editor = mastra.getEditor();\n let browser: InfrastructureStatus['browser'] = {\n type: null,\n provider: null,\n env: null,\n registered: false,\n availableProviders: [],\n config: [],\n };\n let workspace: InfrastructureStatus['workspace'] = {\n type: null,\n workspaceId: null,\n name: null,\n source: null,\n registered: false,\n hasFilesystem: false,\n hasSandbox: false,\n filesystemProvider: null,\n sandboxProvider: null,\n config: [],\n };\n let registries: InfrastructureStatus['registries'] = {\n skillsSh: { enabled: false },\n };\n\n if (editor?.resolveBuilder) {\n const browsers = (editor as unknown as { __browsers?: Map<string, unknown> }).__browsers;\n const builder = await editor.resolveBuilder();\n const builderRegistries = builder?.getRegistries?.();\n registries = {\n skillsSh: { enabled: builderRegistries?.skillsSh?.enabled === true },\n };\n const configuration = builder?.getConfiguration?.()?.agent as\n | {\n browser?: { type?: string; config?: { provider?: string; env?: string } };\n workspace?: {\n type?: string;\n workspaceId?: string;\n config?: { name?: string; filesystem?: unknown; sandbox?: unknown };\n };\n }\n | undefined;\n\n const browserRef = configuration?.browser;\n const browserConfig = browserRef?.config ?? {};\n const providerId = browserConfig.provider ?? null;\n browser = {\n type: browserRef?.type ?? null,\n provider: providerId,\n env: browserConfig.env ?? null,\n registered: providerId ? !!browsers?.has(providerId) : false,\n availableProviders: browsers ? Array.from(browsers.keys()) : [],\n config: getConfigEntries(browserConfig, ['provider', 'env']),\n };\n\n const workspaceRef = configuration?.workspace;\n const workspaceConfig = workspaceRef?.config ?? {};\n const registeredWorkspaces = mastra.listWorkspaces();\n const registeredWorkspace = workspaceRef?.workspaceId\n ? registeredWorkspaces[workspaceRef.workspaceId]\n : undefined;\n const filesystem = registeredWorkspace?.workspace.filesystem ?? workspaceConfig.filesystem;\n const sandbox = registeredWorkspace?.workspace.sandbox ?? workspaceConfig.sandbox;\n const filesystemConfig =\n typeof workspaceConfig.filesystem === 'object' &&\n workspaceConfig.filesystem &&\n 'config' in workspaceConfig.filesystem\n ? (workspaceConfig.filesystem.config as Record<string, unknown>)\n : {};\n const sandboxConfig =\n typeof workspaceConfig.sandbox === 'object' && workspaceConfig.sandbox && 'config' in workspaceConfig.sandbox\n ? (workspaceConfig.sandbox.config as Record<string, unknown>)\n : {};\n workspace = {\n type: workspaceRef?.type ?? null,\n workspaceId: workspaceRef?.workspaceId ?? null,\n name: workspaceConfig.name ?? registeredWorkspace?.workspace.name ?? null,\n source: registeredWorkspace?.source ?? null,\n registered: !!registeredWorkspace,\n hasFilesystem: !!filesystem,\n hasSandbox: !!sandbox,\n filesystemProvider: getProviderName(filesystem),\n sandboxProvider: getProviderName(sandbox),\n config: [\n ...getConfigEntries(filesystemConfig).map(entry => ({ ...entry, key: `filesystem.${entry.key}` })),\n ...getConfigEntries(sandboxConfig).map(entry => ({ ...entry, key: `sandbox.${entry.key}` })),\n ],\n };\n }\n\n return { channels, browser, workspace, registries };\n } catch (error) {\n return handleError(error, 'Error getting infrastructure status');\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,0BAA0B,QAAgE;CAC9G,IAAI,CAAC,QAAQ,OAAO,EAAE,QAAQ,MAAM;CACpC,IAAI,OAAO,OAAO,mBAAmB,YAAY,OAAO,EAAE,QAAQ,MAAM;CACxE,IAAI,OAAO,OAAO,4BAA4B,cAAc,CAAC,OAAO,wBAAwB,GAC1F,OAAO,EAAE,QAAQ,MAAM;CAMzB,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,eAAe;EAC5C,MAAM,EAAE,yBAAyB,MAAM,OAAO;EAC9C,OAAO,qBAAqB,OAAO;CACrC,QAAQ;EACN,OAAO,EAAE,QAAQ,MAAM;CACzB;AACF;;;;;;ACnBA,eAAe,uBAAuB,QAA+C;CACnF,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI,CAAC,UAAU,OAAO,OAAO,mBAAmB,YAAY,OAAO;CACnE,IAAI,CAAC,OAAO,0BAA0B,GAAG,OAAO;CAChD,MAAM,UAAU,MAAM,OAAO,eAAe;CAC5C,IAAI,CAAC,WAAW,CAAC,QAAQ,SAAS,OAAO;CACzC,MAAM,WAAW,QAAQ,cAAc,CAAC,EAAE;CAC1C,IAAI,CAAC,UAAU,OAAO;CAEtB,MAAM,SAASA,uBAAAA,oBAAoB,UAAU,QAAQ;CACrD,OAAO,OAAO,UAAU,OAAO,OAAO;AACxC;;;;;;AAOA,eAAsB,wBAAwB,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AAM,mBACJ,OAAO,gBAAgB,eAAe,YACtC,gBAAgB,cAChB,YAAY,gBAAgB,aACvB,gBAAgB,WAAW,SAC5B,CAAC;IACP,MAAM,gBACJ,OAAO,gBAAgB,YAAY,YAAY,gBAAgB,WAAW,YAAY,gBAAgB,UACjG,gBAAgB,QAAQ,SACzB,CAAC;IACP,YAAY;KACV,MAAM,cAAc,QAAQ;KAC5B,aAAa,cAAc,eAAe;KAC1C,MAAM,gBAAgB,QAAQ,qBAAqB,UAAU,QAAQ;KACrE,QAAQ,qBAAqB,UAAU;KACvC,YAAY,CAAC,CAAC;KACd,eAAe,CAAC,CAAC;KACjB,YAAY,CAAC,CAAC;KACd,oBAAoB,gBAAgB,UAAU;KAC9C,iBAAiB,gBAAgB,OAAO;KACxC,QAAQ,CACN,GAAG,iBAAiB,gBAAgB,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,cAAc,MAAM;KAAM,EAAE,GACjG,GAAG,iBAAiB,aAAa,CAAC,CAAC,KAAI,WAAU;MAAE,GAAG;MAAO,KAAK,WAAW,MAAM;KAAM,EAAE,CAC7F;IACF;GACF;GAEA,OAAO;IAAE;IAAU;IAAS;IAAW;GAAW;EACpD,SAAS,OAAO;GACd,OAAOH,8BAAAA,YAAY,OAAO,qCAAqC;EACjE;CACF;AACF,CAAC"}
@@ -562,9 +562,8 @@ const checkRules = async (rules, path, method, user) => {
562
562
  if (!pathMatchesRule(path, rule.path)) continue;
563
563
  if (rule.methods && !matchesOrIncludes(rule.methods, method)) continue;
564
564
  const condition = rule.condition;
565
- if (typeof condition === "function") {
566
- if (await Promise.resolve().then(() => condition(user)).catch(() => false)) return true;
567
- } else if (rule.allow) return true;
565
+ if (typeof condition === "function") return await Promise.resolve().then(() => condition(user)).then((result) => !!result).catch(() => false);
566
+ return !!rule.allow;
568
567
  }
569
568
  return false;
570
569
  };
@@ -665,4 +664,4 @@ Object.defineProperty(exports, "supportsSessionRefresh", {
665
664
  }
666
665
  });
667
666
 
668
- //# sourceMappingURL=helpers-D7d2R3LL.cjs.map
667
+ //# sourceMappingURL=helpers-0LJI4DxR.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers-D7d2R3LL.cjs","names":["Hono","HonoRequest","HTTPException","MASTRA_USER_KEY","MASTRA_AUTH_TOKEN_KEY","CompositeAuth","MASTRA_RESOURCE_ID_KEY","MASTRA_AUTH_MODE_KEY","MASTRA_USER_PERMISSIONS_KEY","MASTRA_USER_ROLES_KEY"],"sources":["../src/server/auth/custom-route-matcher.ts","../src/server/auth/defaults.ts","../src/server/auth/path-pattern.ts","../src/server/auth/helpers.ts"],"sourcesContent":["import { Hono } from 'hono';\nimport { HonoRequest } from 'hono/request';\n\n/** A custom route as the internal custom-route Hono app registers it. */\nexport interface CustomRouteMatcherEntry {\n method: string;\n path: string;\n /**\n * How many handlers (route middleware + handler) the route registers. Hono stores\n * each one as its own router entry, so mirror the count to build the same router.\n */\n handlerCount?: number;\n}\n\nexport interface CustomRouteMatch<T> {\n entry: T;\n index: number;\n params: Record<string, string>;\n}\n\ntype Marker = (...args: unknown[]) => undefined;\n\nconst noopMiddleware: Marker = () => undefined;\nconst paramRequest = new Request('http://localhost/');\n\n/**\n * Answers \"which custom route will run for this request?\" using the same Hono router\n * the custom-route bridge dispatches with (`buildCustomRouteHandler`), registered in\n * the same order with the same paths and methods. Auth decisions use this instead\n * of a separate pattern matcher, so they can't disagree with dispatch on precedence,\n * case, trailing slashes, percent-decoding or HEAD handling.\n */\nexport class CustomRouteMatcher<T extends CustomRouteMatcherEntry> {\n readonly #app = new Hono();\n readonly #indexByHandler = new Map<unknown, number>();\n readonly #entries: readonly T[];\n\n constructor(entries: readonly T[]) {\n this.#entries = entries;\n // Same global middleware as the custom-route app, so the router sees the same table.\n this.#app.use('*', noopMiddleware as never);\n entries.forEach((entry, index) => {\n const marker: Marker = () => undefined;\n this.#indexByHandler.set(marker, index);\n const handlers = Array.from({ length: Math.max(1, entry.handlerCount ?? 1) }, () => marker as never);\n if (entry.method === 'ALL') {\n this.#app.all(entry.path, handlers[0]!, ...handlers.slice(1));\n } else {\n this.#app.on(entry.method, entry.path, handlers[0]!, ...handlers.slice(1));\n }\n });\n }\n\n /**\n * Match a path the way Hono dispatches it, i.e. `path` is already in the form\n * `getPath()` returns (no query string, percent-decoded once).\n * Throws if Hono can't build a router for the registered paths.\n */\n matchPath(path: string, method: string): CustomRouteMatch<T> | undefined {\n const upper = method.toUpperCase();\n // Hono serves HEAD with the GET handler.\n const dispatchMethod = upper === 'HEAD' ? 'GET' : upper;\n const result = this.#app.router.match(dispatchMethod, path);\n const handlers = result[0];\n for (let i = 0; i < handlers.length; i++) {\n const index = this.#indexByHandler.get(handlers[i]![0][0]);\n if (index === undefined) continue; // the global middleware\n const request = new HonoRequest(paramRequest, path, result as never);\n request.routeIndex = i;\n return { entry: this.#entries[index]!, index, params: request.param() as Record<string, string> };\n }\n return undefined;\n }\n\n /**\n * Match the full URL handed to the custom-route app. Parses it the same way\n * (`new Request(url)` then Hono's `getPath`), so dot segments, encoded characters\n * and the query string are handled exactly as dispatch handles them.\n * Throws if the URL can't be parsed.\n */\n matchUrl(url: string, method: string): CustomRouteMatch<T> | undefined {\n const path = this.#app.getPath(new Request(url));\n return this.matchPath(path, method);\n }\n\n /**\n * Converts a raw request path (as Express/Koa/Fastify see it, not yet decoded) to\n * the path Hono would dispatch when the bridge forwards it. Throws on an\n * unparseable path.\n */\n dispatchPathForRawPath(rawPath: string): string {\n return this.#app.getPath(new Request(`http://localhost${rawPath}`));\n }\n}\n\nconst MAX_CACHED_MATCHERS = 32;\nconst matcherCache = new Map<string, CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }>>();\n\n/**\n * Builds (and caches) a matcher from `customRouteAuthConfig` keys. Keys are\n * `METHOD:path` in registration order, which is the order the server registers\n * custom routes with the custom-route app.\n */\nexport function getCustomRouteAuthConfigMatcher(\n keys: readonly string[],\n): CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }> {\n const signature = JSON.stringify(keys);\n const cached = matcherCache.get(signature);\n if (cached) {\n matcherCache.delete(signature);\n matcherCache.set(signature, cached);\n return cached;\n }\n\n const entries: Array<CustomRouteMatcherEntry & { key: string }> = [];\n for (const key of keys) {\n const colonIndex = key.indexOf(':');\n if (colonIndex === -1) continue; // malformed key\n entries.push({ key, method: key.substring(0, colonIndex).toUpperCase(), path: key.substring(colonIndex + 1) });\n }\n\n const matcher = new CustomRouteMatcher(entries);\n matcherCache.set(signature, matcher);\n if (matcherCache.size > MAX_CACHED_MATCHERS) {\n matcherCache.delete(matcherCache.keys().next().value!);\n }\n return matcher;\n}\n","import type { MastraAuthConfig } from '@mastra/core/server';\n\n// Default configuration that can be extended by clients\nexport const defaultAuthConfig: MastraAuthConfig = {\n protected: ['/api/*'],\n public: ['/api', '/api/auth/*'],\n // Simple rule system\n rules: [\n // Admin users can do anything\n {\n condition: user => {\n if (typeof user === 'object' && user !== null) {\n if ('isAdmin' in user) {\n return !!user.isAdmin;\n }\n\n if ('role' in user) {\n return user.role === 'admin';\n }\n }\n return false;\n },\n allow: true,\n },\n ],\n};\n","/**\n * Path pattern matching utility\n * Inlined from regexparam v3.0.0 (MIT License)\n * https://github.com/lukeed/regexparam\n *\n * Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport interface ParsedPattern {\n keys: string[] | false;\n pattern: RegExp;\n}\n\n/**\n * Parse a route pattern into a RegExp\n * Supports:\n * - Named parameters: /users/:id\n * - Optional parameters: /users/:id?\n * - Wildcards: /files/*\n * - Mixed patterns: /api/:version/users/:id\n */\nexport function parse(input: string | RegExp, loose?: boolean): ParsedPattern {\n if (input instanceof RegExp) return { keys: false, pattern: input };\n\n let c: string;\n let o: number;\n let tmp: string | undefined;\n let ext: number;\n const keys: string[] = [];\n let pattern = '';\n const arr = input.split('/');\n\n arr[0] || arr.shift();\n\n while ((tmp = arr.shift())) {\n c = tmp[0]!;\n if (c === '*') {\n keys.push(c);\n pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';\n } else if (c === ':') {\n o = tmp.indexOf('?', 1);\n ext = tmp.indexOf('.', 1);\n keys.push(tmp.substring(1, ~o ? o : ~ext ? ext : tmp.length));\n pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';\n if (~ext) pattern += (~o ? '?' : '') + '\\\\' + tmp.substring(ext);\n } else {\n // Escape regex metacharacters so static segments stay literal. Without this,\n // a public route like '/a.b' would also match '/axb' and could skip auth for\n // a later protected route the framework dispatches instead.\n pattern += '/' + tmp.replace(/([.+*?^${}()|[\\]\\\\])/g, '\\\\$1');\n }\n }\n\n return {\n keys: keys,\n pattern: new RegExp('^' + pattern + (loose ? '(?=$|/)' : '/?$'), 'i'),\n };\n}\n\n/**\n * Test if a path matches a pattern\n */\nexport function matchPath(path: string, pattern: string | RegExp): boolean {\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n}\n","import type { ISessionProvider } from '@mastra/core/auth';\nimport type { IRBACProvider, EEUser } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { CompositeAuth } from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, MastraAuthConfig, MastraAuthRequest } from '@mastra/core/server';\n\nimport {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n MASTRA_USER_ROLES_KEY,\n MASTRA_AUTH_TOKEN_KEY,\n MASTRA_AUTH_MODE_KEY,\n} from '../constants';\nimport { HTTPException } from '../http-exception';\nimport { CustomRouteMatcher, getCustomRouteAuthConfigMatcher } from './custom-route-matcher';\nimport { defaultAuthConfig } from './defaults';\nimport { parse } from './path-pattern';\n\n// Re-export request-context key constants so custom middleware can read namespaced\n// auth state without importing internal paths.\nexport { MASTRA_USER_KEY, MASTRA_USER_PERMISSIONS_KEY, MASTRA_USER_ROLES_KEY } from '../constants';\n\ntype CustomRouteAuthDecision = 'protected' | 'public' | 'none';\n\n/**\n * Decide auth for a request from the custom route the custom-route app will dispatch\n * it to (see `CustomRouteMatcher`), not from whichever pattern happens to match.\n *\n * Fails closed:\n * - an exact `METHOD:path` (or `ALL:path`) entry that requires auth always wins, so a\n * path registered as protected is never served without auth;\n * - `path` may be a raw request path (Express, Koa, Fastify) or one Hono already\n * decoded, so it's resolved both ways and is only public if every reading lands on\n * a public route, and protected if any reading lands on a protected one;\n * - if the routes or the path can't be parsed, the request is treated as protected.\n */\nconst resolveCustomRouteAuth = (\n path: string,\n method: string,\n customRouteAuthConfig: Map<string, boolean>,\n): CustomRouteAuthDecision => {\n const upperMethod = method.toUpperCase();\n const methods = upperMethod === 'HEAD' ? ['HEAD', 'GET'] : [upperMethod];\n for (const m of methods) {\n if (customRouteAuthConfig.get(`${m}:${path}`) === true || customRouteAuthConfig.get(`ALL:${path}`) === true) {\n return 'protected';\n }\n }\n\n // Adapters pin the current request by appending `METHOD:path` to a copy of the map.\n // As the last entry it only decides when no earlier route matches, so resolve the\n // rest with a cached matcher and fall back to it, instead of building a new router\n // for every request path.\n const keys = [...customRouteAuthConfig.keys()];\n const lastKey = keys[keys.length - 1];\n const pinnedKey =\n lastKey !== undefined && methods.some(m => lastKey === `${m}:${path}` || lastKey === `ALL:${path}`)\n ? lastKey\n : undefined;\n\n let matcher: ReturnType<typeof getCustomRouteAuthConfigMatcher>;\n const candidates = new Set<string>([path]);\n try {\n matcher = getCustomRouteAuthConfigMatcher(pinnedKey ? keys.slice(0, -1) : keys);\n candidates.add(matcher.dispatchPathForRawPath(path));\n } catch {\n return 'protected';\n }\n\n let matchedPublic = false;\n let unmatched = false;\n for (const candidate of candidates) {\n let key: string | undefined;\n try {\n key = matcher.matchPath(candidate, upperMethod)?.entry.key;\n } catch {\n return 'protected';\n }\n if (key === undefined && pinnedKey && candidate === path) {\n key = pinnedKey;\n }\n if (key === undefined) {\n unmatched = true;\n continue;\n }\n if (customRouteAuthConfig.get(key) !== false) {\n return 'protected';\n }\n matchedPublic = true;\n }\n\n return matchedPublic && !unmatched ? 'public' : 'none';\n};\n\n/**\n * Check if a request will be handled by a registered custom route that requires\n * authentication. The route that decides is the one the custom-route app dispatches\n * to (first registered match), using Hono's own matching. Returns false when no\n * custom route handles the request.\n */\nexport const isProtectedCustomRoute = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'protected';\n};\n\nconst apiRouteMatchers = new WeakMap<\n readonly ApiRoute[],\n { signature: string; matcher: CustomRouteMatcher<ApiRoute> }\n>();\n\n/**\n * Find the custom API route Hono dispatches `path` to, with its decoded path params.\n * `path` is in the form Hono's `c.req.path` returns (no query string, decoded once).\n * Matching follows Hono: first registered match wins, case-sensitive, strict\n * trailing slash, and HEAD is served by GET routes.\n */\nexport const findMatchingCustomRoute = (\n path: string,\n method: string,\n apiRoutes?: ApiRoute[],\n): { route: ApiRoute; params: Record<string, string> } | undefined => {\n if (!apiRoutes || apiRoutes.length === 0) return undefined;\n\n const signature = JSON.stringify(apiRoutes.map(route => `${route.method}:${route.path}`));\n let cached = apiRouteMatchers.get(apiRoutes);\n if (!cached || cached.signature !== signature) {\n cached = { signature, matcher: new CustomRouteMatcher(apiRoutes) };\n apiRouteMatchers.set(apiRoutes, cached);\n }\n\n try {\n const match = cached.matcher.matchPath(path, method);\n return match ? { route: match.entry, params: match.params } : undefined;\n } catch {\n // Hono can't route these paths either, so no custom route handles the request.\n return undefined;\n }\n};\n\n/**\n * Check if request is from dev playground\n * @param getHeader - Function to get header value from request\n * @param customRouteAuthConfig - Map of custom route auth configurations\n */\nexport const isDevPlaygroundRequest = (\n path: string,\n method: string,\n getHeader: (name: string) => string | undefined,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return (\n process.env.MASTRA_DEV === 'true' &&\n // Allow if path doesn't match protected patterns AND is not a protected custom route\n ((!isAnyMatch(path, method, protectedAccess) && !isProtectedCustomRoute(path, method, customRouteAuthConfig)) ||\n // Or if has playground header\n getHeader('x-mastra-dev-playground') === 'true')\n );\n};\n\n/**\n * Check if a request will be handled by a custom route registered as public\n * (`requiresAuth: false`). Uses the same dispatch-order resolution as\n * `isProtectedCustomRoute`, and returns false (not public) when no custom route\n * handles the request or the answer is ambiguous.\n */\nexport const isCustomRoutePublic = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'public';\n};\n\n// NOTE: This uses isProtectedCustomRoute (default-allow for unknown paths) rather than\n// !isCustomRoutePublic (default-deny). This is intentional — all registered server and\n// custom routes are auth-checked via registerRoute/checkRouteAuth regardless of this\n// function. The '/api/*' protected pattern exists as a user-facing override mechanism.\n// The old default-deny logic incorrectly blocked non-API paths (e.g. '/', '/agents')\n// which prevented the studio login page from loading in production.\nexport const isProtectedPath = (\n path: string,\n method: string,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return isAnyMatch(path, method, protectedAccess) || isProtectedCustomRoute(path, method, customRouteAuthConfig);\n};\n\nexport const canAccessPublicly = (path: string, method: string, authConfig: MastraAuthConfig): boolean => {\n // Check if this path+method combination is publicly accessible\n const publicAccess = [...(defaultAuthConfig.public || []), ...(authConfig.public || [])];\n\n return isAnyMatch(path, method, publicAccess);\n};\n\nconst isAnyMatch = (\n path: string,\n method: string,\n patterns: MastraAuthConfig['protected'] | MastraAuthConfig['public'],\n): boolean => {\n if (!patterns) {\n return false;\n }\n\n for (const patternPathOrMethod of patterns) {\n if (patternPathOrMethod instanceof RegExp) {\n if (patternPathOrMethod.test(path)) {\n return true;\n }\n }\n\n if (typeof patternPathOrMethod === 'string' && pathMatchesPattern(path, patternPathOrMethod)) {\n return true;\n }\n\n if (Array.isArray(patternPathOrMethod) && patternPathOrMethod.length === 2) {\n const [pattern, methodOrMethods] = patternPathOrMethod;\n if (pathMatchesPattern(path, pattern) && matchesOrIncludes(methodOrMethods, method)) {\n return true;\n }\n }\n }\n\n return false;\n};\n\nexport const pathMatchesPattern = (path: string, pattern: string): boolean => {\n // Use regexparam for battle-tested path matching\n // Supports:\n // - Exact paths: '/api/users'\n // - Wildcards: '/api/agents/*' matches '/api/agents/123'\n // - Path parameters: '/users/:id' matches '/users/123'\n // - Optional parameters: '/users/:id?' matches '/users' and '/users/123'\n // - Mixed patterns: '/api/:version/users/:id/profile'\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n};\n\nexport const pathMatchesRule = (path: string, rulePath: string | RegExp | string[] | undefined): boolean => {\n if (!rulePath) return true; // No path specified means all paths\n\n if (typeof rulePath === 'string') {\n return pathMatchesPattern(path, rulePath);\n }\n\n if (rulePath instanceof RegExp) {\n return rulePath.test(path);\n }\n\n if (Array.isArray(rulePath)) {\n return rulePath.some(p => pathMatchesPattern(path, p));\n }\n\n return false;\n};\n\nexport const matchesOrIncludes = (values: string | string[], value: string): boolean => {\n if (typeof values === 'string') {\n return values === value;\n }\n\n if (Array.isArray(values)) {\n return values.includes(value);\n }\n\n return false;\n};\n\n// ── Core auth middleware ──\n// Framework-agnostic auth logic extracted from adapter middlewares.\n// Each adapter builds an AuthMiddlewareContext and delegates to coreAuthMiddleware.\n\nexport interface AuthMiddlewareContext {\n path: string;\n method: string;\n getHeader: (name: string) => string | undefined;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: { get: (key: string) => unknown; set: (key: string, value: unknown) => void };\n rawRequest: MastraAuthRequest;\n token: string | null;\n buildAuthorizeContext: () => unknown;\n /** When true, force authentication even if the path matches a public pattern. */\n requiresAuth?: boolean;\n}\n\nexport type AuthResult =\n | { action: 'next'; headers?: Record<string, string> }\n | { action: 'error'; status: number; body: Record<string, unknown>; headers?: Record<string, string> };\n\nconst pass: AuthResult = { action: 'next' };\n\n/**\n * Lets an app's `authorize(path, method, user, context)` read `context.get('requestContext')` and\n * `context.get('mastra')` on every adapter, as it can on Hono, so per-caller values (the Knowledge scope) bind\n * the same way everywhere. Hono and NestJS contexts already answer `get`; Express, Fastify and Koa pass a web\n * Request, Elysia its own context, and adapters with no builder pass nothing.\n */\nconst withAuthorizeVariables = (\n base: unknown,\n ctx: Pick<AuthMiddlewareContext, 'mastra' | 'requestContext' | 'customRouteAuthConfig' | 'rawRequest'>,\n): unknown => {\n const variables: Record<string, unknown> = {\n mastra: ctx.mastra,\n requestContext: ctx.requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n };\n const get = (key: string) => variables[key];\n if (base === null || base === undefined) {\n return { get, req: ctx.rawRequest };\n }\n if (typeof base === 'object' && typeof (base as { get?: unknown }).get !== 'function') {\n Object.defineProperty(base, 'get', { value: get, configurable: true });\n }\n return base;\n};\n\nconst adaptToMastraAuthRequest = (request: MastraAuthRequest): MastraAuthRequest => {\n if (!(request instanceof Request)) {\n return request;\n }\n\n return {\n raw: request,\n headers: request.headers,\n header: name => request.headers.get(name) ?? undefined,\n };\n};\n\nexport interface GetAuthenticatedUserOptions {\n mastra: Mastra;\n token: string;\n request: MastraAuthRequest;\n}\n\nexport const getAuthenticatedUser = async <TUser = unknown>({\n mastra,\n token,\n request,\n}: GetAuthenticatedUserOptions): Promise<TUser | null> => {\n const normalizedToken = token.replace(/^Bearer\\s+/i, '').trim();\n if (!normalizedToken) {\n return null;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig || typeof authConfig.authenticateToken !== 'function') {\n return null;\n }\n\n return (await authConfig.authenticateToken(normalizedToken, request)) as TUser | null;\n};\n\n/**\n * Check if an auth config object supports transparent session refresh.\n * Returns true if the auth provider implements the necessary ISessionProvider methods.\n */\nexport function supportsSessionRefresh(\n authConfig: MastraAuthConfig | IMastraAuthProvider,\n): authConfig is (MastraAuthConfig | IMastraAuthProvider) &\n Pick<ISessionProvider, 'refreshSession' | 'getSessionIdFromRequest' | 'getSessionHeaders'> {\n return (\n typeof (authConfig as any).getSessionIdFromRequest === 'function' &&\n typeof (authConfig as any).refreshSession === 'function' &&\n typeof (authConfig as any).getSessionHeaders === 'function'\n );\n}\n\n/**\n * Single auth middleware: authenticate → authorize.\n * Skip checks (dev playground, unprotected path, public path) are evaluated once.\n */\nexport const coreAuthMiddleware = async (ctx: AuthMiddlewareContext): Promise<AuthResult> => {\n const {\n path,\n method,\n getHeader,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n token,\n requiresAuth,\n } = ctx;\n\n // ── Skip checks (evaluated once) ──\n\n // Only bypass auth for dev playground when no real auth provider is configured.\n // When auth IS configured (has authenticateToken), we need the full auth flow\n // so user/roles/permissions are set in requestContext.\n const hasAuthProvider = typeof authConfig.authenticateToken === 'function';\n if (!hasAuthProvider && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) {\n return pass;\n }\n\n if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {\n return pass;\n }\n\n // When a route explicitly requires auth (requiresAuth: true), skip the\n // public-path bypass so the user is still authenticated and permissions\n // are injected into the request context.\n if (\n !requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))\n ) {\n return pass;\n }\n\n // ── Authentication ──\n\n let user: unknown;\n let refreshHeaders: Record<string, string> | undefined;\n const authRequest = adaptToMastraAuthRequest(rawRequest);\n\n type ConsumePendingResponseHeadersFn = (request: typeof authRequest) => Record<string, string> | undefined;\n const mergePendingProviderHeaders = (request: typeof authRequest = authRequest) => {\n const consume = (authConfig as { consumePendingResponseHeaders?: ConsumePendingResponseHeadersFn })\n .consumePendingResponseHeaders;\n if (typeof consume !== 'function') return;\n let pending: Record<string, string> | undefined;\n try {\n pending = consume.call(authConfig, request);\n } catch {\n // Forwarding a rotated cookie is best-effort; never fail auth over it.\n return;\n }\n if (!pending) return;\n refreshHeaders = { ...(refreshHeaders ?? {}), ...pending };\n };\n\n try {\n if (typeof authConfig.authenticateToken === 'function') {\n user = await authConfig.authenticateToken(token ?? '', authRequest);\n mergePendingProviderHeaders();\n } else {\n throw new Error('No token verification method configured');\n }\n\n // If authentication failed, attempt transparent session refresh before returning 401.\n // This handles expired access tokens without requiring client-side refresh logic.\n if (!user && supportsSessionRefresh(authConfig) && rawRequest instanceof Request) {\n let retryHttpError: HTTPException | undefined;\n try {\n const sessionId = authConfig.getSessionIdFromRequest(rawRequest);\n if (sessionId) {\n const newSession = await authConfig.refreshSession(sessionId);\n if (newSession) {\n // Refresh succeeded — build updated session headers and re-authenticate.\n // We create a synthetic request with the new session cookie so\n // authenticateToken (which reads cookies from the request) picks up\n // the refreshed session instead of the expired one.\n refreshHeaders = authConfig.getSessionHeaders(newSession);\n const refreshedCookie = Object.entries(refreshHeaders)\n .filter(([k]) => k.toLowerCase() === 'set-cookie')\n .map(([, v]) => v.split(';')[0]) // Extract name=value before attributes\n .join('; ');\n if (refreshedCookie) {\n const refreshedRequest = new Request(rawRequest.url, {\n method: rawRequest.method,\n headers: new Headers(rawRequest.headers),\n });\n refreshedRequest.headers.set('Cookie', refreshedCookie);\n // Pass the refreshed cookie value as the token so authenticateToken\n // picks up the new session instead of the stale original.\n // Auth providers typically read cookies from the request object, but\n // some may also inspect the token parameter directly.\n const cookieValue = refreshedCookie.includes('=')\n ? refreshedCookie.split('=').slice(1).join('=')\n : refreshedCookie;\n try {\n const retryAuthRequest = adaptToMastraAuthRequest(refreshedRequest);\n user = await authConfig.authenticateToken(cookieValue, retryAuthRequest);\n mergePendingProviderHeaders(retryAuthRequest);\n } catch (retryErr) {\n retryHttpError = retryErr instanceof HTTPException ? retryErr : undefined;\n throw retryErr;\n }\n }\n if (!user) {\n refreshHeaders = undefined;\n }\n }\n }\n } catch (refreshErr) {\n refreshHeaders = undefined;\n // An explicit HTTP error from the retried authenticateToken goes to the outer handler.\n if (retryHttpError === refreshErr) throw refreshErr;\n mastra.getLogger()?.debug('Session refresh failed, falling back to 401', {\n error: refreshErr instanceof Error ? { message: refreshErr.message } : refreshErr,\n });\n }\n }\n\n if (!user) {\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n requestContext.set(MASTRA_USER_KEY, user);\n // Backward-compat: also write the legacy `'user'` key so existing\n // middleware and integrations that read `requestContext.get('user')`\n // (including built-in FGA route enforcement, memory handlers, and the\n // documented public surface) keep working. New code should prefer\n // `MASTRA_USER_KEY` to avoid collisions with caller-supplied keys.\n requestContext.set('user', user);\n\n // Store the raw auth token so downstream code (e.g., editor MCP client\n // resolution) can forward it when connecting to auth-protected MCP servers.\n // The token may arrive via Authorization header, apiKey query param, or\n // cookie (SimpleAuth sets `mastra-token`). Check all sources so the\n // forwarded value is available regardless of how the user authenticated.\n let effectiveToken = token;\n if (!effectiveToken && rawRequest instanceof Request) {\n const cookieHeader = rawRequest.headers.get('cookie');\n if (cookieHeader) {\n const match = cookieHeader.match(/mastra-token=([^;]+)/);\n if (match?.[1]) effectiveToken = match[1];\n }\n }\n if (effectiveToken) {\n requestContext.set(MASTRA_AUTH_TOKEN_KEY, effectiveToken);\n }\n\n if (typeof authConfig.mapUserToResourceId === 'function') {\n try {\n const resourceId = authConfig.mapUserToResourceId(user);\n // CompositeAuth validates the authenticating provider's mapper. It can\n // return undefined when that provider never configured a mapper.\n if (resourceId !== undefined || !(authConfig instanceof CompositeAuth)) {\n if (typeof resourceId !== 'string' || !resourceId.trim()) {\n throw new Error('mapUserToResourceId must return a non-empty string for the authenticated user');\n }\n requestContext.set(MASTRA_RESOURCE_ID_KEY, resourceId);\n }\n } catch (mapError) {\n mastra.getLogger()?.error('mapUserToResourceId failed', {\n error: mapError instanceof Error ? { message: mapError.message, stack: mapError.stack } : mapError,\n });\n return {\n action: 'error',\n status: 500,\n body: { error: 'Failed to map authenticated user to a resource ID' },\n headers: refreshHeaders,\n };\n }\n }\n\n try {\n // Determine which RBAC provider to use based on auth mode\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);\n const serverConfig = mastra.getServer();\n const studioConfig = mastra.getStudio?.();\n // Use studio RBAC if this is a studio request, otherwise use server RBAC\n const rbacProvider = (authMode === 'studio' ? (studioConfig?.rbac ?? serverConfig?.rbac) : serverConfig?.rbac) as\n | IRBACProvider<EEUser>\n | undefined;\n\n if (rbacProvider) {\n if (!user || typeof user !== 'object' || !('id' in user)) {\n mastra.getLogger()?.warn('RBAC: authenticated user missing required \"id\" field, skipping permission loading');\n } else {\n const permissions = await rbacProvider.getPermissions(user as EEUser);\n requestContext.set(MASTRA_USER_PERMISSIONS_KEY, permissions);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userPermissions', permissions);\n\n const roles = await rbacProvider.getRoles(user as EEUser);\n requestContext.set(MASTRA_USER_ROLES_KEY, roles);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userRoles', roles);\n }\n }\n } catch (rbacError) {\n mastra.getLogger()?.error('RBAC: failed to load user permissions/roles', {\n error: rbacError instanceof Error ? { message: rbacError.message, stack: rbacError.stack } : rbacError,\n });\n }\n } catch (err) {\n mastra.getLogger()?.error('Authentication error', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n // Explicit HTTP errors from auth callbacks keep their status/message; anything else is redacted.\n // The HTTPException message is sent to the client, so callers must keep it safe (no internal details).\n if (err instanceof HTTPException && err.status >= 400 && err.status <= 599) {\n return { action: 'error', status: err.status, body: { error: err.message }, headers: refreshHeaders };\n }\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n // ── Authorization ──\n\n const authorizationError = await authorizeAuthenticatedUser({\n path,\n method,\n user,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n buildAuthorizeContext: ctx.buildAuthorizeContext,\n });\n if (authorizationError) {\n return { action: 'error', ...authorizationError, headers: refreshHeaders };\n }\n\n return refreshHeaders ? { action: 'next', headers: refreshHeaders } : pass;\n};\n\nexport interface AuthorizeAuthenticatedUserContext {\n path: string;\n method: string;\n user: unknown;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: AuthMiddlewareContext['requestContext'];\n rawRequest: MastraAuthRequest;\n buildAuthorizeContext: () => unknown;\n}\n\n/**\n * The authorization step of server auth for an already authenticated user:\n * `authorizeUser`, `authorize(path, method, user)`, `rules`, or the RBAC default rules.\n * Returns null when the user may access `method path`.\n */\nexport const authorizeAuthenticatedUser = async (\n ctx: AuthorizeAuthenticatedUserContext,\n): Promise<{ status: number; body: Record<string, unknown> } | null> => {\n const { path, method, user, mastra, authConfig, requestContext, rawRequest } = ctx;\n const denied = { status: 403, body: { error: 'Access denied' } };\n\n if ('authorizeUser' in authConfig && typeof authConfig.authorizeUser === 'function') {\n try {\n const isAuthorized = await authConfig.authorizeUser(user, adaptToMastraAuthRequest(rawRequest));\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorizeUser', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('authorize' in authConfig && typeof authConfig.authorize === 'function') {\n try {\n const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(), {\n mastra,\n requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n rawRequest,\n });\n const isAuthorized = await authConfig.authorize(path, method, user, authorizeCtx as any);\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorize', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n path,\n method,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('rules' in authConfig && authConfig.rules && authConfig.rules.length > 0) {\n return (await checkRules(authConfig.rules, path, method, user)) ? null : denied;\n }\n\n // No explicit authorization configured (authorizeUser, authorize, or rules)\n // Check if RBAC is configured - if not, allow authenticated users through\n // (auth-only mode = authenticated users get full access)\n const rbacProvider =\n requestContext.get(MASTRA_AUTH_MODE_KEY) === 'studio'\n ? (mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac)\n : mastra.getServer()?.rbac;\n if (rbacProvider) {\n if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {\n return (await checkRules(defaultAuthConfig.rules, path, method, user)) ? null : denied;\n }\n return denied;\n }\n\n return null;\n};\n\n// Check authorization rules\nexport const checkRules = async (\n rules: MastraAuthConfig['rules'],\n path: string,\n method: string,\n user: unknown,\n): Promise<boolean> => {\n // Go through rules in order (first match wins)\n for (const i in rules || []) {\n const rule = rules?.[i]!;\n // Check if rule applies to this path\n if (!pathMatchesRule(path, rule.path)) {\n continue;\n }\n\n // Check if rule applies to this method\n if (rule.methods && !matchesOrIncludes(rule.methods, method)) {\n continue;\n }\n\n // Rule matches, check conditions\n const condition = rule.condition;\n if (typeof condition === 'function') {\n const allowed = await Promise.resolve()\n .then(() => condition(user))\n .catch(() => false);\n\n if (allowed) {\n return true;\n }\n } else if (rule.allow) {\n return true;\n }\n }\n\n // No matching rules, deny by default\n return false;\n};\n"],"mappings":";;;;;;AAsBA,MAAM,uBAA+B,KAAA;AACrC,MAAM,eAAe,IAAI,QAAQ,mBAAmB;;;;;;;;AASpD,IAAa,qBAAb,MAAmE;CACjE,OAAgB,IAAIA,KAAAA,KAAK;CACzB,kCAA2B,IAAI,IAAqB;CACpD;CAEA,YAAY,SAAuB;EACjC,KAAK,WAAW;EAEhB,KAAK,KAAK,IAAI,KAAK,cAAuB;EAC1C,QAAQ,SAAS,OAAO,UAAU;GAChC,MAAM,eAAuB,KAAA;GAC7B,KAAK,gBAAgB,IAAI,QAAQ,KAAK;GACtC,MAAM,WAAW,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,GAAG,MAAM,gBAAgB,CAAC,EAAE,SAAS,MAAe;GACnG,IAAI,MAAM,WAAW,OACnB,KAAK,KAAK,IAAI,MAAM,MAAM,SAAS,IAAK,GAAG,SAAS,MAAM,CAAC,CAAC;QAE5D,KAAK,KAAK,GAAG,MAAM,QAAQ,MAAM,MAAM,SAAS,IAAK,GAAG,SAAS,MAAM,CAAC,CAAC;EAE7E,CAAC;CACH;;;;;;CAOA,UAAU,MAAc,QAAiD;EACvE,MAAM,QAAQ,OAAO,YAAY;EAEjC,MAAM,iBAAiB,UAAU,SAAS,QAAQ;EAClD,MAAM,SAAS,KAAK,KAAK,OAAO,MAAM,gBAAgB,IAAI;EAC1D,MAAM,WAAW,OAAO;EACxB,KAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;GACxC,MAAM,QAAQ,KAAK,gBAAgB,IAAI,SAAS,EAAE,CAAE,EAAE,CAAC,EAAE;GACzD,IAAI,UAAU,K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AAM,WAAW,WAAW,OAAO,MAAM,QAAQ,IAAI,IAAK,OAAO;CAU3E,IAHE,eAAe,IAAA,kBAAwB,MAAM,WACxC,OAAO,YAAY,CAAC,EAAE,QAAQ,OAAO,UAAU,CAAC,EAAE,OACnD,OAAO,UAAU,CAAC,EAAE,MACR;EAChB,IAAI,kBAAkB,SAAS,kBAAkB,MAAM,SAAS,GAC9D,OAAQ,MAAM,WAAW,kBAAkB,OAAO,MAAM,QAAQ,IAAI,IAAK,OAAO;EAElF,OAAO;CACT;CAEA,OAAO;AACT;AAGA,MAAa,aAAa,OACxB,OACA,MACA,QACA,SACqB;CAErB,KAAK,MAAM,KAAK,SAAS,CAAC,GAAG;EAC3B,MAAM,OAAO,QAAQ;EAErB,IAAI,CAAC,gBAAgB,MAAM,KAAK,IAAI,GAClC;EAIF,IAAI,KAAK,WAAW,CAAC,kBAAkB,KAAK,SAAS,MAAM,GACzD;EAIF,MAAM,YAAY,KAAK;EACvB,IAAI,OAAO,cAAc,YAKnB;OAAA,MAJkB,QAAQ,QAAQ,CAAC,CACpC,WAAW,UAAU,IAAI,CAAC,CAAC,CAC3B,YAAY,KAAK,GAGlB,OAAO;EAAA,OAEJ,IAAI,KAAK,OACd,OAAO;CAEX;CAGA,OAAO;AACT"}
1
+ {"version":3,"file":"helpers-0LJI4DxR.cjs","names":["Hono","HonoRequest","HTTPException","MASTRA_USER_KEY","MASTRA_AUTH_TOKEN_KEY","CompositeAuth","MASTRA_RESOURCE_ID_KEY","MASTRA_AUTH_MODE_KEY","MASTRA_USER_PERMISSIONS_KEY","MASTRA_USER_ROLES_KEY"],"sources":["../src/server/auth/custom-route-matcher.ts","../src/server/auth/defaults.ts","../src/server/auth/path-pattern.ts","../src/server/auth/helpers.ts"],"sourcesContent":["import { Hono } from 'hono';\nimport { HonoRequest } from 'hono/request';\n\n/** A custom route as the internal custom-route Hono app registers it. */\nexport interface CustomRouteMatcherEntry {\n method: string;\n path: string;\n /**\n * How many handlers (route middleware + handler) the route registers. Hono stores\n * each one as its own router entry, so mirror the count to build the same router.\n */\n handlerCount?: number;\n}\n\nexport interface CustomRouteMatch<T> {\n entry: T;\n index: number;\n params: Record<string, string>;\n}\n\ntype Marker = (...args: unknown[]) => undefined;\n\nconst noopMiddleware: Marker = () => undefined;\nconst paramRequest = new Request('http://localhost/');\n\n/**\n * Answers \"which custom route will run for this request?\" using the same Hono router\n * the custom-route bridge dispatches with (`buildCustomRouteHandler`), registered in\n * the same order with the same paths and methods. Auth decisions use this instead\n * of a separate pattern matcher, so they can't disagree with dispatch on precedence,\n * case, trailing slashes, percent-decoding or HEAD handling.\n */\nexport class CustomRouteMatcher<T extends CustomRouteMatcherEntry> {\n readonly #app = new Hono();\n readonly #indexByHandler = new Map<unknown, number>();\n readonly #entries: readonly T[];\n\n constructor(entries: readonly T[]) {\n this.#entries = entries;\n // Same global middleware as the custom-route app, so the router sees the same table.\n this.#app.use('*', noopMiddleware as never);\n entries.forEach((entry, index) => {\n const marker: Marker = () => undefined;\n this.#indexByHandler.set(marker, index);\n const handlers = Array.from({ length: Math.max(1, entry.handlerCount ?? 1) }, () => marker as never);\n if (entry.method === 'ALL') {\n this.#app.all(entry.path, handlers[0]!, ...handlers.slice(1));\n } else {\n this.#app.on(entry.method, entry.path, handlers[0]!, ...handlers.slice(1));\n }\n });\n }\n\n /**\n * Match a path the way Hono dispatches it, i.e. `path` is already in the form\n * `getPath()` returns (no query string, percent-decoded once).\n * Throws if Hono can't build a router for the registered paths.\n */\n matchPath(path: string, method: string): CustomRouteMatch<T> | undefined {\n const upper = method.toUpperCase();\n // Hono serves HEAD with the GET handler.\n const dispatchMethod = upper === 'HEAD' ? 'GET' : upper;\n const result = this.#app.router.match(dispatchMethod, path);\n const handlers = result[0];\n for (let i = 0; i < handlers.length; i++) {\n const index = this.#indexByHandler.get(handlers[i]![0][0]);\n if (index === undefined) continue; // the global middleware\n const request = new HonoRequest(paramRequest, path, result as never);\n request.routeIndex = i;\n return { entry: this.#entries[index]!, index, params: request.param() as Record<string, string> };\n }\n return undefined;\n }\n\n /**\n * Match the full URL handed to the custom-route app. Parses it the same way\n * (`new Request(url)` then Hono's `getPath`), so dot segments, encoded characters\n * and the query string are handled exactly as dispatch handles them.\n * Throws if the URL can't be parsed.\n */\n matchUrl(url: string, method: string): CustomRouteMatch<T> | undefined {\n const path = this.#app.getPath(new Request(url));\n return this.matchPath(path, method);\n }\n\n /**\n * Converts a raw request path (as Express/Koa/Fastify see it, not yet decoded) to\n * the path Hono would dispatch when the bridge forwards it. Throws on an\n * unparseable path.\n */\n dispatchPathForRawPath(rawPath: string): string {\n return this.#app.getPath(new Request(`http://localhost${rawPath}`));\n }\n}\n\nconst MAX_CACHED_MATCHERS = 32;\nconst matcherCache = new Map<string, CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }>>();\n\n/**\n * Builds (and caches) a matcher from `customRouteAuthConfig` keys. Keys are\n * `METHOD:path` in registration order, which is the order the server registers\n * custom routes with the custom-route app.\n */\nexport function getCustomRouteAuthConfigMatcher(\n keys: readonly string[],\n): CustomRouteMatcher<CustomRouteMatcherEntry & { key: string }> {\n const signature = JSON.stringify(keys);\n const cached = matcherCache.get(signature);\n if (cached) {\n matcherCache.delete(signature);\n matcherCache.set(signature, cached);\n return cached;\n }\n\n const entries: Array<CustomRouteMatcherEntry & { key: string }> = [];\n for (const key of keys) {\n const colonIndex = key.indexOf(':');\n if (colonIndex === -1) continue; // malformed key\n entries.push({ key, method: key.substring(0, colonIndex).toUpperCase(), path: key.substring(colonIndex + 1) });\n }\n\n const matcher = new CustomRouteMatcher(entries);\n matcherCache.set(signature, matcher);\n if (matcherCache.size > MAX_CACHED_MATCHERS) {\n matcherCache.delete(matcherCache.keys().next().value!);\n }\n return matcher;\n}\n","import type { MastraAuthConfig } from '@mastra/core/server';\n\n// Default configuration that can be extended by clients\nexport const defaultAuthConfig: MastraAuthConfig = {\n protected: ['/api/*'],\n public: ['/api', '/api/auth/*'],\n // Simple rule system\n rules: [\n // Admin users can do anything\n {\n condition: user => {\n if (typeof user === 'object' && user !== null) {\n if ('isAdmin' in user) {\n return !!user.isAdmin;\n }\n\n if ('role' in user) {\n return user.role === 'admin';\n }\n }\n return false;\n },\n allow: true,\n },\n ],\n};\n","/**\n * Path pattern matching utility\n * Inlined from regexparam v3.0.0 (MIT License)\n * https://github.com/lukeed/regexparam\n *\n * Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport interface ParsedPattern {\n keys: string[] | false;\n pattern: RegExp;\n}\n\n/**\n * Parse a route pattern into a RegExp\n * Supports:\n * - Named parameters: /users/:id\n * - Optional parameters: /users/:id?\n * - Wildcards: /files/*\n * - Mixed patterns: /api/:version/users/:id\n */\nexport function parse(input: string | RegExp, loose?: boolean): ParsedPattern {\n if (input instanceof RegExp) return { keys: false, pattern: input };\n\n let c: string;\n let o: number;\n let tmp: string | undefined;\n let ext: number;\n const keys: string[] = [];\n let pattern = '';\n const arr = input.split('/');\n\n arr[0] || arr.shift();\n\n while ((tmp = arr.shift())) {\n c = tmp[0]!;\n if (c === '*') {\n keys.push(c);\n pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';\n } else if (c === ':') {\n o = tmp.indexOf('?', 1);\n ext = tmp.indexOf('.', 1);\n keys.push(tmp.substring(1, ~o ? o : ~ext ? ext : tmp.length));\n pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';\n if (~ext) pattern += (~o ? '?' : '') + '\\\\' + tmp.substring(ext);\n } else {\n // Escape regex metacharacters so static segments stay literal. Without this,\n // a public route like '/a.b' would also match '/axb' and could skip auth for\n // a later protected route the framework dispatches instead.\n pattern += '/' + tmp.replace(/([.+*?^${}()|[\\]\\\\])/g, '\\\\$1');\n }\n }\n\n return {\n keys: keys,\n pattern: new RegExp('^' + pattern + (loose ? '(?=$|/)' : '/?$'), 'i'),\n };\n}\n\n/**\n * Test if a path matches a pattern\n */\nexport function matchPath(path: string, pattern: string | RegExp): boolean {\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n}\n","import type { ISessionProvider } from '@mastra/core/auth';\nimport type { IRBACProvider, EEUser } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { CompositeAuth } from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, MastraAuthConfig, MastraAuthRequest } from '@mastra/core/server';\n\nimport {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n MASTRA_USER_ROLES_KEY,\n MASTRA_AUTH_TOKEN_KEY,\n MASTRA_AUTH_MODE_KEY,\n} from '../constants';\nimport { HTTPException } from '../http-exception';\nimport { CustomRouteMatcher, getCustomRouteAuthConfigMatcher } from './custom-route-matcher';\nimport { defaultAuthConfig } from './defaults';\nimport { parse } from './path-pattern';\n\n// Re-export request-context key constants so custom middleware can read namespaced\n// auth state without importing internal paths.\nexport { MASTRA_USER_KEY, MASTRA_USER_PERMISSIONS_KEY, MASTRA_USER_ROLES_KEY } from '../constants';\n\ntype CustomRouteAuthDecision = 'protected' | 'public' | 'none';\n\n/**\n * Decide auth for a request from the custom route the custom-route app will dispatch\n * it to (see `CustomRouteMatcher`), not from whichever pattern happens to match.\n *\n * Fails closed:\n * - an exact `METHOD:path` (or `ALL:path`) entry that requires auth always wins, so a\n * path registered as protected is never served without auth;\n * - `path` may be a raw request path (Express, Koa, Fastify) or one Hono already\n * decoded, so it's resolved both ways and is only public if every reading lands on\n * a public route, and protected if any reading lands on a protected one;\n * - if the routes or the path can't be parsed, the request is treated as protected.\n */\nconst resolveCustomRouteAuth = (\n path: string,\n method: string,\n customRouteAuthConfig: Map<string, boolean>,\n): CustomRouteAuthDecision => {\n const upperMethod = method.toUpperCase();\n const methods = upperMethod === 'HEAD' ? ['HEAD', 'GET'] : [upperMethod];\n for (const m of methods) {\n if (customRouteAuthConfig.get(`${m}:${path}`) === true || customRouteAuthConfig.get(`ALL:${path}`) === true) {\n return 'protected';\n }\n }\n\n // Adapters pin the current request by appending `METHOD:path` to a copy of the map.\n // As the last entry it only decides when no earlier route matches, so resolve the\n // rest with a cached matcher and fall back to it, instead of building a new router\n // for every request path.\n const keys = [...customRouteAuthConfig.keys()];\n const lastKey = keys[keys.length - 1];\n const pinnedKey =\n lastKey !== undefined && methods.some(m => lastKey === `${m}:${path}` || lastKey === `ALL:${path}`)\n ? lastKey\n : undefined;\n\n let matcher: ReturnType<typeof getCustomRouteAuthConfigMatcher>;\n const candidates = new Set<string>([path]);\n try {\n matcher = getCustomRouteAuthConfigMatcher(pinnedKey ? keys.slice(0, -1) : keys);\n candidates.add(matcher.dispatchPathForRawPath(path));\n } catch {\n return 'protected';\n }\n\n let matchedPublic = false;\n let unmatched = false;\n for (const candidate of candidates) {\n let key: string | undefined;\n try {\n key = matcher.matchPath(candidate, upperMethod)?.entry.key;\n } catch {\n return 'protected';\n }\n if (key === undefined && pinnedKey && candidate === path) {\n key = pinnedKey;\n }\n if (key === undefined) {\n unmatched = true;\n continue;\n }\n if (customRouteAuthConfig.get(key) !== false) {\n return 'protected';\n }\n matchedPublic = true;\n }\n\n return matchedPublic && !unmatched ? 'public' : 'none';\n};\n\n/**\n * Check if a request will be handled by a registered custom route that requires\n * authentication. The route that decides is the one the custom-route app dispatches\n * to (first registered match), using Hono's own matching. Returns false when no\n * custom route handles the request.\n */\nexport const isProtectedCustomRoute = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'protected';\n};\n\nconst apiRouteMatchers = new WeakMap<\n readonly ApiRoute[],\n { signature: string; matcher: CustomRouteMatcher<ApiRoute> }\n>();\n\n/**\n * Find the custom API route Hono dispatches `path` to, with its decoded path params.\n * `path` is in the form Hono's `c.req.path` returns (no query string, decoded once).\n * Matching follows Hono: first registered match wins, case-sensitive, strict\n * trailing slash, and HEAD is served by GET routes.\n */\nexport const findMatchingCustomRoute = (\n path: string,\n method: string,\n apiRoutes?: ApiRoute[],\n): { route: ApiRoute; params: Record<string, string> } | undefined => {\n if (!apiRoutes || apiRoutes.length === 0) return undefined;\n\n const signature = JSON.stringify(apiRoutes.map(route => `${route.method}:${route.path}`));\n let cached = apiRouteMatchers.get(apiRoutes);\n if (!cached || cached.signature !== signature) {\n cached = { signature, matcher: new CustomRouteMatcher(apiRoutes) };\n apiRouteMatchers.set(apiRoutes, cached);\n }\n\n try {\n const match = cached.matcher.matchPath(path, method);\n return match ? { route: match.entry, params: match.params } : undefined;\n } catch {\n // Hono can't route these paths either, so no custom route handles the request.\n return undefined;\n }\n};\n\n/**\n * Check if request is from dev playground\n * @param getHeader - Function to get header value from request\n * @param customRouteAuthConfig - Map of custom route auth configurations\n */\nexport const isDevPlaygroundRequest = (\n path: string,\n method: string,\n getHeader: (name: string) => string | undefined,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return (\n process.env.MASTRA_DEV === 'true' &&\n // Allow if path doesn't match protected patterns AND is not a protected custom route\n ((!isAnyMatch(path, method, protectedAccess) && !isProtectedCustomRoute(path, method, customRouteAuthConfig)) ||\n // Or if has playground header\n getHeader('x-mastra-dev-playground') === 'true')\n );\n};\n\n/**\n * Check if a request will be handled by a custom route registered as public\n * (`requiresAuth: false`). Uses the same dispatch-order resolution as\n * `isProtectedCustomRoute`, and returns false (not public) when no custom route\n * handles the request or the answer is ambiguous.\n */\nexport const isCustomRoutePublic = (\n path: string,\n method: string,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n if (!customRouteAuthConfig || customRouteAuthConfig.size === 0) {\n return false;\n }\n return resolveCustomRouteAuth(path, method, customRouteAuthConfig) === 'public';\n};\n\n// NOTE: This uses isProtectedCustomRoute (default-allow for unknown paths) rather than\n// !isCustomRoutePublic (default-deny). This is intentional — all registered server and\n// custom routes are auth-checked via registerRoute/checkRouteAuth regardless of this\n// function. The '/api/*' protected pattern exists as a user-facing override mechanism.\n// The old default-deny logic incorrectly blocked non-API paths (e.g. '/', '/agents')\n// which prevented the studio login page from loading in production.\nexport const isProtectedPath = (\n path: string,\n method: string,\n authConfig: MastraAuthConfig,\n customRouteAuthConfig?: Map<string, boolean>,\n): boolean => {\n const protectedAccess = [...(defaultAuthConfig.protected || []), ...(authConfig.protected || [])];\n return isAnyMatch(path, method, protectedAccess) || isProtectedCustomRoute(path, method, customRouteAuthConfig);\n};\n\nexport const canAccessPublicly = (path: string, method: string, authConfig: MastraAuthConfig): boolean => {\n // Check if this path+method combination is publicly accessible\n const publicAccess = [...(defaultAuthConfig.public || []), ...(authConfig.public || [])];\n\n return isAnyMatch(path, method, publicAccess);\n};\n\nconst isAnyMatch = (\n path: string,\n method: string,\n patterns: MastraAuthConfig['protected'] | MastraAuthConfig['public'],\n): boolean => {\n if (!patterns) {\n return false;\n }\n\n for (const patternPathOrMethod of patterns) {\n if (patternPathOrMethod instanceof RegExp) {\n if (patternPathOrMethod.test(path)) {\n return true;\n }\n }\n\n if (typeof patternPathOrMethod === 'string' && pathMatchesPattern(path, patternPathOrMethod)) {\n return true;\n }\n\n if (Array.isArray(patternPathOrMethod) && patternPathOrMethod.length === 2) {\n const [pattern, methodOrMethods] = patternPathOrMethod;\n if (pathMatchesPattern(path, pattern) && matchesOrIncludes(methodOrMethods, method)) {\n return true;\n }\n }\n }\n\n return false;\n};\n\nexport const pathMatchesPattern = (path: string, pattern: string): boolean => {\n // Use regexparam for battle-tested path matching\n // Supports:\n // - Exact paths: '/api/users'\n // - Wildcards: '/api/agents/*' matches '/api/agents/123'\n // - Path parameters: '/users/:id' matches '/users/123'\n // - Optional parameters: '/users/:id?' matches '/users' and '/users/123'\n // - Mixed patterns: '/api/:version/users/:id/profile'\n const { pattern: regex } = parse(pattern);\n return regex.test(path);\n};\n\nexport const pathMatchesRule = (path: string, rulePath: string | RegExp | string[] | undefined): boolean => {\n if (!rulePath) return true; // No path specified means all paths\n\n if (typeof rulePath === 'string') {\n return pathMatchesPattern(path, rulePath);\n }\n\n if (rulePath instanceof RegExp) {\n return rulePath.test(path);\n }\n\n if (Array.isArray(rulePath)) {\n return rulePath.some(p => pathMatchesPattern(path, p));\n }\n\n return false;\n};\n\nexport const matchesOrIncludes = (values: string | string[], value: string): boolean => {\n if (typeof values === 'string') {\n return values === value;\n }\n\n if (Array.isArray(values)) {\n return values.includes(value);\n }\n\n return false;\n};\n\n// ── Core auth middleware ──\n// Framework-agnostic auth logic extracted from adapter middlewares.\n// Each adapter builds an AuthMiddlewareContext and delegates to coreAuthMiddleware.\n\nexport interface AuthMiddlewareContext {\n path: string;\n method: string;\n getHeader: (name: string) => string | undefined;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: { get: (key: string) => unknown; set: (key: string, value: unknown) => void };\n rawRequest: MastraAuthRequest;\n token: string | null;\n buildAuthorizeContext: () => unknown;\n /** When true, force authentication even if the path matches a public pattern. */\n requiresAuth?: boolean;\n}\n\nexport type AuthResult =\n | { action: 'next'; headers?: Record<string, string> }\n | { action: 'error'; status: number; body: Record<string, unknown>; headers?: Record<string, string> };\n\nconst pass: AuthResult = { action: 'next' };\n\n/**\n * Lets an app's `authorize(path, method, user, context)` read `context.get('requestContext')` and\n * `context.get('mastra')` on every adapter, as it can on Hono, so per-caller values (the Knowledge scope) bind\n * the same way everywhere. Hono and NestJS contexts already answer `get`; Express, Fastify and Koa pass a web\n * Request, Elysia its own context, and adapters with no builder pass nothing.\n */\nconst withAuthorizeVariables = (\n base: unknown,\n ctx: Pick<AuthMiddlewareContext, 'mastra' | 'requestContext' | 'customRouteAuthConfig' | 'rawRequest'>,\n): unknown => {\n const variables: Record<string, unknown> = {\n mastra: ctx.mastra,\n requestContext: ctx.requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n };\n const get = (key: string) => variables[key];\n if (base === null || base === undefined) {\n return { get, req: ctx.rawRequest };\n }\n if (typeof base === 'object' && typeof (base as { get?: unknown }).get !== 'function') {\n Object.defineProperty(base, 'get', { value: get, configurable: true });\n }\n return base;\n};\n\nconst adaptToMastraAuthRequest = (request: MastraAuthRequest): MastraAuthRequest => {\n if (!(request instanceof Request)) {\n return request;\n }\n\n return {\n raw: request,\n headers: request.headers,\n header: name => request.headers.get(name) ?? undefined,\n };\n};\n\nexport interface GetAuthenticatedUserOptions {\n mastra: Mastra;\n token: string;\n request: MastraAuthRequest;\n}\n\nexport const getAuthenticatedUser = async <TUser = unknown>({\n mastra,\n token,\n request,\n}: GetAuthenticatedUserOptions): Promise<TUser | null> => {\n const normalizedToken = token.replace(/^Bearer\\s+/i, '').trim();\n if (!normalizedToken) {\n return null;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig || typeof authConfig.authenticateToken !== 'function') {\n return null;\n }\n\n return (await authConfig.authenticateToken(normalizedToken, request)) as TUser | null;\n};\n\n/**\n * Check if an auth config object supports transparent session refresh.\n * Returns true if the auth provider implements the necessary ISessionProvider methods.\n */\nexport function supportsSessionRefresh(\n authConfig: MastraAuthConfig | IMastraAuthProvider,\n): authConfig is (MastraAuthConfig | IMastraAuthProvider) &\n Pick<ISessionProvider, 'refreshSession' | 'getSessionIdFromRequest' | 'getSessionHeaders'> {\n return (\n typeof (authConfig as any).getSessionIdFromRequest === 'function' &&\n typeof (authConfig as any).refreshSession === 'function' &&\n typeof (authConfig as any).getSessionHeaders === 'function'\n );\n}\n\n/**\n * Single auth middleware: authenticate → authorize.\n * Skip checks (dev playground, unprotected path, public path) are evaluated once.\n */\nexport const coreAuthMiddleware = async (ctx: AuthMiddlewareContext): Promise<AuthResult> => {\n const {\n path,\n method,\n getHeader,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n token,\n requiresAuth,\n } = ctx;\n\n // ── Skip checks (evaluated once) ──\n\n // Only bypass auth for dev playground when no real auth provider is configured.\n // When auth IS configured (has authenticateToken), we need the full auth flow\n // so user/roles/permissions are set in requestContext.\n const hasAuthProvider = typeof authConfig.authenticateToken === 'function';\n if (!hasAuthProvider && isDevPlaygroundRequest(path, method, getHeader, authConfig, customRouteAuthConfig)) {\n return pass;\n }\n\n if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {\n return pass;\n }\n\n // When a route explicitly requires auth (requiresAuth: true), skip the\n // public-path bypass so the user is still authenticated and permissions\n // are injected into the request context.\n if (\n !requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig))\n ) {\n return pass;\n }\n\n // ── Authentication ──\n\n let user: unknown;\n let refreshHeaders: Record<string, string> | undefined;\n const authRequest = adaptToMastraAuthRequest(rawRequest);\n\n type ConsumePendingResponseHeadersFn = (request: typeof authRequest) => Record<string, string> | undefined;\n const mergePendingProviderHeaders = (request: typeof authRequest = authRequest) => {\n const consume = (authConfig as { consumePendingResponseHeaders?: ConsumePendingResponseHeadersFn })\n .consumePendingResponseHeaders;\n if (typeof consume !== 'function') return;\n let pending: Record<string, string> | undefined;\n try {\n pending = consume.call(authConfig, request);\n } catch {\n // Forwarding a rotated cookie is best-effort; never fail auth over it.\n return;\n }\n if (!pending) return;\n refreshHeaders = { ...(refreshHeaders ?? {}), ...pending };\n };\n\n try {\n if (typeof authConfig.authenticateToken === 'function') {\n user = await authConfig.authenticateToken(token ?? '', authRequest);\n mergePendingProviderHeaders();\n } else {\n throw new Error('No token verification method configured');\n }\n\n // If authentication failed, attempt transparent session refresh before returning 401.\n // This handles expired access tokens without requiring client-side refresh logic.\n if (!user && supportsSessionRefresh(authConfig) && rawRequest instanceof Request) {\n let retryHttpError: HTTPException | undefined;\n try {\n const sessionId = authConfig.getSessionIdFromRequest(rawRequest);\n if (sessionId) {\n const newSession = await authConfig.refreshSession(sessionId);\n if (newSession) {\n // Refresh succeeded — build updated session headers and re-authenticate.\n // We create a synthetic request with the new session cookie so\n // authenticateToken (which reads cookies from the request) picks up\n // the refreshed session instead of the expired one.\n refreshHeaders = authConfig.getSessionHeaders(newSession);\n const refreshedCookie = Object.entries(refreshHeaders)\n .filter(([k]) => k.toLowerCase() === 'set-cookie')\n .map(([, v]) => v.split(';')[0]) // Extract name=value before attributes\n .join('; ');\n if (refreshedCookie) {\n const refreshedRequest = new Request(rawRequest.url, {\n method: rawRequest.method,\n headers: new Headers(rawRequest.headers),\n });\n refreshedRequest.headers.set('Cookie', refreshedCookie);\n // Pass the refreshed cookie value as the token so authenticateToken\n // picks up the new session instead of the stale original.\n // Auth providers typically read cookies from the request object, but\n // some may also inspect the token parameter directly.\n const cookieValue = refreshedCookie.includes('=')\n ? refreshedCookie.split('=').slice(1).join('=')\n : refreshedCookie;\n try {\n const retryAuthRequest = adaptToMastraAuthRequest(refreshedRequest);\n user = await authConfig.authenticateToken(cookieValue, retryAuthRequest);\n mergePendingProviderHeaders(retryAuthRequest);\n } catch (retryErr) {\n retryHttpError = retryErr instanceof HTTPException ? retryErr : undefined;\n throw retryErr;\n }\n }\n if (!user) {\n refreshHeaders = undefined;\n }\n }\n }\n } catch (refreshErr) {\n refreshHeaders = undefined;\n // An explicit HTTP error from the retried authenticateToken goes to the outer handler.\n if (retryHttpError === refreshErr) throw refreshErr;\n mastra.getLogger()?.debug('Session refresh failed, falling back to 401', {\n error: refreshErr instanceof Error ? { message: refreshErr.message } : refreshErr,\n });\n }\n }\n\n if (!user) {\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n requestContext.set(MASTRA_USER_KEY, user);\n // Backward-compat: also write the legacy `'user'` key so existing\n // middleware and integrations that read `requestContext.get('user')`\n // (including built-in FGA route enforcement, memory handlers, and the\n // documented public surface) keep working. New code should prefer\n // `MASTRA_USER_KEY` to avoid collisions with caller-supplied keys.\n requestContext.set('user', user);\n\n // Store the raw auth token so downstream code (e.g., editor MCP client\n // resolution) can forward it when connecting to auth-protected MCP servers.\n // The token may arrive via Authorization header, apiKey query param, or\n // cookie (SimpleAuth sets `mastra-token`). Check all sources so the\n // forwarded value is available regardless of how the user authenticated.\n let effectiveToken = token;\n if (!effectiveToken && rawRequest instanceof Request) {\n const cookieHeader = rawRequest.headers.get('cookie');\n if (cookieHeader) {\n const match = cookieHeader.match(/mastra-token=([^;]+)/);\n if (match?.[1]) effectiveToken = match[1];\n }\n }\n if (effectiveToken) {\n requestContext.set(MASTRA_AUTH_TOKEN_KEY, effectiveToken);\n }\n\n if (typeof authConfig.mapUserToResourceId === 'function') {\n try {\n const resourceId = authConfig.mapUserToResourceId(user);\n // CompositeAuth validates the authenticating provider's mapper. It can\n // return undefined when that provider never configured a mapper.\n if (resourceId !== undefined || !(authConfig instanceof CompositeAuth)) {\n if (typeof resourceId !== 'string' || !resourceId.trim()) {\n throw new Error('mapUserToResourceId must return a non-empty string for the authenticated user');\n }\n requestContext.set(MASTRA_RESOURCE_ID_KEY, resourceId);\n }\n } catch (mapError) {\n mastra.getLogger()?.error('mapUserToResourceId failed', {\n error: mapError instanceof Error ? { message: mapError.message, stack: mapError.stack } : mapError,\n });\n return {\n action: 'error',\n status: 500,\n body: { error: 'Failed to map authenticated user to a resource ID' },\n headers: refreshHeaders,\n };\n }\n }\n\n try {\n // Determine which RBAC provider to use based on auth mode\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);\n const serverConfig = mastra.getServer();\n const studioConfig = mastra.getStudio?.();\n // Use studio RBAC if this is a studio request, otherwise use server RBAC\n const rbacProvider = (authMode === 'studio' ? (studioConfig?.rbac ?? serverConfig?.rbac) : serverConfig?.rbac) as\n | IRBACProvider<EEUser>\n | undefined;\n\n if (rbacProvider) {\n if (!user || typeof user !== 'object' || !('id' in user)) {\n mastra.getLogger()?.warn('RBAC: authenticated user missing required \"id\" field, skipping permission loading');\n } else {\n const permissions = await rbacProvider.getPermissions(user as EEUser);\n requestContext.set(MASTRA_USER_PERMISSIONS_KEY, permissions);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userPermissions', permissions);\n\n const roles = await rbacProvider.getRoles(user as EEUser);\n requestContext.set(MASTRA_USER_ROLES_KEY, roles);\n // Backward-compat alias for callers reading the legacy key.\n requestContext.set('userRoles', roles);\n }\n }\n } catch (rbacError) {\n mastra.getLogger()?.error('RBAC: failed to load user permissions/roles', {\n error: rbacError instanceof Error ? { message: rbacError.message, stack: rbacError.stack } : rbacError,\n });\n }\n } catch (err) {\n mastra.getLogger()?.error('Authentication error', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n // Explicit HTTP errors from auth callbacks keep their status/message; anything else is redacted.\n // The HTTPException message is sent to the client, so callers must keep it safe (no internal details).\n if (err instanceof HTTPException && err.status >= 400 && err.status <= 599) {\n return { action: 'error', status: err.status, body: { error: err.message }, headers: refreshHeaders };\n }\n return { action: 'error', status: 401, body: { error: 'Invalid or expired token' }, headers: refreshHeaders };\n }\n\n // ── Authorization ──\n\n const authorizationError = await authorizeAuthenticatedUser({\n path,\n method,\n user,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest,\n buildAuthorizeContext: ctx.buildAuthorizeContext,\n });\n if (authorizationError) {\n return { action: 'error', ...authorizationError, headers: refreshHeaders };\n }\n\n return refreshHeaders ? { action: 'next', headers: refreshHeaders } : pass;\n};\n\nexport interface AuthorizeAuthenticatedUserContext {\n path: string;\n method: string;\n user: unknown;\n mastra: Mastra;\n authConfig: MastraAuthConfig;\n customRouteAuthConfig?: Map<string, boolean>;\n requestContext: AuthMiddlewareContext['requestContext'];\n rawRequest: MastraAuthRequest;\n buildAuthorizeContext: () => unknown;\n}\n\n/**\n * The authorization step of server auth for an already authenticated user:\n * `authorizeUser`, `authorize(path, method, user)`, `rules`, or the RBAC default rules.\n * Returns null when the user may access `method path`.\n */\nexport const authorizeAuthenticatedUser = async (\n ctx: AuthorizeAuthenticatedUserContext,\n): Promise<{ status: number; body: Record<string, unknown> } | null> => {\n const { path, method, user, mastra, authConfig, requestContext, rawRequest } = ctx;\n const denied = { status: 403, body: { error: 'Access denied' } };\n\n if ('authorizeUser' in authConfig && typeof authConfig.authorizeUser === 'function') {\n try {\n const isAuthorized = await authConfig.authorizeUser(user, adaptToMastraAuthRequest(rawRequest));\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorizeUser', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('authorize' in authConfig && typeof authConfig.authorize === 'function') {\n try {\n const authorizeCtx = withAuthorizeVariables(ctx.buildAuthorizeContext(), {\n mastra,\n requestContext,\n customRouteAuthConfig: ctx.customRouteAuthConfig,\n rawRequest,\n });\n const isAuthorized = await authConfig.authorize(path, method, user, authorizeCtx as any);\n return isAuthorized ? null : denied;\n } catch (err) {\n mastra.getLogger()?.error('Authorization error in authorize', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n path,\n method,\n });\n return { status: 500, body: { error: 'Authorization error' } };\n }\n }\n\n if ('rules' in authConfig && authConfig.rules && authConfig.rules.length > 0) {\n return (await checkRules(authConfig.rules, path, method, user)) ? null : denied;\n }\n\n // No explicit authorization configured (authorizeUser, authorize, or rules)\n // Check if RBAC is configured - if not, allow authenticated users through\n // (auth-only mode = authenticated users get full access)\n const rbacProvider =\n requestContext.get(MASTRA_AUTH_MODE_KEY) === 'studio'\n ? (mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac)\n : mastra.getServer()?.rbac;\n if (rbacProvider) {\n if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {\n return (await checkRules(defaultAuthConfig.rules, path, method, user)) ? null : denied;\n }\n return denied;\n }\n\n return null;\n};\n\n// Check authorization rules\nexport const checkRules = async (\n rules: MastraAuthConfig['rules'],\n path: string,\n method: string,\n user: unknown,\n): Promise<boolean> => {\n // Go through rules in order (first match wins)\n for (const i in rules || []) {\n const rule = rules?.[i]!;\n // Check if rule applies to this path\n if (!pathMatchesRule(path, rule.path)) {\n continue;\n }\n\n // Check if rule applies to this method\n if (rule.methods && !matchesOrIncludes(rule.methods, method)) {\n continue;\n }\n\n // Rule matches, so it decides. A failed condition denies instead of\n // falling through to a broader rule further down the list.\n const condition = rule.condition;\n if (typeof condition === 'function') {\n return await Promise.resolve()\n .then(() => condition(user))\n .then(result => !!result)\n .catch(() => false);\n }\n return !!rule.allow;\n }\n\n // No matching rules, deny by default\n return false;\n};\n"],"mappings":";;;;;;AAsBA,MAAM,uBAA+B,KAAA;AACrC,MAAM,eAAe,IAAI,QAAQ,mBAAmB;;;;;;;;AASpD,IAAa,qBAAb,MAAmE;CACjE,OAAgB,IAAIA,KAAAA,KAAK;CACzB,kCAA2B,IAAI,IAAqB;CACpD;CAEA,YAAY,SAAuB;EACjC,KAAK,WAAW;EAEhB,KAAK,KAAK,IAAI,KAAK,cAAuB;EAC1C,QAAQ,SAAS,OAAO,UAAU;GAChC,MAAM,e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CAAC,kBAAkB,KAAK,SAAS,MAAM,GACzD;EAKF,MAAM,YAAY,KAAK;EACvB,IAAI,OAAO,cAAc,YACvB,OAAO,MAAM,QAAQ,QAAQ,CAAC,CAC3B,WAAW,UAAU,IAAI,CAAC,CAAC,CAC3B,MAAK,WAAU,CAAC,CAAC,MAAM,CAAC,CACxB,YAAY,KAAK;EAEtB,OAAO,CAAC,CAAC,KAAK;CAChB;CAGA,OAAO;AACT"}
@@ -562,12 +562,11 @@ const checkRules = async (rules, path, method, user) => {
562
562
  if (!pathMatchesRule(path, rule.path)) continue;
563
563
  if (rule.methods && !matchesOrIncludes(rule.methods, method)) continue;
564
564
  const condition = rule.condition;
565
- if (typeof condition === "function") {
566
- if (await Promise.resolve().then(() => condition(user)).catch(() => false)) return true;
567
- } else if (rule.allow) return true;
565
+ if (typeof condition === "function") return await Promise.resolve().then(() => condition(user)).then((result) => !!result).catch(() => false);
566
+ return !!rule.allow;
568
567
  }
569
568
  return false;
570
569
  };
571
570
  export { findMatchingCustomRoute as a, isDevPlaygroundRequest as c, matchesOrIncludes as d, pathMatchesPattern as f, CustomRouteMatcher as g, defaultAuthConfig as h, coreAuthMiddleware as i, isProtectedCustomRoute as l, supportsSessionRefresh as m, canAccessPublicly as n, getAuthenticatedUser as o, pathMatchesRule as p, checkRules as r, isCustomRoutePublic as s, authorizeAuthenticatedUser as t, isProtectedPath as u };
572
571
 
573
- //# sourceMappingURL=helpers-C3dENOkQ.js.map
572
+ //# sourceMappingURL=helpers-C9QZKOhz.js.map