@scalar/api-client 3.13.7 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (385) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +2 -1
  3. package/dist/assets/computer.ascii.virtual.js.map +1 -1
  4. package/dist/components/HelpfulLink.vue.script.js +1 -1
  5. package/dist/components/HelpfulLink.vue.script.js.map +1 -1
  6. package/dist/components/HttpMethod/HttpMethod.vue.js +1 -1
  7. package/dist/components/HttpMethod/HttpMethod.vue.script.js +1 -1
  8. package/dist/components/HttpMethod/HttpMethod.vue.script.js.map +1 -1
  9. package/dist/components/ScalarAsciiArt/ScalarAsciiArt.vue.js +1 -1
  10. package/dist/components/ScalarAsciiArt/ScalarAsciiArt.vue.script.js +1 -1
  11. package/dist/components/ScalarAsciiArt/ScalarAsciiArt.vue.script.js.map +1 -1
  12. package/dist/components/SectionFilter.vue.d.ts +1 -1
  13. package/dist/components/SectionFilter.vue.d.ts.map +1 -1
  14. package/dist/components/SectionFilter.vue.js +1 -1
  15. package/dist/components/SectionFilter.vue.script.js +2 -2
  16. package/dist/components/SectionFilter.vue.script.js.map +1 -1
  17. package/dist/components/SectionFilterButton.vue.script.js +1 -1
  18. package/dist/components/SectionFilterButton.vue.script.js.map +1 -1
  19. package/dist/components/Server/ServerVariablesForm.vue.d.ts.map +1 -1
  20. package/dist/components/Server/ServerVariablesForm.vue.script.js +1 -1
  21. package/dist/components/Server/ServerVariablesForm.vue.script.js.map +1 -1
  22. package/dist/components/Server/ServerVariablesSelect.vue.script.js +1 -1
  23. package/dist/components/Server/ServerVariablesSelect.vue.script.js.map +1 -1
  24. package/dist/components/Server/ServerVariablesTextbox.vue.script.js +1 -1
  25. package/dist/components/Server/ServerVariablesTextbox.vue.script.js.map +1 -1
  26. package/dist/components/Sidebar/Actions/DeleteSidebarListElement.vue.d.ts.map +1 -1
  27. package/dist/components/Sidebar/Actions/DeleteSidebarListElement.vue.script.js +1 -1
  28. package/dist/components/Sidebar/Actions/DeleteSidebarListElement.vue.script.js.map +1 -1
  29. package/dist/components/Sidebar/Actions/SidebarListElementForm.vue.d.ts.map +1 -1
  30. package/dist/components/Sidebar/Actions/SidebarListElementForm.vue.script.js +1 -1
  31. package/dist/components/Sidebar/Actions/SidebarListElementForm.vue.script.js.map +1 -1
  32. package/dist/components/ViewLayout/ViewLayout.vue.script.js +1 -1
  33. package/dist/components/ViewLayout/ViewLayout.vue.script.js.map +1 -1
  34. package/dist/components/ViewLayout/ViewLayoutContent.vue.js +1 -1
  35. package/dist/components/ViewLayout/ViewLayoutContent.vue.js.map +1 -1
  36. package/dist/components/ViewLayout/ViewLayoutSection.vue.script.js +1 -1
  37. package/dist/components/ViewLayout/ViewLayoutSection.vue.script.js.map +1 -1
  38. package/dist/hooks/use-file-dialog.js +2 -1
  39. package/dist/hooks/use-file-dialog.js.map +1 -1
  40. package/dist/plugins/posthog/index.js.map +1 -1
  41. package/dist/plugins/posthog/sanitize-event-payload.js +1 -1
  42. package/dist/plugins/posthog/sanitize-event-payload.js.map +1 -1
  43. package/dist/style.css +420 -382
  44. package/dist/v2/blocks/operation-block/OperationBlock.vue.d.ts.map +1 -1
  45. package/dist/v2/blocks/operation-block/OperationBlock.vue.js.map +1 -1
  46. package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js +4 -2
  47. package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js.map +1 -1
  48. package/dist/v2/blocks/operation-block/components/Header.vue.d.ts.map +1 -1
  49. package/dist/v2/blocks/operation-block/components/Header.vue.js +1 -1
  50. package/dist/v2/blocks/operation-block/components/Header.vue.script.js +1 -1
  51. package/dist/v2/blocks/operation-block/components/Header.vue.script.js.map +1 -1
  52. package/dist/v2/blocks/operation-block/components/OpenApiClientButton.vue.js +1 -1
  53. package/dist/v2/blocks/operation-block/components/OpenApiClientButton.vue.script.js +1 -1
  54. package/dist/v2/blocks/operation-block/components/OpenApiClientButton.vue.script.js.map +1 -1
  55. package/dist/v2/blocks/operation-block/helpers/decode-buffer.js.map +1 -1
  56. package/dist/v2/blocks/operation-block/helpers/get-cookie-header-keys.js.map +1 -1
  57. package/dist/v2/blocks/operation-block/helpers/har-to-fetch-request.js.map +1 -1
  58. package/dist/v2/blocks/operation-block/helpers/har-to-fetch-response.js.map +1 -1
  59. package/dist/v2/blocks/operation-block/helpers/persist-response-cookies.js.map +1 -1
  60. package/dist/v2/blocks/operation-block/helpers/response-cache.js.map +1 -1
  61. package/dist/v2/blocks/operation-block/helpers/send-request.js.map +1 -1
  62. package/dist/v2/blocks/operation-block/helpers/validate-path-parameters.js.map +1 -1
  63. package/dist/v2/blocks/request-block/RequestBlock.vue.d.ts.map +1 -1
  64. package/dist/v2/blocks/request-block/RequestBlock.vue.js +1 -1
  65. package/dist/v2/blocks/request-block/RequestBlock.vue.js.map +1 -1
  66. package/dist/v2/blocks/request-block/RequestBlock.vue.script.js +58 -29
  67. package/dist/v2/blocks/request-block/RequestBlock.vue.script.js.map +1 -1
  68. package/dist/v2/blocks/request-block/components/RequestBody.vue.d.ts +6 -6
  69. package/dist/v2/blocks/request-block/components/RequestBody.vue.d.ts.map +1 -1
  70. package/dist/v2/blocks/request-block/components/RequestBody.vue.js +1 -1
  71. package/dist/v2/blocks/request-block/components/RequestBody.vue.js.map +1 -1
  72. package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js +73 -12
  73. package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js.map +1 -1
  74. package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.d.ts.map +1 -1
  75. package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.script.js +1 -1
  76. package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.script.js.map +1 -1
  77. package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.d.ts +19 -0
  78. package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.d.ts.map +1 -0
  79. package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.js +7 -0
  80. package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.js.map +1 -0
  81. package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.script.js +81 -0
  82. package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.script.js.map +1 -0
  83. package/dist/v2/blocks/request-block/components/RequestBodyViewToggle.vue.d.ts +13 -0
  84. package/dist/v2/blocks/request-block/components/RequestBodyViewToggle.vue.d.ts.map +1 -0
  85. package/dist/v2/blocks/request-block/components/RequestBodyViewToggle.vue.js +7 -0
  86. package/dist/v2/blocks/request-block/components/RequestBodyViewToggle.vue.js.map +1 -0
  87. package/dist/v2/blocks/request-block/components/RequestBodyViewToggle.vue.script.js +34 -0
  88. package/dist/v2/blocks/request-block/components/RequestBodyViewToggle.vue.script.js.map +1 -0
  89. package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.d.ts.map +1 -1
  90. package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js +1 -1
  91. package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js.map +1 -1
  92. package/dist/v2/blocks/request-block/components/RequestParams.vue.d.ts +2 -0
  93. package/dist/v2/blocks/request-block/components/RequestParams.vue.d.ts.map +1 -1
  94. package/dist/v2/blocks/request-block/components/RequestParams.vue.js.map +1 -1
  95. package/dist/v2/blocks/request-block/components/RequestParams.vue.script.js +5 -3
  96. package/dist/v2/blocks/request-block/components/RequestParams.vue.script.js.map +1 -1
  97. package/dist/v2/blocks/request-block/components/RequestTable.vue.d.ts +2 -0
  98. package/dist/v2/blocks/request-block/components/RequestTable.vue.d.ts.map +1 -1
  99. package/dist/v2/blocks/request-block/components/RequestTable.vue.js +1 -1
  100. package/dist/v2/blocks/request-block/components/RequestTable.vue.js.map +1 -1
  101. package/dist/v2/blocks/request-block/components/RequestTable.vue.script.js +6 -3
  102. package/dist/v2/blocks/request-block/components/RequestTable.vue.script.js.map +1 -1
  103. package/dist/v2/blocks/request-block/components/RequestTableRow.vue.d.ts +8 -0
  104. package/dist/v2/blocks/request-block/components/RequestTableRow.vue.d.ts.map +1 -1
  105. package/dist/v2/blocks/request-block/components/RequestTableRow.vue.js.map +1 -1
  106. package/dist/v2/blocks/request-block/components/RequestTableRow.vue.script.js +37 -18
  107. package/dist/v2/blocks/request-block/components/RequestTableRow.vue.script.js.map +1 -1
  108. package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.script.js +1 -1
  109. package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.script.js.map +1 -1
  110. package/dist/v2/blocks/request-block/helpers/create-parameter-handlers.js.map +1 -1
  111. package/dist/v2/blocks/request-block/helpers/create-parameter-rows.js +1 -1
  112. package/dist/v2/blocks/request-block/helpers/create-parameter-rows.js.map +1 -1
  113. package/dist/v2/blocks/request-block/helpers/files.js.map +1 -1
  114. package/dist/v2/blocks/request-block/helpers/fold-structured-body-rows.d.ts +17 -0
  115. package/dist/v2/blocks/request-block/helpers/fold-structured-body-rows.d.ts.map +1 -0
  116. package/dist/v2/blocks/request-block/helpers/fold-structured-body-rows.js +33 -0
  117. package/dist/v2/blocks/request-block/helpers/fold-structured-body-rows.js.map +1 -0
  118. package/dist/v2/blocks/request-block/helpers/get-form-body-rows.d.ts +28 -0
  119. package/dist/v2/blocks/request-block/helpers/get-form-body-rows.d.ts.map +1 -1
  120. package/dist/v2/blocks/request-block/helpers/get-form-body-rows.js +12 -7
  121. package/dist/v2/blocks/request-block/helpers/get-form-body-rows.js.map +1 -1
  122. package/dist/v2/blocks/request-block/helpers/get-parameter-content.js.map +1 -1
  123. package/dist/v2/blocks/request-block/helpers/get-parameter-schema.js.map +1 -1
  124. package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.d.ts +13 -0
  125. package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.d.ts.map +1 -0
  126. package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.js +39 -0
  127. package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.js.map +1 -0
  128. package/dist/v2/blocks/request-block/helpers/group-by.js.map +1 -1
  129. package/dist/v2/blocks/request-block/helpers/group-global-cookies.d.ts +54 -0
  130. package/dist/v2/blocks/request-block/helpers/group-global-cookies.d.ts.map +1 -0
  131. package/dist/v2/blocks/request-block/helpers/group-global-cookies.js +56 -0
  132. package/dist/v2/blocks/request-block/helpers/group-global-cookies.js.map +1 -0
  133. package/dist/v2/blocks/request-block/helpers/structured-body-codec.d.ts +15 -0
  134. package/dist/v2/blocks/request-block/helpers/structured-body-codec.d.ts.map +1 -0
  135. package/dist/v2/blocks/request-block/helpers/structured-body-codec.js +33 -0
  136. package/dist/v2/blocks/request-block/helpers/structured-body-codec.js.map +1 -0
  137. package/dist/v2/blocks/request-block/helpers/validate-parameter.js.map +1 -1
  138. package/dist/v2/blocks/response-block/ResponseBlock.vue.d.ts.map +1 -1
  139. package/dist/v2/blocks/response-block/ResponseBlock.vue.js +1 -1
  140. package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js +1 -1
  141. package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js.map +1 -1
  142. package/dist/v2/blocks/response-block/components/Headers.vue.script.js +1 -1
  143. package/dist/v2/blocks/response-block/components/Headers.vue.script.js.map +1 -1
  144. package/dist/v2/blocks/response-block/components/ResponseBody.vue.js +1 -1
  145. package/dist/v2/blocks/response-block/components/ResponseBody.vue.script.js +1 -1
  146. package/dist/v2/blocks/response-block/components/ResponseBody.vue.script.js.map +1 -1
  147. package/dist/v2/blocks/response-block/components/ResponseBodyDownload.vue.script.js +1 -1
  148. package/dist/v2/blocks/response-block/components/ResponseBodyDownload.vue.script.js.map +1 -1
  149. package/dist/v2/blocks/response-block/components/ResponseBodyInfo.vue.js +1 -1
  150. package/dist/v2/blocks/response-block/components/ResponseBodyInfo.vue.js.map +1 -1
  151. package/dist/v2/blocks/response-block/components/ResponseBodyPreview.vue.js +1 -1
  152. package/dist/v2/blocks/response-block/components/ResponseBodyPreview.vue.script.js +1 -1
  153. package/dist/v2/blocks/response-block/components/ResponseBodyPreview.vue.script.js.map +1 -1
  154. package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.js +1 -1
  155. package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js +1 -1
  156. package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js.map +1 -1
  157. package/dist/v2/blocks/response-block/components/ResponseBodyStreaming.vue.d.ts.map +1 -1
  158. package/dist/v2/blocks/response-block/components/ResponseBodyStreaming.vue.script.js +1 -1
  159. package/dist/v2/blocks/response-block/components/ResponseBodyStreaming.vue.script.js.map +1 -1
  160. package/dist/v2/blocks/response-block/components/ResponseBodyToggle.vue.script.js +1 -1
  161. package/dist/v2/blocks/response-block/components/ResponseBodyToggle.vue.script.js.map +1 -1
  162. package/dist/v2/blocks/response-block/components/ResponseBodyVirtual.vue.script.js +1 -1
  163. package/dist/v2/blocks/response-block/components/ResponseBodyVirtual.vue.script.js.map +1 -1
  164. package/dist/v2/blocks/response-block/components/ResponseCookies.vue.script.js +1 -1
  165. package/dist/v2/blocks/response-block/components/ResponseCookies.vue.script.js.map +1 -1
  166. package/dist/v2/blocks/response-block/components/ResponseEmpty.vue.js +1 -1
  167. package/dist/v2/blocks/response-block/components/ResponseEmpty.vue.script.js +1 -1
  168. package/dist/v2/blocks/response-block/components/ResponseEmpty.vue.script.js.map +1 -1
  169. package/dist/v2/blocks/response-block/components/ResponseLoadingOverlay.vue.d.ts.map +1 -1
  170. package/dist/v2/blocks/response-block/components/ResponseLoadingOverlay.vue.js +1 -1
  171. package/dist/v2/blocks/response-block/components/ResponseLoadingOverlay.vue.script.js +1 -1
  172. package/dist/v2/blocks/response-block/components/ResponseLoadingOverlay.vue.script.js.map +1 -1
  173. package/dist/v2/blocks/response-block/components/ResponseMetaInformation.vue.script.js +1 -1
  174. package/dist/v2/blocks/response-block/components/ResponseMetaInformation.vue.script.js.map +1 -1
  175. package/dist/v2/blocks/response-block/helpers/extract-filename.js.map +1 -1
  176. package/dist/v2/blocks/response-block/helpers/get-content-length.js.map +1 -1
  177. package/dist/v2/blocks/response-block/helpers/media-types.js.map +1 -1
  178. package/dist/v2/blocks/response-block/helpers/parse-set-cookie.js.map +1 -1
  179. package/dist/v2/blocks/response-block/helpers/prettify-jsonc-string.js.map +1 -1
  180. package/dist/v2/blocks/response-block/helpers/process-response-body.js.map +1 -1
  181. package/dist/v2/blocks/response-block/helpers/resolve-response-body-handler.js.map +1 -1
  182. package/dist/v2/blocks/response-block/helpers/resolve-response-content-type.js +7 -1
  183. package/dist/v2/blocks/response-block/helpers/resolve-response-content-type.js.map +1 -1
  184. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.d.ts.map +1 -1
  185. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.js +1 -1
  186. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.script.js +1 -1
  187. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.script.js.map +1 -1
  188. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBarHistory.vue.d.ts.map +1 -1
  189. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBarHistory.vue.js +1 -1
  190. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBarHistory.vue.script.js +1 -1
  191. package/dist/v2/blocks/scalar-address-bar-block/components/AddressBarHistory.vue.script.js.map +1 -1
  192. package/dist/v2/blocks/scalar-address-bar-block/components/EnvironmentSelector.vue.d.ts.map +1 -1
  193. package/dist/v2/blocks/scalar-address-bar-block/components/EnvironmentSelector.vue.script.js +1 -1
  194. package/dist/v2/blocks/scalar-address-bar-block/components/EnvironmentSelector.vue.script.js.map +1 -1
  195. package/dist/v2/blocks/scalar-address-bar-block/components/httpStatusCodeColors.js +3 -1
  196. package/dist/v2/blocks/scalar-address-bar-block/components/httpStatusCodeColors.js.map +1 -1
  197. package/dist/v2/blocks/scalar-address-bar-block/helpers/is-placeholder-path.js.map +1 -1
  198. package/dist/v2/blocks/scalar-address-bar-block/helpers/refocus-blur-target.js.map +1 -1
  199. package/dist/v2/blocks/scalar-address-bar-block/hooks/use-loading-animation.js.map +1 -1
  200. package/dist/v2/blocks/scalar-address-bar-block/hooks/use-path-masking.js.map +1 -1
  201. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.d.ts.map +1 -1
  202. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js +1 -1
  203. package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js.map +1 -1
  204. package/dist/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue.d.ts.map +1 -1
  205. package/dist/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue.script.js +1 -1
  206. package/dist/v2/blocks/scalar-auth-selector-block/components/DeleteRequestAuthModal.vue.script.js.map +1 -1
  207. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.d.ts +18 -2
  208. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.d.ts.map +1 -1
  209. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.js.map +1 -1
  210. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js +19 -14
  211. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js.map +1 -1
  212. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesAddModal.vue.d.ts.map +1 -1
  213. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesAddModal.vue.script.js +1 -1
  214. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesAddModal.vue.script.js.map +1 -1
  215. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.d.ts +6 -2
  216. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.d.ts.map +1 -1
  217. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.js.map +1 -1
  218. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.script.js +17 -9
  219. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.script.js.map +1 -1
  220. package/dist/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue.d.ts.map +1 -1
  221. package/dist/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue.script.js +1 -1
  222. package/dist/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue.script.js.map +1 -1
  223. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue.d.ts.map +1 -1
  224. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue.script.js +1 -1
  225. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue.script.js.map +1 -1
  226. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue.d.ts.map +1 -1
  227. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue.script.js +3 -3
  228. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTableInput.vue.script.js.map +1 -1
  229. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.d.ts +7 -3
  230. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.d.ts.map +1 -1
  231. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.js.map +1 -1
  232. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js +339 -26
  233. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js.map +1 -1
  234. package/dist/v2/blocks/scalar-auth-selector-block/helpers/auth-options.js.map +1 -1
  235. package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.js +5 -0
  236. package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.js.map +1 -1
  237. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth-callback.js +1 -1
  238. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth-callback.js.map +1 -1
  239. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.d.ts.map +1 -1
  240. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js +9 -13
  241. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js.map +1 -1
  242. package/dist/v2/blocks/scalar-auth-selector-block/helpers/openid-discovery-to-flows.js.map +1 -1
  243. package/dist/v2/blocks/scalar-auth-selector-block/helpers/resolve-default-oauth2-redirect-url.js.map +1 -1
  244. package/dist/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.d.ts +42 -0
  245. package/dist/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.d.ts.map +1 -0
  246. package/dist/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.js +60 -0
  247. package/dist/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.js.map +1 -0
  248. package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.d.ts +17 -1
  249. package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.d.ts.map +1 -1
  250. package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.js +33 -1
  251. package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.js.map +1 -1
  252. package/dist/v2/components/code-input/CodeInput.vue.d.ts.map +1 -1
  253. package/dist/v2/components/code-input/CodeInput.vue.js +1 -1
  254. package/dist/v2/components/code-input/CodeInput.vue.script.js +6 -1
  255. package/dist/v2/components/code-input/CodeInput.vue.script.js.map +1 -1
  256. package/dist/v2/components/code-input/CodeInputLite.vue.d.ts.map +1 -1
  257. package/dist/v2/components/code-input/CodeInputLite.vue.js +1 -1
  258. package/dist/v2/components/code-input/CodeInputLite.vue.script.js +5 -1
  259. package/dist/v2/components/code-input/CodeInputLite.vue.script.js.map +1 -1
  260. package/dist/v2/components/code-input/PillTooltipHost.vue.script.js +1 -1
  261. package/dist/v2/components/code-input/PillTooltipHost.vue.script.js.map +1 -1
  262. package/dist/v2/components/code-input/code-variable-widget.js +1 -0
  263. package/dist/v2/components/code-input/code-variable-widget.js.map +1 -1
  264. package/dist/v2/components/code-input/helpers/build-pill-context.js.map +1 -1
  265. package/dist/v2/components/code-input/helpers/lookup-variable-value.js.map +1 -1
  266. package/dist/v2/components/code-input/helpers/pill-signature.js.map +1 -1
  267. package/dist/v2/components/code-input/helpers/serialize-value.js.map +1 -1
  268. package/dist/v2/components/context-menu/ContextMenu.vue.script.js +1 -1
  269. package/dist/v2/components/context-menu/ContextMenu.vue.script.js.map +1 -1
  270. package/dist/v2/components/data-table/DataTable.vue.script.js +1 -1
  271. package/dist/v2/components/data-table/DataTable.vue.script.js.map +1 -1
  272. package/dist/v2/components/data-table/DataTableCell.vue.script.js +1 -1
  273. package/dist/v2/components/data-table/DataTableCell.vue.script.js.map +1 -1
  274. package/dist/v2/components/data-table/DataTableCheckbox.vue.d.ts +2 -0
  275. package/dist/v2/components/data-table/DataTableCheckbox.vue.d.ts.map +1 -1
  276. package/dist/v2/components/data-table/DataTableCheckbox.vue.js.map +1 -1
  277. package/dist/v2/components/data-table/DataTableCheckbox.vue.script.js +9 -3
  278. package/dist/v2/components/data-table/DataTableCheckbox.vue.script.js.map +1 -1
  279. package/dist/v2/components/data-table/DataTableHeader.vue.script.js +1 -1
  280. package/dist/v2/components/data-table/DataTableHeader.vue.script.js.map +1 -1
  281. package/dist/v2/components/data-table/DataTableInput.vue.d.ts.map +1 -1
  282. package/dist/v2/components/data-table/DataTableInput.vue.js +1 -1
  283. package/dist/v2/components/data-table/DataTableInput.vue.script.js +1 -1
  284. package/dist/v2/components/data-table/DataTableInput.vue.script.js.map +1 -1
  285. package/dist/v2/components/data-table/DataTableInputSelect.vue.d.ts.map +1 -1
  286. package/dist/v2/components/data-table/DataTableInputSelect.vue.script.js +3 -2
  287. package/dist/v2/components/data-table/DataTableInputSelect.vue.script.js.map +1 -1
  288. package/dist/v2/components/data-table/DataTableRow.vue.js +1 -1
  289. package/dist/v2/components/data-table/DataTableRow.vue.js.map +1 -1
  290. package/dist/v2/components/data-table/DataTableText.vue.script.js +1 -1
  291. package/dist/v2/components/data-table/DataTableText.vue.script.js.map +1 -1
  292. package/dist/v2/components/forms/ConfirmationForm.vue.d.ts.map +1 -1
  293. package/dist/v2/components/forms/ConfirmationForm.vue.script.js +1 -1
  294. package/dist/v2/components/forms/ConfirmationForm.vue.script.js.map +1 -1
  295. package/dist/v2/components/layout/CollapsibleSection.vue.d.ts.map +1 -1
  296. package/dist/v2/components/layout/CollapsibleSection.vue.script.js +1 -1
  297. package/dist/v2/components/layout/CollapsibleSection.vue.script.js.map +1 -1
  298. package/dist/v2/components/layout/ValueEmitter.vue.d.ts +1 -1
  299. package/dist/v2/components/layout/ValueEmitter.vue.d.ts.map +1 -1
  300. package/dist/v2/components/layout/ValueEmitter.vue.script.js +1 -1
  301. package/dist/v2/components/layout/ValueEmitter.vue.script.js.map +1 -1
  302. package/dist/v2/components/modals/DeleteModal.vue.d.ts.map +1 -1
  303. package/dist/v2/components/modals/DeleteModal.vue.script.js +1 -1
  304. package/dist/v2/components/modals/DeleteModal.vue.script.js.map +1 -1
  305. package/dist/v2/components/modals/ModalClientContainer.vue.js +1 -1
  306. package/dist/v2/components/modals/ModalClientContainer.vue.script.js +1 -1
  307. package/dist/v2/components/modals/ModalClientContainer.vue.script.js.map +1 -1
  308. package/dist/v2/components/resize/Resize.vue.js +1 -1
  309. package/dist/v2/components/resize/Resize.vue.script.js +1 -1
  310. package/dist/v2/components/resize/Resize.vue.script.js.map +1 -1
  311. package/dist/v2/components/resize/use-split-resize.js +4 -2
  312. package/dist/v2/components/resize/use-split-resize.js.map +1 -1
  313. package/dist/v2/components/server/ServerDropdown.vue.d.ts.map +1 -1
  314. package/dist/v2/components/server/ServerDropdown.vue.script.js +1 -1
  315. package/dist/v2/components/server/ServerDropdown.vue.script.js.map +1 -1
  316. package/dist/v2/components/server/ServerDropdownItem.vue.d.ts.map +1 -1
  317. package/dist/v2/components/server/ServerDropdownItem.vue.js +1 -1
  318. package/dist/v2/components/server/ServerDropdownItem.vue.script.js +1 -1
  319. package/dist/v2/components/server/ServerDropdownItem.vue.script.js.map +1 -1
  320. package/dist/v2/components/sidebar/Sidebar.vue.d.ts.map +1 -1
  321. package/dist/v2/components/sidebar/Sidebar.vue.script.js +3 -3
  322. package/dist/v2/components/sidebar/Sidebar.vue.script.js.map +1 -1
  323. package/dist/v2/components/sidebar/SidebarMenu.vue.d.ts.map +1 -1
  324. package/dist/v2/components/sidebar/SidebarMenu.vue.script.js +1 -1
  325. package/dist/v2/components/sidebar/SidebarMenu.vue.script.js.map +1 -1
  326. package/dist/v2/components/sidebar/SidebarToggle.vue.script.js +1 -1
  327. package/dist/v2/components/sidebar/SidebarToggle.vue.script.js.map +1 -1
  328. package/dist/v2/constants.js +1 -1
  329. package/dist/v2/features/command-palette/components/CommandActionForm.vue.script.js +1 -1
  330. package/dist/v2/features/command-palette/components/CommandActionForm.vue.script.js.map +1 -1
  331. package/dist/v2/features/command-palette/components/CommandActionInput.vue.script.js +1 -1
  332. package/dist/v2/features/command-palette/components/CommandActionInput.vue.script.js.map +1 -1
  333. package/dist/v2/features/environments/EnvironmentsList.vue.d.ts.map +1 -1
  334. package/dist/v2/features/environments/EnvironmentsList.vue.script.js +1 -1
  335. package/dist/v2/features/environments/EnvironmentsList.vue.script.js.map +1 -1
  336. package/dist/v2/features/environments/components/Environment.vue.d.ts.map +1 -1
  337. package/dist/v2/features/environments/components/Environment.vue.script.js +1 -1
  338. package/dist/v2/features/environments/components/Environment.vue.script.js.map +1 -1
  339. package/dist/v2/features/environments/components/EnvironmentColors.vue.script.js +3 -2
  340. package/dist/v2/features/environments/components/EnvironmentColors.vue.script.js.map +1 -1
  341. package/dist/v2/features/environments/components/EnvironmentCreateModal.vue.d.ts.map +1 -1
  342. package/dist/v2/features/environments/components/EnvironmentCreateModal.vue.script.js +1 -1
  343. package/dist/v2/features/environments/components/EnvironmentCreateModal.vue.script.js.map +1 -1
  344. package/dist/v2/features/environments/components/EnvironmentDeleteModal.vue.d.ts.map +1 -1
  345. package/dist/v2/features/environments/components/EnvironmentDeleteModal.vue.script.js +1 -1
  346. package/dist/v2/features/environments/components/EnvironmentDeleteModal.vue.script.js.map +1 -1
  347. package/dist/v2/features/environments/components/EnvironmentVariablesDropdown.vue.d.ts.map +1 -1
  348. package/dist/v2/features/environments/components/EnvironmentVariablesDropdown.vue.script.js +1 -1
  349. package/dist/v2/features/environments/components/EnvironmentVariablesDropdown.vue.script.js.map +1 -1
  350. package/dist/v2/features/environments/components/EnvironmentVariablesTable.vue.d.ts.map +1 -1
  351. package/dist/v2/features/environments/components/EnvironmentVariablesTable.vue.js +1 -1
  352. package/dist/v2/features/environments/components/EnvironmentVariablesTable.vue.script.js +1 -1
  353. package/dist/v2/features/environments/components/EnvironmentVariablesTable.vue.script.js.map +1 -1
  354. package/dist/v2/features/modal/Modal.vue.d.ts.map +1 -1
  355. package/dist/v2/features/modal/Modal.vue.script.js +1 -1
  356. package/dist/v2/features/modal/Modal.vue.script.js.map +1 -1
  357. package/dist/v2/features/modal/helpers/create-api-client-modal.js +11 -0
  358. package/dist/v2/features/modal/helpers/create-api-client-modal.js.map +1 -1
  359. package/dist/v2/features/modal/helpers/map-hidden-clients-config.js.map +1 -1
  360. package/dist/v2/features/modal/helpers/resolve-route-parameters.js +1 -1
  361. package/dist/v2/features/modal/helpers/resolve-route-parameters.js.map +1 -1
  362. package/dist/v2/features/modal/hooks/use-modal-sidebar.js.map +1 -1
  363. package/dist/v2/features/modal/modal-events.js.map +1 -1
  364. package/dist/v2/features/operation/Operation.vue.script.js +1 -1
  365. package/dist/v2/features/operation/Operation.vue.script.js.map +1 -1
  366. package/dist/v2/features/search/components/DocumentSearchModal.vue.d.ts.map +1 -1
  367. package/dist/v2/features/search/components/DocumentSearchModal.vue.js +1 -1
  368. package/dist/v2/features/search/components/DocumentSearchModal.vue.script.js +1 -1
  369. package/dist/v2/features/search/components/DocumentSearchModal.vue.script.js.map +1 -1
  370. package/dist/v2/features/search/components/SearchResult.vue.d.ts.map +1 -1
  371. package/dist/v2/features/search/components/SearchResult.vue.script.js +1 -1
  372. package/dist/v2/features/search/components/SearchResult.vue.script.js.map +1 -1
  373. package/dist/v2/features/search/helpers/create-fuse-instance.js.map +1 -1
  374. package/dist/v2/features/search/helpers/create-search-index.js.map +1 -1
  375. package/dist/v2/features/search/hooks/use-document-search.js.map +1 -1
  376. package/dist/v2/features/search/hooks/use-search-index.js.map +1 -1
  377. package/dist/v2/helpers/generate-location-id.js.map +1 -1
  378. package/dist/v2/helpers/handle-hotkeys.js +1 -1
  379. package/dist/v2/helpers/handle-hotkeys.js.map +1 -1
  380. package/dist/v2/helpers/test-utils.js.map +1 -1
  381. package/dist/v2/hooks/use-global-hot-keys.js.map +1 -1
  382. package/dist/v2/hooks/use-scroll-lock.js.map +1 -1
  383. package/dist/v2/workspace-events.js.map +1 -1
  384. package/dist/vue-styles.css +228 -235
  385. package/package.json +22 -22
@@ -9,10 +9,15 @@ import { coerceValue } from "@scalar/workspace-store/schemas/typebox-coerce";
9
9
  * @see https://openid.net/specs/openid-connect-discovery-1_0.html
10
10
  */
11
11
  var OpenIDConnectDiscoverySchema = Type.Object({
12
+ /** URL of the OAuth 2.0 Authorization Endpoint */
12
13
  authorization_endpoint: Type.Optional(Type.String()),
14
+ /** URL of the OAuth 2.0 Token Endpoint */
13
15
  token_endpoint: Type.Optional(Type.String()),
16
+ /** List of OAuth 2.0 scope values that this server supports */
14
17
  scopes_supported: Type.Optional(Type.Array(Type.String())),
18
+ /** List of OAuth 2.0 grant type values that this server supports */
15
19
  grant_types_supported: Type.Optional(Type.Array(Type.String())),
20
+ /** Supported PKCE code challenge methods (RFC 7636) */
16
21
  code_challenge_methods_supported: Type.Optional(Type.Array(Type.String()))
17
22
  });
18
23
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-openid-connect-discovery.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { redirectToProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport { type Static, Type } from '@scalar/typebox'\nimport { coerceValue } from '@scalar/workspace-store/schemas/typebox-coerce'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\n/**\n * OpenID Connect Discovery Document (subset)\n * Represents the metadata fields consumed by the auth selector flow conversion.\n *\n * @see https://openid.net/specs/openid-connect-discovery-1_0.html\n */\nconst OpenIDConnectDiscoverySchema = Type.Object({\n /** URL of the OAuth 2.0 Authorization Endpoint */\n authorization_endpoint: Type.Optional(Type.String()),\n /** URL of the OAuth 2.0 Token Endpoint */\n token_endpoint: Type.Optional(Type.String()),\n /** List of OAuth 2.0 scope values that this server supports */\n scopes_supported: Type.Optional(Type.Array(Type.String())),\n /** List of OAuth 2.0 grant type values that this server supports */\n grant_types_supported: Type.Optional(Type.Array(Type.String())),\n /** Supported PKCE code challenge methods (RFC 7636) */\n code_challenge_methods_supported: Type.Optional(Type.Array(Type.String())),\n})\n\nexport type OpenIDConnectDiscovery = Static<typeof OpenIDConnectDiscoverySchema>\n\n/**\n * The required scope for OpenID Connect requests.\n * If this scope is present, the request is an OIDC request; otherwise, it is a standard OAuth 2.0 request.\n */\nexport const OPENID_SCOPE = 'openid'\n\n/**\n * Fetches the OpenID Connect discovery document from the specified URL.\n * Supports both full discovery URLs and issuer URLs.\n *\n * @param url - The OpenID Connect discovery URL or issuer URL\n * @param proxyUrl - Optional CORS proxy to route the request through\n * @param customFetch - Fetch used for the discovery request; the desktop app passes an IPC-backed fetch so it leaves the renderer's network stack.\n * @returns The discovery document or an error\n */\nexport const fetchOpenIDConnectDiscovery = async (\n url: string,\n proxyUrl: string,\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<OpenIDConnectDiscovery>> => {\n try {\n // If the URL does not end with the well-known path, append it\n let discoveryUrl = url.trim()\n\n if (!discoveryUrl) {\n return [new Error('URL cannot be empty'), null]\n }\n\n // Remove trailing slash if present\n if (discoveryUrl.endsWith('/')) {\n discoveryUrl = discoveryUrl.slice(0, -1)\n }\n\n // If the URL does not already include the well-known path, append it\n if (!discoveryUrl.includes('/.well-known/openid-configuration')) {\n discoveryUrl = `${discoveryUrl}/.well-known/openid-configuration`\n }\n\n const proxiedUrl = redirectToProxy(proxyUrl, discoveryUrl)\n const response = await customFetch(proxiedUrl)\n\n if (!response.ok) {\n return [\n new Error(`Failed to fetch OpenID Connect discovery document: ${response.status} ${response.statusText}`),\n null,\n ]\n }\n\n const data = coerceValue(OpenIDConnectDiscoverySchema, await response.json())\n\n // Validate that we have the essential fields\n if (!data.authorization_endpoint && !data.token_endpoint) {\n return [new Error('Invalid OpenID Connect discovery document: missing required endpoints'), null]\n }\n\n return [null, data]\n } catch (error) {\n if (error instanceof Error) {\n return [error, null]\n }\n return [new Error('Failed to fetch OpenID Connect discovery document'), null]\n }\n}\n"],"mappings":";;;;;;;;;;AAaA,IAAM,+BAA+B,KAAK,OAAO;CAE/C,wBAAwB,KAAK,SAAS,KAAK,QAAQ,CAAC;CAEpD,gBAAgB,KAAK,SAAS,KAAK,QAAQ,CAAC;CAE5C,kBAAkB,KAAK,SAAS,KAAK,MAAM,KAAK,QAAQ,CAAC,CAAC;CAE1D,uBAAuB,KAAK,SAAS,KAAK,MAAM,KAAK,QAAQ,CAAC,CAAC;CAE/D,kCAAkC,KAAK,SAAS,KAAK,MAAM,KAAK,QAAQ,CAAC,CAAC;CAC3E,CAAC;;;;;;;;;;AAmBF,IAAa,8BAA8B,OACzC,KACA,UACA,cAA2B,UACwB;AACnD,KAAI;EAEF,IAAI,eAAe,IAAI,MAAM;AAE7B,MAAI,CAAC,aACH,QAAO,iBAAC,IAAI,MAAM,sBAAsB,EAAE,KAAK;AAIjD,MAAI,aAAa,SAAS,IAAI,CAC5B,gBAAe,aAAa,MAAM,GAAG,GAAG;AAI1C,MAAI,CAAC,aAAa,SAAS,oCAAoC,CAC7D,gBAAe,GAAG,aAAa;EAIjC,MAAM,WAAW,MAAM,YADJ,gBAAgB,UAAU,aAAa,CACZ;AAE9C,MAAI,CAAC,SAAS,GACZ,QAAO,iBACL,IAAI,MAAM,sDAAsD,SAAS,OAAO,GAAG,SAAS,aAAa,EACzG,KACD;EAGH,MAAM,OAAO,YAAY,8BAA8B,MAAM,SAAS,MAAM,CAAC;AAG7E,MAAI,CAAC,KAAK,0BAA0B,CAAC,KAAK,eACxC,QAAO,iBAAC,IAAI,MAAM,wEAAwE,EAAE,KAAK;AAGnG,SAAO,CAAC,MAAM,KAAK;UACZ,OAAO;AACd,MAAI,iBAAiB,MACnB,QAAO,CAAC,OAAO,KAAK;AAEtB,SAAO,iBAAC,IAAI,MAAM,oDAAoD,EAAE,KAAK"}
1
+ {"version":3,"file":"fetch-openid-connect-discovery.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { redirectToProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport { type Static, Type } from '@scalar/typebox'\nimport { coerceValue } from '@scalar/workspace-store/schemas/typebox-coerce'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\n/**\n * OpenID Connect Discovery Document (subset)\n * Represents the metadata fields consumed by the auth selector flow conversion.\n *\n * @see https://openid.net/specs/openid-connect-discovery-1_0.html\n */\nconst OpenIDConnectDiscoverySchema = Type.Object({\n /** URL of the OAuth 2.0 Authorization Endpoint */\n authorization_endpoint: Type.Optional(Type.String()),\n /** URL of the OAuth 2.0 Token Endpoint */\n token_endpoint: Type.Optional(Type.String()),\n /** List of OAuth 2.0 scope values that this server supports */\n scopes_supported: Type.Optional(Type.Array(Type.String())),\n /** List of OAuth 2.0 grant type values that this server supports */\n grant_types_supported: Type.Optional(Type.Array(Type.String())),\n /** Supported PKCE code challenge methods (RFC 7636) */\n code_challenge_methods_supported: Type.Optional(Type.Array(Type.String())),\n})\n\nexport type OpenIDConnectDiscovery = Static<typeof OpenIDConnectDiscoverySchema>\n\n/**\n * The required scope for OpenID Connect requests.\n * If this scope is present, the request is an OIDC request; otherwise, it is a standard OAuth 2.0 request.\n */\nexport const OPENID_SCOPE = 'openid'\n\n/**\n * Fetches the OpenID Connect discovery document from the specified URL.\n * Supports both full discovery URLs and issuer URLs.\n *\n * @param url - The OpenID Connect discovery URL or issuer URL\n * @param proxyUrl - Optional CORS proxy to route the request through\n * @param customFetch - Fetch used for the discovery request; the desktop app passes an IPC-backed fetch so it leaves the renderer's network stack.\n * @returns The discovery document or an error\n */\nexport const fetchOpenIDConnectDiscovery = async (\n url: string,\n proxyUrl: string,\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<OpenIDConnectDiscovery>> => {\n try {\n // If the URL does not end with the well-known path, append it\n let discoveryUrl = url.trim()\n\n if (!discoveryUrl) {\n return [new Error('URL cannot be empty'), null]\n }\n\n // Remove trailing slash if present\n if (discoveryUrl.endsWith('/')) {\n discoveryUrl = discoveryUrl.slice(0, -1)\n }\n\n // If the URL does not already include the well-known path, append it\n if (!discoveryUrl.includes('/.well-known/openid-configuration')) {\n discoveryUrl = `${discoveryUrl}/.well-known/openid-configuration`\n }\n\n const proxiedUrl = redirectToProxy(proxyUrl, discoveryUrl)\n const response = await customFetch(proxiedUrl)\n\n if (!response.ok) {\n return [\n new Error(`Failed to fetch OpenID Connect discovery document: ${response.status} ${response.statusText}`),\n null,\n ]\n }\n\n const data = coerceValue(OpenIDConnectDiscoverySchema, await response.json())\n\n // Validate that we have the essential fields\n if (!data.authorization_endpoint && !data.token_endpoint) {\n return [new Error('Invalid OpenID Connect discovery document: missing required endpoints'), null]\n }\n\n return [null, data]\n } catch (error) {\n if (error instanceof Error) {\n return [error, null]\n }\n return [new Error('Failed to fetch OpenID Connect discovery document'), null]\n }\n}\n"],"mappings":";;;;;;;;;;AAaA,IAAM,+BAA+B,KAAK,OAAO;;CAE/C,wBAAwB,KAAK,SAAS,KAAK,OAAO,CAAC;;CAEnD,gBAAgB,KAAK,SAAS,KAAK,OAAO,CAAC;;CAE3C,kBAAkB,KAAK,SAAS,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;;CAEzD,uBAAuB,KAAK,SAAS,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;;CAE9D,kCAAkC,KAAK,SAAS,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;AAC3E,CAAC;;;;;;;;;;AAmBD,IAAa,8BAA8B,OACzC,KACA,UACA,cAA2B,UACwB;CACnD,IAAI;EAEF,IAAI,eAAe,IAAI,KAAK;EAE5B,IAAI,CAAC,cACH,OAAO,iBAAC,IAAI,MAAM,qBAAqB,GAAG,IAAI;EAIhD,IAAI,aAAa,SAAS,GAAG,GAC3B,eAAe,aAAa,MAAM,GAAG,EAAE;EAIzC,IAAI,CAAC,aAAa,SAAS,mCAAmC,GAC5D,eAAe,GAAG,aAAa;EAIjC,MAAM,WAAW,MAAM,YADJ,gBAAgB,UAAU,YACV,CAAU;EAE7C,IAAI,CAAC,SAAS,IACZ,OAAO,iBACL,IAAI,MAAM,sDAAsD,SAAS,OAAO,GAAG,SAAS,YAAY,GACxG,IACF;EAGF,MAAM,OAAO,YAAY,8BAA8B,MAAM,SAAS,KAAK,CAAC;EAG5E,IAAI,CAAC,KAAK,0BAA0B,CAAC,KAAK,gBACxC,OAAO,iBAAC,IAAI,MAAM,uEAAuE,GAAG,IAAI;EAGlG,OAAO,CAAC,MAAM,IAAI;CACpB,SAAS,OAAO;EACd,IAAI,iBAAiB,OACnB,OAAO,CAAC,OAAO,IAAI;EAErB,OAAO,iBAAC,IAAI,MAAM,mDAAmD,GAAG,IAAI;CAC9E;AACF"}
@@ -70,6 +70,6 @@ var getOAuthCallbackData = (getCallbackUrl, tokenName = "access_token") => {
70
70
  }
71
71
  };
72
72
  //#endregion
73
- export { getOAuthCallbackData };
73
+ export { getOAuthCallbackData, getOAuthCallbackParamWithSource, getOAuthCallbackParams };
74
74
 
75
75
  //# sourceMappingURL=oauth-callback.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-callback.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth-callback.ts"],"sourcesContent":["/**\n * Keeps a callback parameter paired with the URL component it was read from.\n * State validation depends on this source so query and hash values cannot be\n * mixed across different OAuth callback shapes.\n */\ntype OAuthCallbackParamResult = {\n /** The query or hash parameters that contained the value. */\n params: URLSearchParams | null\n /** The callback parameter value, or null when the parameter is missing. */\n value: string | null\n}\n\n/**\n * Normalized OAuth callback data used after the popup returns to a readable\n * redirect URL. Credential params are retained so callers can validate state\n * from the same URL component as the returned credential.\n */\ntype OAuthCallbackData = {\n /** Access token returned by implicit or token-based flows. */\n accessToken: string | null\n /** The URL component that contained the access token. */\n accessTokenParams: URLSearchParams | null\n /** Authorization code returned by authorization-code flows. */\n code: string | null\n /** The URL component that contained the authorization code. */\n codeParams: URLSearchParams | null\n /** OAuth error code returned by the provider. */\n error: string | null\n /** Provider-supplied details for the OAuth error. */\n errorDescription: string | null\n /** Refresh token returned by providers that include one in the callback. */\n refreshToken: string | null\n}\n\n/**\n * Splits an OAuth redirect URL into query and hash parameters.\n *\n * OAuth providers are inconsistent about where they return callback data:\n * authorization-code flows usually use the query string, while implicit flows\n * commonly use the URL fragment. Keeping both sets separate lets callers decide\n * which source should win when a provider sends duplicate keys.\n */\nexport const getOAuthCallbackParams = (\n callbackUrl: string,\n): { searchParams: URLSearchParams; hashParams: URLSearchParams } => {\n const parsedUrl = new URL(callbackUrl)\n\n return {\n searchParams: parsedUrl.searchParams,\n hashParams: new URLSearchParams(parsedUrl.hash.slice(1)),\n }\n}\n\n/**\n * Reads a callback parameter from the query string first, then the hash fragment.\n *\n * Query-string values intentionally take precedence because they are the\n * standard location for authorization-code callbacks. The hash lookup keeps\n * implicit-flow callbacks and non-standard providers working.\n */\nexport const getOAuthCallbackParam = (callbackUrl: string, paramName: string): string | null => {\n const { searchParams, hashParams } = getOAuthCallbackParams(callbackUrl)\n return searchParams.get(paramName) ?? hashParams.get(paramName)\n}\n\n/**\n * Reads a callback parameter and returns the URL component it came from.\n *\n * OAuth state must be validated from the same component as the credential\n * (`code` or `access_token`) so mixed query/hash callbacks cannot pair a\n * trusted state with an untrusted credential.\n */\nexport const getOAuthCallbackParamWithSource = (\n searchParams: URLSearchParams,\n hashParams: URLSearchParams,\n paramName: string,\n): OAuthCallbackParamResult => {\n const searchValue = searchParams.get(paramName)\n if (searchValue !== null) {\n return { params: searchParams, value: searchValue }\n }\n\n const hashValue = hashParams.get(paramName)\n if (hashValue !== null) {\n return { params: hashParams, value: hashValue }\n }\n\n return { params: null, value: null }\n}\n\n/**\n * Safely reads the OAuth popup callback data.\n *\n * Accessing the popup URL can throw while it is still on another origin, so\n * callers get null values until the popup returns to a readable callback URL.\n */\nexport const getOAuthCallbackData = (getCallbackUrl: () => string, tokenName = 'access_token'): OAuthCallbackData => {\n try {\n const { searchParams, hashParams } = getOAuthCallbackParams(getCallbackUrl())\n const accessTokenResult = getOAuthCallbackParamWithSource(searchParams, hashParams, tokenName)\n const codeResult = getOAuthCallbackParamWithSource(searchParams, hashParams, 'code')\n\n return {\n accessToken: accessTokenResult.value,\n accessTokenParams: accessTokenResult.params,\n code: codeResult.value,\n codeParams: codeResult.params,\n error: searchParams.get('error') ?? hashParams.get('error'),\n errorDescription: searchParams.get('error_description') ?? hashParams.get('error_description'),\n refreshToken: searchParams.get('refresh_token') ?? hashParams.get('refresh_token'),\n }\n } catch (_e) {\n // Ignore CORS errors while the popup is still on the provider origin.\n return {\n accessToken: null,\n accessTokenParams: null,\n code: null,\n codeParams: null,\n error: null,\n errorDescription: null,\n refreshToken: null,\n }\n }\n}\n"],"mappings":";;;;;;;;;AA0CA,IAAa,0BACX,gBACmE;CACnE,MAAM,YAAY,IAAI,IAAI,YAAY;AAEtC,QAAO;EACL,cAAc,UAAU;EACxB,YAAY,IAAI,gBAAgB,UAAU,KAAK,MAAM,EAAE,CAAC;EACzD;;;;;;;;;AAsBH,IAAa,mCACX,cACA,YACA,cAC6B;CAC7B,MAAM,cAAc,aAAa,IAAI,UAAU;AAC/C,KAAI,gBAAgB,KAClB,QAAO;EAAE,QAAQ;EAAc,OAAO;EAAa;CAGrD,MAAM,YAAY,WAAW,IAAI,UAAU;AAC3C,KAAI,cAAc,KAChB,QAAO;EAAE,QAAQ;EAAY,OAAO;EAAW;AAGjD,QAAO;EAAE,QAAQ;EAAM,OAAO;EAAM;;;;;;;;AAStC,IAAa,wBAAwB,gBAA8B,YAAY,mBAAsC;AACnH,KAAI;EACF,MAAM,EAAE,cAAc,eAAe,uBAAuB,gBAAgB,CAAC;EAC7E,MAAM,oBAAoB,gCAAgC,cAAc,YAAY,UAAU;EAC9F,MAAM,aAAa,gCAAgC,cAAc,YAAY,OAAO;AAEpF,SAAO;GACL,aAAa,kBAAkB;GAC/B,mBAAmB,kBAAkB;GACrC,MAAM,WAAW;GACjB,YAAY,WAAW;GACvB,OAAO,aAAa,IAAI,QAAQ,IAAI,WAAW,IAAI,QAAQ;GAC3D,kBAAkB,aAAa,IAAI,oBAAoB,IAAI,WAAW,IAAI,oBAAoB;GAC9F,cAAc,aAAa,IAAI,gBAAgB,IAAI,WAAW,IAAI,gBAAgB;GACnF;UACM,IAAI;AAEX,SAAO;GACL,aAAa;GACb,mBAAmB;GACnB,MAAM;GACN,YAAY;GACZ,OAAO;GACP,kBAAkB;GAClB,cAAc;GACf"}
1
+ {"version":3,"file":"oauth-callback.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth-callback.ts"],"sourcesContent":["/**\n * Keeps a callback parameter paired with the URL component it was read from.\n * State validation depends on this source so query and hash values cannot be\n * mixed across different OAuth callback shapes.\n */\ntype OAuthCallbackParamResult = {\n /** The query or hash parameters that contained the value. */\n params: URLSearchParams | null\n /** The callback parameter value, or null when the parameter is missing. */\n value: string | null\n}\n\n/**\n * Normalized OAuth callback data used after the popup returns to a readable\n * redirect URL. Credential params are retained so callers can validate state\n * from the same URL component as the returned credential.\n */\ntype OAuthCallbackData = {\n /** Access token returned by implicit or token-based flows. */\n accessToken: string | null\n /** The URL component that contained the access token. */\n accessTokenParams: URLSearchParams | null\n /** Authorization code returned by authorization-code flows. */\n code: string | null\n /** The URL component that contained the authorization code. */\n codeParams: URLSearchParams | null\n /** OAuth error code returned by the provider. */\n error: string | null\n /** Provider-supplied details for the OAuth error. */\n errorDescription: string | null\n /** Refresh token returned by providers that include one in the callback. */\n refreshToken: string | null\n}\n\n/**\n * Splits an OAuth redirect URL into query and hash parameters.\n *\n * OAuth providers are inconsistent about where they return callback data:\n * authorization-code flows usually use the query string, while implicit flows\n * commonly use the URL fragment. Keeping both sets separate lets callers decide\n * which source should win when a provider sends duplicate keys.\n */\nexport const getOAuthCallbackParams = (\n callbackUrl: string,\n): { searchParams: URLSearchParams; hashParams: URLSearchParams } => {\n const parsedUrl = new URL(callbackUrl)\n\n return {\n searchParams: parsedUrl.searchParams,\n hashParams: new URLSearchParams(parsedUrl.hash.slice(1)),\n }\n}\n\n/**\n * Reads a callback parameter from the query string first, then the hash fragment.\n *\n * Query-string values intentionally take precedence because they are the\n * standard location for authorization-code callbacks. The hash lookup keeps\n * implicit-flow callbacks and non-standard providers working.\n */\nexport const getOAuthCallbackParam = (callbackUrl: string, paramName: string): string | null => {\n const { searchParams, hashParams } = getOAuthCallbackParams(callbackUrl)\n return searchParams.get(paramName) ?? hashParams.get(paramName)\n}\n\n/**\n * Reads a callback parameter and returns the URL component it came from.\n *\n * OAuth state must be validated from the same component as the credential\n * (`code` or `access_token`) so mixed query/hash callbacks cannot pair a\n * trusted state with an untrusted credential.\n */\nexport const getOAuthCallbackParamWithSource = (\n searchParams: URLSearchParams,\n hashParams: URLSearchParams,\n paramName: string,\n): OAuthCallbackParamResult => {\n const searchValue = searchParams.get(paramName)\n if (searchValue !== null) {\n return { params: searchParams, value: searchValue }\n }\n\n const hashValue = hashParams.get(paramName)\n if (hashValue !== null) {\n return { params: hashParams, value: hashValue }\n }\n\n return { params: null, value: null }\n}\n\n/**\n * Safely reads the OAuth popup callback data.\n *\n * Accessing the popup URL can throw while it is still on another origin, so\n * callers get null values until the popup returns to a readable callback URL.\n */\nexport const getOAuthCallbackData = (getCallbackUrl: () => string, tokenName = 'access_token'): OAuthCallbackData => {\n try {\n const { searchParams, hashParams } = getOAuthCallbackParams(getCallbackUrl())\n const accessTokenResult = getOAuthCallbackParamWithSource(searchParams, hashParams, tokenName)\n const codeResult = getOAuthCallbackParamWithSource(searchParams, hashParams, 'code')\n\n return {\n accessToken: accessTokenResult.value,\n accessTokenParams: accessTokenResult.params,\n code: codeResult.value,\n codeParams: codeResult.params,\n error: searchParams.get('error') ?? hashParams.get('error'),\n errorDescription: searchParams.get('error_description') ?? hashParams.get('error_description'),\n refreshToken: searchParams.get('refresh_token') ?? hashParams.get('refresh_token'),\n }\n } catch (_e) {\n // Ignore CORS errors while the popup is still on the provider origin.\n return {\n accessToken: null,\n accessTokenParams: null,\n code: null,\n codeParams: null,\n error: null,\n errorDescription: null,\n refreshToken: null,\n }\n }\n}\n"],"mappings":";;;;;;;;;AA0CA,IAAa,0BACX,gBACmE;CACnE,MAAM,YAAY,IAAI,IAAI,WAAW;CAErC,OAAO;EACL,cAAc,UAAU;EACxB,YAAY,IAAI,gBAAgB,UAAU,KAAK,MAAM,CAAC,CAAC;CACzD;AACF;;;;;;;;AAqBA,IAAa,mCACX,cACA,YACA,cAC6B;CAC7B,MAAM,cAAc,aAAa,IAAI,SAAS;CAC9C,IAAI,gBAAgB,MAClB,OAAO;EAAE,QAAQ;EAAc,OAAO;CAAY;CAGpD,MAAM,YAAY,WAAW,IAAI,SAAS;CAC1C,IAAI,cAAc,MAChB,OAAO;EAAE,QAAQ;EAAY,OAAO;CAAU;CAGhD,OAAO;EAAE,QAAQ;EAAM,OAAO;CAAK;AACrC;;;;;;;AAQA,IAAa,wBAAwB,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AAG,IAAI,EACjC,uBAAsB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,KAChD,gBAWF,CAAA;AAuCD;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAC1B,OAAO,sBAAsB,EAC7B,MAAM,MAAM,sBAAsB,EAClC,gBAAgB,MAAM,EAAE;AACxB,wEAAwE;AACxE,cAAc,YAAY,GAAG,IAAI;AACjC,kCAAkC;AAClC,UAAU,MAAM;AAChB,6FAA6F;AAC7F,uBAAsB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM;AACjD,mHAAmH;AACnH,cAAc,WAAW;AACzB;;;;GAIG;AACH,kBAAkB,qBAAqB,KACtC,OAAO,CAAC,aAAa,CAAC,YAAY,CAAC,CA6NrC,CAAA;AA+ID;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,GAC7B,OAAO,sBAAsB,EAC7B,MAAM,gBAAgB;AACtB,kCAAkC;AAClC,UAAU,MAAM;AAChB,+DAA+D;AAC/D,cAAc,YAAY,GAAG,IAAI;AACjC,2EAA2E;AAC3E,uBAAsB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM;AACjD,gIAAgI;AAChI,cAAa,WAAmB,KAC/B,OAAO,CAAC,aAAa,CAAC,YAAY,CAAC,CAqFrC,CAAA"}
@@ -6,13 +6,6 @@ import { isRelativePath } from "@scalar/helpers/url/is-relative-path";
6
6
  import { shouldUseProxy } from "@scalar/helpers/url/redirect-to-proxy";
7
7
  import { encode, fromUint8Array } from "js-base64";
8
8
  //#region src/v2/blocks/scalar-auth-selector-block/helpers/oauth.ts
9
- var authorizationCodeUsesPkcePublicClient = (flowType, flow) => {
10
- if (flowType !== "authorizationCode") return false;
11
- const authCode = flow;
12
- if (!authCode) return false;
13
- const pkceMode = authCode["x-usePkce"];
14
- return pkceMode === "SHA-256" || pkceMode === "plain";
15
- };
16
9
  /**
17
10
  * Resolves the active server URL using OpenAPI server variables first, then
18
11
  * Scalar environment variables.
@@ -36,7 +29,7 @@ var getActiveServerBase = (activeServer, environmentVariables = {}) => {
36
29
  * @see https://www.rfc-editor.org/rfc/rfc7636#page-8
37
30
  */
38
31
  var generateCodeVerifier = () => {
39
- const buffer = new Uint8Array(32);
32
+ const buffer = /* @__PURE__ */ new Uint8Array(32);
40
33
  crypto.getRandomValues(buffer);
41
34
  return fromUint8Array(buffer, true);
42
35
  };
@@ -177,8 +170,11 @@ var authorizeServers = async (flows, type, scopes, { code, pkce, proxyUrl, custo
177
170
  if (scopes && (type === "clientCredentials" || type === "password")) formData.set("scope", scopes);
178
171
  /** Where to add the credentials */
179
172
  const addCredentialsToBody = flow["x-scalar-credentials-location"] === "body";
180
- const pkcePublicClient = authorizationCodeUsesPkcePublicClient(type, flow);
181
- const hasClientSecret = Boolean(flow["x-scalar-secret-client-secret"]) && !pkcePublicClient;
173
+ /**
174
+ * PKCE and client authentication are independent: a confidential client may use both.
175
+ * We send the client_secret whenever one is set, regardless of PKCE (see RFC 9700 Section 2.1.1).
176
+ */
177
+ const hasClientSecret = Boolean(flow["x-scalar-secret-client-secret"]);
182
178
  if (addCredentialsToBody || type === "authorizationCode" && !hasClientSecret) formData.set("client_id", flow["x-scalar-secret-client-id"]);
183
179
  if (addCredentialsToBody && hasClientSecret) formData.set("client_secret", flow["x-scalar-secret-client-secret"]);
184
180
  if (redirectUri) formData.set("redirect_uri", redirectUri);
@@ -231,8 +227,8 @@ var refreshOauth2Token = async (flows, type, proxyUrl, activeServer, environment
231
227
  formData.set("grant_type", "refresh_token");
232
228
  formData.set("refresh_token", refreshToken);
233
229
  const addCredentialsToBody = flow["x-scalar-credentials-location"] === "body";
234
- const pkcePublicClient = authorizationCodeUsesPkcePublicClient(type, flow);
235
- const hasClientSecret = Boolean(flow["x-scalar-secret-client-secret"]) && !pkcePublicClient;
230
+ /** A confidential client keeps using its secret on refresh, even when PKCE is enabled. */
231
+ const hasClientSecret = Boolean(flow["x-scalar-secret-client-secret"]);
236
232
  if (addCredentialsToBody || type === "authorizationCode" && !hasClientSecret) formData.set("client_id", flow["x-scalar-secret-client-id"]);
237
233
  if (addCredentialsToBody && hasClientSecret) formData.set("client_secret", flow["x-scalar-secret-client-secret"]);
238
234
  if (flow["x-scalar-security-body"]) Object.entries(flow["x-scalar-security-body"]).forEach(([key, value]) => {
@@ -259,6 +255,6 @@ var refreshOauth2Token = async (flows, type, proxyUrl, activeServer, environment
259
255
  }
260
256
  };
261
257
  //#endregion
262
- export { authorizeOauth2, refreshOauth2Token };
258
+ export { authorizeOauth2, getActiveServerBase, getServerUrl, refreshOauth2Token };
263
259
 
264
260
  //# sourceMappingURL=oauth.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { replaceEnvVariables, replacePathVariables } from '@scalar/helpers/regex/replace-variables'\nimport { isRelativePath } from '@scalar/helpers/url/is-relative-path'\nimport { makeUrlAbsolute } from '@scalar/helpers/url/make-url-absolute'\nimport { shouldUseProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport type { OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example'\nimport { getServerVariables } from '@scalar/workspace-store/request-example'\nimport type { ServerObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { encode, fromUint8Array } from 'js-base64'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\nimport { getOAuthCallbackData } from './oauth-callback'\n\n/** Oauth2 security schemes which are not implicit */\ntype NonImplicitFlows = Omit<OAuthFlowsObjectSecret, 'implicit'>\n\nconst authorizationCodeUsesPkcePublicClient = (\n flowType: keyof NonImplicitFlows,\n flow: NonImplicitFlows[keyof NonImplicitFlows],\n): boolean => {\n if (flowType !== 'authorizationCode') {\n return false\n }\n const authCode = flow as OAuthFlowsObjectSecret['authorizationCode']\n if (!authCode) {\n return false\n }\n const pkceMode = authCode['x-usePkce']\n return pkceMode === 'SHA-256' || pkceMode === 'plain'\n}\n\ntype PKCEState = {\n codeVerifier: string\n codeChallenge: string\n codeChallengeMethod: string\n}\n\ntype ActiveServerBase = { basePath: string } | { baseUrl: string } | Record<string, never>\n\nexport type OAuth2Tokens = {\n accessToken: string\n refreshToken?: string\n}\n\n/**\n * Captures the OAuth2 redirect for environments where the browser-popup polling\n * approach cannot work (notably the Electron desktop app, where the renderer\n * runs on `file://` and providers reject `file://` redirect URIs).\n *\n * The implementation opens the authorization URL in the system browser and\n * resolves once the provider redirects back. Because the redirect target (for\n * example an ephemeral loopback port) is only known to the host environment, the\n * implementation appends the `redirect_uri` itself and reports back the exact\n * value it used so the token exchange can send the matching `redirect_uri`.\n */\nexport type CaptureOAuth2Callback = (params: {\n /** The fully built authorization URL, without a `redirect_uri` parameter. */\n authorizationUrl: string\n}) => Promise<\n ErrorResponse<{\n /** The full callback URL the provider redirected to, including query and/or hash params. */\n callbackUrl: string\n /** The `redirect_uri` the host environment used, so the token exchange can match it. */\n redirectUri: string\n }>\n>\n\n/** Flow types that support token refresh (all except implicit) */\ntype RefreshableFlows = Exclude<keyof OAuthFlowsObjectSecret, 'implicit'>\n\n/**\n * Resolves the active server URL using OpenAPI server variables first, then\n * Scalar environment variables.\n */\nexport const getServerUrl = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): string =>\n replaceEnvVariables(\n replacePathVariables(activeServer?.url ?? '', getServerVariables(activeServer)),\n environmentVariables,\n )\n\n/**\n * Builds the base option used when OAuth URLs are relative to the active server.\n *\n * Relative server URLs become browser-only base paths because they need the\n * current window location to resolve correctly.\n */\nexport const getActiveServerBase = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): ActiveServerBase => {\n const serverUrl = getServerUrl(activeServer, environmentVariables)\n if (!serverUrl) {\n return {}\n }\n\n if (isRelativePath(serverUrl)) {\n return typeof window === 'undefined' ? {} : { basePath: serverUrl }\n }\n\n return { baseUrl: serverUrl }\n}\n\n/**\n * Generates a random string for PKCE code verifier\n *\n * @see https://www.rfc-editor.org/rfc/rfc7636#page-8\n */\nconst generateCodeVerifier = (): string => {\n // Generate 32 random bytes\n const buffer = new Uint8Array(32)\n crypto.getRandomValues(buffer)\n\n // Base64URL encode the bytes\n return fromUint8Array(buffer, true)\n}\n\n/**\n * Creates a code challenge from the code verifier\n */\nconst generateCodeChallenge = async (verifier: string, encoding: 'SHA-256' | 'plain'): Promise<string> => {\n if (encoding === 'plain') {\n return verifier\n }\n\n // If crypto.subtle.digest is not a function, we cannot use SHA-256\n if (typeof crypto?.subtle?.digest !== 'function') {\n console.warn('SHA-256 is only supported when using https, using a plain text code challenge instead.')\n return verifier\n }\n\n // ASCII encoding is just taking the lower 8 bits of each character\n const encoder = new TextEncoder()\n const data = encoder.encode(verifier)\n const digest = await crypto.subtle.digest('SHA-256', data)\n\n // Base64URL encode the bytes\n return fromUint8Array(new Uint8Array(digest), true)\n}\n\n/**\n * Authorize oauth2 flow\n *\n * @returns the resolved oauth2 tokens\n */\nexport const authorizeOauth2 = async (\n flows: OAuthFlowsObjectSecret,\n type: keyof OAuthFlowsObjectSecret,\n selectedScopes: string[],\n /** We use the active server to set a base for relative redirect uris */\n activeServer: ServerObject | null,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** Flattened environment variables used to resolve server URL templates like `{protocol}` */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the token request; the desktop app passes an IPC-backed fetch (see {@link authorizeServers}). */\n customFetch?: CustomFetch,\n /**\n * Optional redirect capture for interactive flows (authorization code and implicit).\n * When provided, the system browser plus a host-owned redirect target replaces the\n * default popup-polling approach. Required for the Electron desktop app.\n */\n captureCallback?: CaptureOAuth2Callback,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n try {\n if (!flow) {\n return [new Error('Flow not found'), null]\n }\n\n const scopes = selectedScopes.join(' ')\n\n // Client Credentials or Password Flow\n if (type === 'clientCredentials' || type === 'password') {\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n // Generate a random state string with the length of 8 characters\n const state = (Math.random() + 1).toString(36).substring(2, 10)\n\n const authorizationUrl = makeUrlAbsolute(\n flows[type]!['x-scalar-secret-auth-url'] ?? flows[type]!.authorizationUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n\n const url = new URL(authorizationUrl)\n\n /** Special PKCE state */\n let pkce: PKCEState | null = null\n\n // Params unique to the flows\n if (type === 'implicit') {\n url.searchParams.set('response_type', 'token')\n } else if (type === 'authorizationCode') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n url.searchParams.set('response_type', 'code')\n\n // PKCE\n if (typedFlow['x-usePkce'] !== 'no') {\n const codeVerifier = generateCodeVerifier()\n const codeChallenge = await generateCodeChallenge(codeVerifier, typedFlow['x-usePkce'])\n\n // Set state for later verification\n pkce = {\n codeVerifier,\n codeChallenge,\n codeChallengeMethod: typedFlow['x-usePkce'] === 'SHA-256' ? 'S256' : 'plain',\n }\n\n // Set the code challenge and method on the url\n url.searchParams.set('code_challenge', codeChallenge)\n url.searchParams.set('code_challenge_method', pkce.codeChallengeMethod)\n }\n }\n\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n // The capture path appends its own `redirect_uri` (it owns the target, for\n // example an ephemeral loopback port), so we only set it here for the popup path.\n if (!captureCallback) {\n // Handle relative redirect uris\n if (typedFlow['x-scalar-secret-redirect-uri'].startsWith('/')) {\n const baseUrl =\n getServerUrl(activeServer, environmentVariables) || window.location.origin + window.location.pathname\n const redirectUri = new URL(typedFlow['x-scalar-secret-redirect-uri'], baseUrl).toString()\n\n url.searchParams.set('redirect_uri', redirectUri)\n } else {\n url.searchParams.set('redirect_uri', typedFlow['x-scalar-secret-redirect-uri'])\n }\n }\n\n if (flow['x-scalar-security-query']) {\n Object.keys(flow['x-scalar-security-query']).forEach((key: string): void => {\n const value = flow['x-scalar-security-query']?.[key]\n if (!value) {\n return\n }\n url.searchParams.set(key, value)\n })\n }\n\n // Common to all flows\n url.searchParams.set('client_id', flow['x-scalar-secret-client-id'])\n url.searchParams.set('state', state)\n if (scopes) {\n url.searchParams.set('scope', scopes)\n }\n\n // Capture path: open the system browser and let the host environment catch\n // the redirect (used by the desktop app, where popup polling cannot work).\n if (captureCallback) {\n const [captureError, capture] = await captureCallback({ authorizationUrl: url.toString() })\n\n if (captureError || !capture) {\n return [captureError ?? new Error('Failed to capture the OAuth2 redirect'), null]\n }\n\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => capture.callbackUrl, flow['x-tokenName'] || 'access_token')\n\n if (error) {\n return [new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null]\n }\n\n // Implicit Flow\n if (accessToken) {\n if ((accessTokenParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return [null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }]\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n if ((codeParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n // The token request must echo the exact redirect_uri used in the authorization request.\n redirectUri: capture.redirectUri,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n return [new Error('No authorization code or access token was returned'), null]\n }\n\n const windowFeatures = 'left=100,top=100,width=800,height=600'\n const authWindow = window.open(url, 'openAuth2Window', windowFeatures)\n\n // Open up a window and poll until closed or we have the data we want\n if (authWindow) {\n // We need to return a promise here due to the setInterval\n return new Promise<ErrorResponse<OAuth2Tokens>>((resolve) => {\n const checkWindowClosed = setInterval(() => {\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => authWindow.location.href, flow['x-tokenName'] || 'access_token')\n\n // The window has closed OR we have what we are looking for so we stop polling\n if (authWindow.closed || accessToken || code || error) {\n clearInterval(checkWindowClosed)\n authWindow.close()\n\n if (error) {\n resolve([new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null])\n return\n }\n\n // Implicit Flow\n if (accessToken) {\n const _state = accessTokenParams?.get('state') ?? null\n\n if (_state === state) {\n resolve([null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }])\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n const _state = codeParams?.get('state') ?? null\n\n if (_state === state) {\n void authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n .then(resolve)\n .catch((error: unknown) => {\n resolve([\n error instanceof Error ? error : new Error('Failed to get an access token', { cause: error }),\n null,\n ])\n })\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // User closed window without authorizing\n resolve([new Error('Window was closed without granting authorization'), null])\n }\n }, 200)\n })\n }\n return [new Error('Failed to open auth window'), null]\n } catch (error) {\n return [error instanceof Error ? error : new Error('Failed to authorize oauth2 flow', { cause: error }), null]\n }\n}\n\n/**\n * Makes the BE authorization call to grab the token server to server\n * Used for clientCredentials and authorizationCode\n */\nconst authorizeServers = async (\n flows: NonImplicitFlows,\n type: keyof NonImplicitFlows,\n scopes: string,\n {\n code,\n pkce,\n proxyUrl,\n customFetch = fetch,\n redirectUri,\n }: {\n code?: string\n pkce?: PKCEState | null\n proxyUrl?: string\n customFetch?: CustomFetch\n /** Overrides the stored redirect_uri (the capture path owns the real target). */\n redirectUri?: string\n } = {},\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const formData = new URLSearchParams()\n\n // Only client credentials and password flows support scopes in the token request\n if (scopes && (type === 'clientCredentials' || type === 'password')) {\n formData.set('scope', scopes)\n }\n\n /** Where to add the credentials */\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n const pkcePublicClient = authorizationCodeUsesPkcePublicClient(type, flow)\n const hasClientSecret = Boolean(flow['x-scalar-secret-client-secret']) && !pkcePublicClient\n /**\n * Public authorization-code clients still need client_id in the token body.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', flow['x-scalar-secret-client-id'])\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', flow['x-scalar-secret-client-secret'])\n }\n if (redirectUri) {\n formData.set('redirect_uri', redirectUri)\n } else if ('x-scalar-secret-redirect-uri' in flow && flow['x-scalar-secret-redirect-uri']) {\n formData.set('redirect_uri', flow['x-scalar-secret-redirect-uri'])\n }\n\n // Authorization Code\n if (code) {\n formData.set('code', code)\n formData.set('grant_type', 'authorization_code')\n\n // PKCE\n if (pkce) {\n formData.set('code_verifier', pkce.codeVerifier)\n }\n }\n // Password\n else if (type === 'password') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n formData.set('grant_type', 'password')\n formData.set('username', typedFlow['x-scalar-secret-username'])\n formData.set('password', typedFlow['x-scalar-secret-password'])\n }\n // Client Credentials\n else {\n formData.set('grant_type', 'client_credentials')\n }\n\n // Additional request body parameters\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n // Add client id + secret to headers for confidential clients.\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${flow['x-scalar-secret-client-id']}:${flow['x-scalar-secret-client-secret']}`)}`\n }\n\n // Check if we should use the proxy\n const tokenUrl = makeUrlAbsolute(\n flow['x-scalar-secret-token-url'] ?? flow.tokenUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n const url = shouldUseProxy(proxyUrl, tokenUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', tokenUrl]]).toString()}`\n : tokenUrl\n\n // Make the call\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n // Use custom token name if specified, otherwise default to access_token\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const refreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Failed to get an access token'), null]\n }\n\n return [null, { accessToken, ...(typeof refreshToken === 'string' ? { refreshToken } : {}) }]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to get an access token. Please check your credentials.', { cause: error }),\n null,\n ]\n }\n}\n\n/**\n * Exchange a refresh token for a new access token using the `grant_type=refresh_token` flow.\n *\n * Uses the stored refresh token, client credentials, and the token URL (or refreshUrl when available)\n * to request fresh tokens from the authorization server per RFC 6749 Section 6.\n */\nexport const refreshOauth2Token = async (\n flows: OAuthFlowsObjectSecret,\n type: RefreshableFlows,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** We use the active server to set a base for relative URLs */\n activeServer: ServerObject | null,\n /** Flattened environment variables used to resolve server URL templates */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the refresh request; the desktop app passes an IPC-backed fetch so it leaves the renderer's network stack. */\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const refreshToken = flow['x-scalar-secret-refresh-token']\n if (!refreshToken) {\n return [new Error('No refresh token available'), null]\n }\n\n const formData = new URLSearchParams()\n formData.set('grant_type', 'refresh_token')\n formData.set('refresh_token', refreshToken)\n\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n const pkcePublicClient = authorizationCodeUsesPkcePublicClient(type, flow)\n const hasClientSecret = Boolean(flow['x-scalar-secret-client-secret']) && !pkcePublicClient\n /**\n * Public authorization-code clients still need client_id in the refresh body per RFC 6749 Section 6.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', flow['x-scalar-secret-client-id'])\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', flow['x-scalar-secret-client-secret'])\n }\n\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${flow['x-scalar-secret-client-id']}:${flow['x-scalar-secret-client-secret']}`)}`\n }\n\n const refreshUrl = flow.refreshUrl || flow['x-scalar-secret-token-url'] || flow.tokenUrl\n const absoluteRefreshUrl = makeUrlAbsolute(refreshUrl, getActiveServerBase(activeServer, environmentVariables))\n const url = shouldUseProxy(proxyUrl, absoluteRefreshUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', absoluteRefreshUrl]]).toString()}`\n : absoluteRefreshUrl\n\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const newRefreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Token refresh failed'), null]\n }\n\n return [\n null,\n {\n accessToken,\n ...(typeof newRefreshToken === 'string' ? { refreshToken: newRefreshToken } : { refreshToken }),\n },\n ]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to ref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,KAAI,wBAAwB,gBAC1B,UAAS,IAAI,iBAAiB,KAAK,iCAAiC;AAGtE,KAAI,KAAK,0BACP,QAAO,QAAQ,KAAK,0BAA0B,CAAC,SAAS,CAAC,KAAK,WAAW;AACvE,MAAI,UAAU,KAAA,KAAa,UAAU,KACnC,UAAS,IAAI,KAAK,OAAO,MAAM,CAAC;GAElC;AAGJ,KAAI;EACF,MAAM,UAAkC,EACtC,gBAAgB,qCACjB;AAED,MAAI,CAAC,wBAAwB,gBAC3B,SAAQ,gBAAgB,SAAS,OAAO,GAAG,KAAK,6BAA6B,GAAG,KAAK,mCAAmC;EAI1H,MAAM,qBAAqB,gBADR,KAAK,cAAc,KAAK,gCAAgC,KAAK,UACzB,oBAAoB,cAAc,qBAAqB,CAAC;EAU/G,MAAM,eAAe,OALR,MAAM,YAJP,eAAe,UAAU,mBAAmB,GACpD,GAAG,SAAS,GAAG,IAAI,gBAAgB,CAAC,CAAC,cAAc,mBAAmB,CAAC,CAAC,CAAC,UAAU,KACnF,oBAEgC;GAClC,QAAQ;GACR;GACA,MAAM;GACP,CAAC,EAC8B,MAAM;EAGtC,MAAM,cAAc,aADF,KAAK,kBAAkB;EAEzC,MAAM,kBAAkB,aAAa;AAErC,MAAI,CAAC,YACH,QAAO,CAAC,IAAI,MAAM,aAAa,qBAAqB,aAAa,SAAS,uBAAuB,EAAE,KAAK;AAG1G,SAAO,CACL,MACA;GACE;GACA,GAAI,OAAO,oBAAoB,WAAW,EAAE,cAAc,iBAAiB,GAAG,EAAE,cAAc;GAC/F,CACF;UACM,OAAO;AACd,SAAO,CACL,iBAAiB,QACb,QACA,IAAI,MAAM,4DAA4D,EAAE,OAAO,OAAO,CAAC,EAC3F,KACD"}
1
+ {"version":3,"file":"oauth.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { replaceEnvVariables, replacePathVariables } from '@scalar/helpers/regex/replace-variables'\nimport { isRelativePath } from '@scalar/helpers/url/is-relative-path'\nimport { makeUrlAbsolute } from '@scalar/helpers/url/make-url-absolute'\nimport { shouldUseProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport type { OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example'\nimport { getServerVariables } from '@scalar/workspace-store/request-example'\nimport type { ServerObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport { encode, fromUint8Array } from 'js-base64'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\nimport { getOAuthCallbackData } from './oauth-callback'\n\n/** Oauth2 security schemes which are not implicit */\ntype NonImplicitFlows = Omit<OAuthFlowsObjectSecret, 'implicit'>\n\ntype PKCEState = {\n codeVerifier: string\n codeChallenge: string\n codeChallengeMethod: string\n}\n\ntype ActiveServerBase = { basePath: string } | { baseUrl: string } | Record<string, never>\n\nexport type OAuth2Tokens = {\n accessToken: string\n refreshToken?: string\n}\n\n/**\n * Captures the OAuth2 redirect for environments where the browser-popup polling\n * approach cannot work (notably the Electron desktop app, where the renderer\n * runs on `file://` and providers reject `file://` redirect URIs).\n *\n * The implementation opens the authorization URL in the system browser and\n * resolves once the provider redirects back. Because the redirect target (for\n * example an ephemeral loopback port) is only known to the host environment, the\n * implementation appends the `redirect_uri` itself and reports back the exact\n * value it used so the token exchange can send the matching `redirect_uri`.\n */\nexport type CaptureOAuth2Callback = (params: {\n /** The fully built authorization URL, without a `redirect_uri` parameter. */\n authorizationUrl: string\n}) => Promise<\n ErrorResponse<{\n /** The full callback URL the provider redirected to, including query and/or hash params. */\n callbackUrl: string\n /** The `redirect_uri` the host environment used, so the token exchange can match it. */\n redirectUri: string\n }>\n>\n\n/** Flow types that support token refresh (all except implicit) */\ntype RefreshableFlows = Exclude<keyof OAuthFlowsObjectSecret, 'implicit'>\n\n/**\n * Resolves the active server URL using OpenAPI server variables first, then\n * Scalar environment variables.\n */\nexport const getServerUrl = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): string =>\n replaceEnvVariables(\n replacePathVariables(activeServer?.url ?? '', getServerVariables(activeServer)),\n environmentVariables,\n )\n\n/**\n * Builds the base option used when OAuth URLs are relative to the active server.\n *\n * Relative server URLs become browser-only base paths because they need the\n * current window location to resolve correctly.\n */\nexport const getActiveServerBase = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): ActiveServerBase => {\n const serverUrl = getServerUrl(activeServer, environmentVariables)\n if (!serverUrl) {\n return {}\n }\n\n if (isRelativePath(serverUrl)) {\n return typeof window === 'undefined' ? {} : { basePath: serverUrl }\n }\n\n return { baseUrl: serverUrl }\n}\n\n/**\n * Generates a random string for PKCE code verifier\n *\n * @see https://www.rfc-editor.org/rfc/rfc7636#page-8\n */\nconst generateCodeVerifier = (): string => {\n // Generate 32 random bytes\n const buffer = new Uint8Array(32)\n crypto.getRandomValues(buffer)\n\n // Base64URL encode the bytes\n return fromUint8Array(buffer, true)\n}\n\n/**\n * Creates a code challenge from the code verifier\n */\nconst generateCodeChallenge = async (verifier: string, encoding: 'SHA-256' | 'plain'): Promise<string> => {\n if (encoding === 'plain') {\n return verifier\n }\n\n // If crypto.subtle.digest is not a function, we cannot use SHA-256\n if (typeof crypto?.subtle?.digest !== 'function') {\n console.warn('SHA-256 is only supported when using https, using a plain text code challenge instead.')\n return verifier\n }\n\n // ASCII encoding is just taking the lower 8 bits of each character\n const encoder = new TextEncoder()\n const data = encoder.encode(verifier)\n const digest = await crypto.subtle.digest('SHA-256', data)\n\n // Base64URL encode the bytes\n return fromUint8Array(new Uint8Array(digest), true)\n}\n\n/**\n * Authorize oauth2 flow\n *\n * @returns the resolved oauth2 tokens\n */\nexport const authorizeOauth2 = async (\n flows: OAuthFlowsObjectSecret,\n type: keyof OAuthFlowsObjectSecret,\n selectedScopes: string[],\n /** We use the active server to set a base for relative redirect uris */\n activeServer: ServerObject | null,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** Flattened environment variables used to resolve server URL templates like `{protocol}` */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the token request; the desktop app passes an IPC-backed fetch (see {@link authorizeServers}). */\n customFetch?: CustomFetch,\n /**\n * Optional redirect capture for interactive flows (authorization code and implicit).\n * When provided, the system browser plus a host-owned redirect target replaces the\n * default popup-polling approach. Required for the Electron desktop app.\n */\n captureCallback?: CaptureOAuth2Callback,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n try {\n if (!flow) {\n return [new Error('Flow not found'), null]\n }\n\n const scopes = selectedScopes.join(' ')\n\n // Client Credentials or Password Flow\n if (type === 'clientCredentials' || type === 'password') {\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n // Generate a random state string with the length of 8 characters\n const state = (Math.random() + 1).toString(36).substring(2, 10)\n\n const authorizationUrl = makeUrlAbsolute(\n flows[type]!['x-scalar-secret-auth-url'] ?? flows[type]!.authorizationUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n\n const url = new URL(authorizationUrl)\n\n /** Special PKCE state */\n let pkce: PKCEState | null = null\n\n // Params unique to the flows\n if (type === 'implicit') {\n url.searchParams.set('response_type', 'token')\n } else if (type === 'authorizationCode') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n url.searchParams.set('response_type', 'code')\n\n // PKCE\n if (typedFlow['x-usePkce'] !== 'no') {\n const codeVerifier = generateCodeVerifier()\n const codeChallenge = await generateCodeChallenge(codeVerifier, typedFlow['x-usePkce'])\n\n // Set state for later verification\n pkce = {\n codeVerifier,\n codeChallenge,\n codeChallengeMethod: typedFlow['x-usePkce'] === 'SHA-256' ? 'S256' : 'plain',\n }\n\n // Set the code challenge and method on the url\n url.searchParams.set('code_challenge', codeChallenge)\n url.searchParams.set('code_challenge_method', pkce.codeChallengeMethod)\n }\n }\n\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n // The capture path appends its own `redirect_uri` (it owns the target, for\n // example an ephemeral loopback port), so we only set it here for the popup path.\n if (!captureCallback) {\n // Handle relative redirect uris\n if (typedFlow['x-scalar-secret-redirect-uri'].startsWith('/')) {\n const baseUrl =\n getServerUrl(activeServer, environmentVariables) || window.location.origin + window.location.pathname\n const redirectUri = new URL(typedFlow['x-scalar-secret-redirect-uri'], baseUrl).toString()\n\n url.searchParams.set('redirect_uri', redirectUri)\n } else {\n url.searchParams.set('redirect_uri', typedFlow['x-scalar-secret-redirect-uri'])\n }\n }\n\n if (flow['x-scalar-security-query']) {\n Object.keys(flow['x-scalar-security-query']).forEach((key: string): void => {\n const value = flow['x-scalar-security-query']?.[key]\n if (!value) {\n return\n }\n url.searchParams.set(key, value)\n })\n }\n\n // Common to all flows\n url.searchParams.set('client_id', flow['x-scalar-secret-client-id'])\n url.searchParams.set('state', state)\n if (scopes) {\n url.searchParams.set('scope', scopes)\n }\n\n // Capture path: open the system browser and let the host environment catch\n // the redirect (used by the desktop app, where popup polling cannot work).\n if (captureCallback) {\n const [captureError, capture] = await captureCallback({ authorizationUrl: url.toString() })\n\n if (captureError || !capture) {\n return [captureError ?? new Error('Failed to capture the OAuth2 redirect'), null]\n }\n\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => capture.callbackUrl, flow['x-tokenName'] || 'access_token')\n\n if (error) {\n return [new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null]\n }\n\n // Implicit Flow\n if (accessToken) {\n if ((accessTokenParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return [null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }]\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n if ((codeParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n // The token request must echo the exact redirect_uri used in the authorization request.\n redirectUri: capture.redirectUri,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n return [new Error('No authorization code or access token was returned'), null]\n }\n\n const windowFeatures = 'left=100,top=100,width=800,height=600'\n const authWindow = window.open(url, 'openAuth2Window', windowFeatures)\n\n // Open up a window and poll until closed or we have the data we want\n if (authWindow) {\n // We need to return a promise here due to the setInterval\n return new Promise<ErrorResponse<OAuth2Tokens>>((resolve) => {\n const checkWindowClosed = setInterval(() => {\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => authWindow.location.href, flow['x-tokenName'] || 'access_token')\n\n // The window has closed OR we have what we are looking for so we stop polling\n if (authWindow.closed || accessToken || code || error) {\n clearInterval(checkWindowClosed)\n authWindow.close()\n\n if (error) {\n resolve([new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null])\n return\n }\n\n // Implicit Flow\n if (accessToken) {\n const _state = accessTokenParams?.get('state') ?? null\n\n if (_state === state) {\n resolve([null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }])\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n const _state = codeParams?.get('state') ?? null\n\n if (_state === state) {\n void authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n .then(resolve)\n .catch((error: unknown) => {\n resolve([\n error instanceof Error ? error : new Error('Failed to get an access token', { cause: error }),\n null,\n ])\n })\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // User closed window without authorizing\n resolve([new Error('Window was closed without granting authorization'), null])\n }\n }, 200)\n })\n }\n return [new Error('Failed to open auth window'), null]\n } catch (error) {\n return [error instanceof Error ? error : new Error('Failed to authorize oauth2 flow', { cause: error }), null]\n }\n}\n\n/**\n * Makes the BE authorization call to grab the token server to server\n * Used for clientCredentials and authorizationCode\n */\nconst authorizeServers = async (\n flows: NonImplicitFlows,\n type: keyof NonImplicitFlows,\n scopes: string,\n {\n code,\n pkce,\n proxyUrl,\n customFetch = fetch,\n redirectUri,\n }: {\n code?: string\n pkce?: PKCEState | null\n proxyUrl?: string\n customFetch?: CustomFetch\n /** Overrides the stored redirect_uri (the capture path owns the real target). */\n redirectUri?: string\n } = {},\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const formData = new URLSearchParams()\n\n // Only client credentials and password flows support scopes in the token request\n if (scopes && (type === 'clientCredentials' || type === 'password')) {\n formData.set('scope', scopes)\n }\n\n /** Where to add the credentials */\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n /**\n * PKCE and client authentication are independent: a confidential client may use both.\n * We send the client_secret whenever one is set, regardless of PKCE (see RFC 9700 Section 2.1.1).\n */\n const hasClientSecret = Boolean(flow['x-scalar-secret-client-secret'])\n /**\n * Public authorization-code clients still need client_id in the token body.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', flow['x-scalar-secret-client-id'])\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', flow['x-scalar-secret-client-secret'])\n }\n if (redirectUri) {\n formData.set('redirect_uri', redirectUri)\n } else if ('x-scalar-secret-redirect-uri' in flow && flow['x-scalar-secret-redirect-uri']) {\n formData.set('redirect_uri', flow['x-scalar-secret-redirect-uri'])\n }\n\n // Authorization Code\n if (code) {\n formData.set('code', code)\n formData.set('grant_type', 'authorization_code')\n\n // PKCE\n if (pkce) {\n formData.set('code_verifier', pkce.codeVerifier)\n }\n }\n // Password\n else if (type === 'password') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n formData.set('grant_type', 'password')\n formData.set('username', typedFlow['x-scalar-secret-username'])\n formData.set('password', typedFlow['x-scalar-secret-password'])\n }\n // Client Credentials\n else {\n formData.set('grant_type', 'client_credentials')\n }\n\n // Additional request body parameters\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n // Add client id + secret to headers for confidential clients.\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${flow['x-scalar-secret-client-id']}:${flow['x-scalar-secret-client-secret']}`)}`\n }\n\n // Check if we should use the proxy\n const tokenUrl = makeUrlAbsolute(\n flow['x-scalar-secret-token-url'] ?? flow.tokenUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n const url = shouldUseProxy(proxyUrl, tokenUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', tokenUrl]]).toString()}`\n : tokenUrl\n\n // Make the call\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n // Use custom token name if specified, otherwise default to access_token\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const refreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Failed to get an access token'), null]\n }\n\n return [null, { accessToken, ...(typeof refreshToken === 'string' ? { refreshToken } : {}) }]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to get an access token. Please check your credentials.', { cause: error }),\n null,\n ]\n }\n}\n\n/**\n * Exchange a refresh token for a new access token using the `grant_type=refresh_token` flow.\n *\n * Uses the stored refresh token, client credentials, and the token URL (or refreshUrl when available)\n * to request fresh tokens from the authorization server per RFC 6749 Section 6.\n */\nexport const refreshOauth2Token = async (\n flows: OAuthFlowsObjectSecret,\n type: RefreshableFlows,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** We use the active server to set a base for relative URLs */\n activeServer: ServerObject | null,\n /** Flattened environment variables used to resolve server URL templates */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the refresh request; the desktop app passes an IPC-backed fetch so it leaves the renderer's network stack. */\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const refreshToken = flow['x-scalar-secret-refresh-token']\n if (!refreshToken) {\n return [new Error('No refresh token available'), null]\n }\n\n const formData = new URLSearchParams()\n formData.set('grant_type', 'refresh_token')\n formData.set('refresh_token', refreshToken)\n\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n /** A confidential client keeps using its secret on refresh, even when PKCE is enabled. */\n const hasClientSecret = Boolean(flow['x-scalar-secret-client-secret'])\n /**\n * Public authorization-code clients still need client_id in the refresh body per RFC 6749 Section 6.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', flow['x-scalar-secret-client-id'])\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', flow['x-scalar-secret-client-secret'])\n }\n\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${flow['x-scalar-secret-client-id']}:${flow['x-scalar-secret-client-secret']}`)}`\n }\n\n const refreshUrl = flow.refreshUrl || flow['x-scalar-secret-token-url'] || flow.tokenUrl\n const absoluteRefreshUrl = makeUrlAbsolute(refreshUrl, getActiveServerBase(activeServer, environmentVariables))\n const url = shouldUseProxy(proxyUrl, absoluteRefreshUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', absoluteRefreshUrl]]).toString()}`\n : absoluteRefreshUrl\n\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const newRefreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Token refresh failed'), null]\n }\n\n return [\n null,\n {\n accessToken,\n ...(typeof newRefreshToken === 'string' ? { refreshToken: newRefreshToken } : { refreshToken }),\n },\n ]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to refresh the access token. Please re-authorize.', { cause: error }),\n null,\n ]\n }\n}\n"],"mappings":";;;;;;;;;;;;AA4DA,IAAa,gBACX,cACA,uBAA+C,CAAC,MAEhD,oBACE,qBAAqB,cAAc,OAAO,IAAI,mBAAmB,YAAY,CAAC,GAC9E,oBACF;;;;;;;AAQF,IAAa,uBACX,cACA,uBAA+C,CAAC,MAC3B;CACrB,MAAM,YAAY,aAAa,cAAc,oBAAoB;CACjE,IAAI,CAAC,WACH,OAAO,CAAC;CAGV,IAAI,eAAe,SAAS,GAC1B,OAAO,OAAO,WAAW,cAAc,CAAC,IAAI,EAAE,UAAU,UAAU;CAGpE,OAAO,EAAE,SAAS,UAAU;AAC9B;;;;;;AAOA,IAAM,6BAAqC;CAEzC,MAAM,yBAAS,IAAI,WAAW,EAAE;CAChC,OAAO,gBAAgB,MAAM;CAG7B,OAAO,eAAe,QAAQ,IAAI;AACpC;;;;AAKA,IAAM,wBAAwB,OAAO,UAAkB,aAAmD;CACxG,IAAI,aAAa,SACf,OAAO;CAIT,IAAI,OAAO,QAAQ,QAAQ,WAAW,YAAY;EAChD,QAAQ,KAAK,wFAAwF;EACrG,OAAO;CACT;CAIA,MAAM,OAAO,IADO,YACP,CAAA,CAAQ,OAAO,QAAQ;CACpC,MAA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a,qBAAqB,aAAa,SAAS,sBAAsB,GAAG,IAAI;EAGzG,OAAO,CACL,MACA;GACE;GACA,GAAI,OAAO,oBAAoB,WAAW,EAAE,cAAc,gBAAgB,IAAI,EAAE,aAAa;EAC/F,CACF;CACF,SAAS,OAAO;EACd,OAAO,CACL,iBAAiB,QACb,QACA,IAAI,MAAM,4DAA4D,EAAE,OAAO,MAAM,CAAC,GAC1F,IACF;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"openid-discovery-to-flows.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/openid-discovery-to-flows.ts"],"sourcesContent":["import { OpenIDConnectSchema, type SecretsOpenIdConnect } from '@scalar/workspace-store/entities/auth'\nimport { coerceValue } from '@scalar/workspace-store/schemas/typebox-coerce'\nimport type { OAuthFlowsObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\nimport type { OpenIDConnectDiscovery } from './fetch-openid-connect-discovery'\n\n/** Takes in an open ID Connect discovery response and converts it into an oauth flow to be used for authorization */\nexport const openIDDiscoveryToFlows = (discovery: OpenIDConnectDiscovery): SecretsOpenIdConnect => {\n const scopes = Object.fromEntries((discovery.scopes_supported ?? []).map((scope) => [scope, '']))\n const grantTypes = new Set(discovery.grant_types_supported ?? ['authorization_code', 'implicit'])\n const authorizationUrl = discovery.authorization_endpoint\n const tokenUrl = discovery.token_endpoint\n\n const usePkce = discovery.code_challenge_methods_supported?.includes('S256')\n ? 'SHA-256'\n : discovery.code_challenge_methods_supported?.includes('plain')\n ? 'plain'\n : 'no'\n\n const flows: OAuthFlowsObject = {}\n\n // Implicit\n if (grantTypes.has('implicit') && authorizationUrl) {\n flows.implicit = {\n authorizationUrl,\n refreshUrl: authorizationUrl,\n scopes,\n }\n }\n\n // Password\n if (grantTypes.has('password') && tokenUrl) {\n flows.password = {\n tokenUrl,\n refreshUrl: tokenUrl,\n scopes,\n }\n }\n\n // Client Credentials\n if (grantTypes.has('client_credentials') && tokenUrl) {\n flows.clientCredentials = {\n tokenUrl,\n refreshUrl: tokenUrl,\n scopes,\n }\n }\n\n // Authorization Code\n if (grantTypes.has('authorization_code') && authorizationUrl && tokenUrl) {\n flows.authorizationCode = {\n authorizationUrl,\n tokenUrl,\n refreshUrl: tokenUrl,\n 'x-usePkce': usePkce,\n scopes,\n }\n }\n\n return coerceValue(OpenIDConnectSchema, flows)\n}\n"],"mappings":";;;;AAOA,IAAa,0BAA0B,cAA4D;CACjG,MAAM,SAAS,OAAO,aAAa,UAAU,oBAAoB,EAAE,EAAE,KAAK,UAAU,CAAC,OAAO,GAAG,CAAC,CAAC;CACjG,MAAM,aAAa,IAAI,IAAI,UAAU,yBAAyB,CAAC,sBAAsB,WAAW,CAAC;CACjG,MAAM,mBAAmB,UAAU;CACnC,MAAM,WAAW,UAAU;CAE3B,MAAM,UAAU,UAAU,kCAAkC,SAAS,OAAO,GACxE,YACA,UAAU,kCAAkC,SAAS,QAAQ,GAC3D,UACA;CAEN,MAAM,QAA0B,EAAE;AAGlC,KAAI,WAAW,IAAI,WAAW,IAAI,iBAChC,OAAM,WAAW;EACf;EACA,YAAY;EACZ;EACD;AAIH,KAAI,WAAW,IAAI,WAAW,IAAI,SAChC,OAAM,WAAW;EACf;EACA,YAAY;EACZ;EACD;AAIH,KAAI,WAAW,IAAI,qBAAqB,IAAI,SAC1C,OAAM,oBAAoB;EACxB;EACA,YAAY;EACZ;EACD;AAIH,KAAI,WAAW,IAAI,qBAAqB,IAAI,oBAAoB,SAC9D,OAAM,oBAAoB;EACxB;EACA;EACA,YAAY;EACZ,aAAa;EACb;EACD;AAGH,QAAO,YAAY,qBAAqB,MAAM"}
1
+ {"version":3,"file":"openid-discovery-to-flows.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/openid-discovery-to-flows.ts"],"sourcesContent":["import { OpenIDConnectSchema, type SecretsOpenIdConnect } from '@scalar/workspace-store/entities/auth'\nimport { coerceValue } from '@scalar/workspace-store/schemas/typebox-coerce'\nimport type { OAuthFlowsObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\nimport type { OpenIDConnectDiscovery } from './fetch-openid-connect-discovery'\n\n/** Takes in an open ID Connect discovery response and converts it into an oauth flow to be used for authorization */\nexport const openIDDiscoveryToFlows = (discovery: OpenIDConnectDiscovery): SecretsOpenIdConnect => {\n const scopes = Object.fromEntries((discovery.scopes_supported ?? []).map((scope) => [scope, '']))\n const grantTypes = new Set(discovery.grant_types_supported ?? ['authorization_code', 'implicit'])\n const authorizationUrl = discovery.authorization_endpoint\n const tokenUrl = discovery.token_endpoint\n\n const usePkce = discovery.code_challenge_methods_supported?.includes('S256')\n ? 'SHA-256'\n : discovery.code_challenge_methods_supported?.includes('plain')\n ? 'plain'\n : 'no'\n\n const flows: OAuthFlowsObject = {}\n\n // Implicit\n if (grantTypes.has('implicit') && authorizationUrl) {\n flows.implicit = {\n authorizationUrl,\n refreshUrl: authorizationUrl,\n scopes,\n }\n }\n\n // Password\n if (grantTypes.has('password') && tokenUrl) {\n flows.password = {\n tokenUrl,\n refreshUrl: tokenUrl,\n scopes,\n }\n }\n\n // Client Credentials\n if (grantTypes.has('client_credentials') && tokenUrl) {\n flows.clientCredentials = {\n tokenUrl,\n refreshUrl: tokenUrl,\n scopes,\n }\n }\n\n // Authorization Code\n if (grantTypes.has('authorization_code') && authorizationUrl && tokenUrl) {\n flows.authorizationCode = {\n authorizationUrl,\n tokenUrl,\n refreshUrl: tokenUrl,\n 'x-usePkce': usePkce,\n scopes,\n }\n }\n\n return coerceValue(OpenIDConnectSchema, flows)\n}\n"],"mappings":";;;;AAOA,IAAa,0BAA0B,cAA4D;CACjG,MAAM,SAAS,OAAO,aAAa,UAAU,oBAAoB,CAAC,EAAA,CAAG,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;CAChG,MAAM,aAAa,IAAI,IAAI,UAAU,yBAAyB,CAAC,sBAAsB,UAAU,CAAC;CAChG,MAAM,mBAAmB,UAAU;CACnC,MAAM,WAAW,UAAU;CAE3B,MAAM,UAAU,UAAU,kCAAkC,SAAS,MAAM,IACvE,YACA,UAAU,kCAAkC,SAAS,OAAO,IAC1D,UACA;CAEN,MAAM,QAA0B,CAAC;CAGjC,IAAI,WAAW,IAAI,UAAU,KAAK,kBAChC,MAAM,WAAW;EACf;EACA,YAAY;EACZ;CACF;CAIF,IAAI,WAAW,IAAI,UAAU,KAAK,UAChC,MAAM,WAAW;EACf;EACA,YAAY;EACZ;CACF;CAIF,IAAI,WAAW,IAAI,oBAAoB,KAAK,UAC1C,MAAM,oBAAoB;EACxB;EACA,YAAY;EACZ;CACF;CAIF,IAAI,WAAW,IAAI,oBAAoB,KAAK,oBAAoB,UAC9D,MAAM,oBAAoB;EACxB;EACA;EACA,YAAY;EACZ,aAAa;EACb;CACF;CAGF,OAAO,YAAY,qBAAqB,KAAK;AAC/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-default-oauth2-redirect-url.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/resolve-default-oauth2-redirect-url.ts"],"sourcesContent":["import type { ApiClientConfiguration } from '@scalar/types/api-reference'\n\n/**\n * Resolve the default OAuth2 redirect URI.\n *\n * Priority:\n * 1. Explicit oauth2RedirectUri config override.\n * 2. Empty string in non-browser and file:// contexts.\n * 3. Browser origin + pathname fallback.\n */\nexport const resolveDefaultOAuth2RedirectUri = (config: Pick<ApiClientConfiguration, 'oauth2RedirectUri'>): string => {\n if (config.oauth2RedirectUri) {\n return config.oauth2RedirectUri\n }\n\n if (typeof window === 'undefined' || window.location.protocol === 'file:') {\n return ''\n }\n\n return window.location.origin + window.location.pathname\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,mCAAmC,WAAsE;AACpH,KAAI,OAAO,kBACT,QAAO,OAAO;AAGhB,KAAI,OAAO,WAAW,eAAe,OAAO,SAAS,aAAa,QAChE,QAAO;AAGT,QAAO,OAAO,SAAS,SAAS,OAAO,SAAS"}
1
+ {"version":3,"file":"resolve-default-oauth2-redirect-url.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/resolve-default-oauth2-redirect-url.ts"],"sourcesContent":["import type { ApiClientConfiguration } from '@scalar/types/api-reference'\n\n/**\n * Resolve the default OAuth2 redirect URI.\n *\n * Priority:\n * 1. Explicit oauth2RedirectUri config override.\n * 2. Empty string in non-browser and file:// contexts.\n * 3. Browser origin + pathname fallback.\n */\nexport const resolveDefaultOAuth2RedirectUri = (config: Pick<ApiClientConfiguration, 'oauth2RedirectUri'>): string => {\n if (config.oauth2RedirectUri) {\n return config.oauth2RedirectUri\n }\n\n if (typeof window === 'undefined' || window.location.protocol === 'file:') {\n return ''\n }\n\n return window.location.origin + window.location.pathname\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,mCAAmC,WAAsE;CACpH,IAAI,OAAO,mBACT,OAAO,OAAO;CAGhB,IAAI,OAAO,WAAW,eAAe,OAAO,SAAS,aAAa,SAChE,OAAO;CAGT,OAAO,OAAO,SAAS,SAAS,OAAO,SAAS;AAClD"}
@@ -0,0 +1,42 @@
1
+ import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error';
2
+ import type { WorkspaceEventBus } from '@scalar/workspace-store/events';
3
+ import { type OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example';
4
+ import type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments';
5
+ import type { ServerObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document';
6
+ import type { OAuth2Options } from '../../../../v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.js';
7
+ import { type OAuth2Tokens } from '../../../../v2/blocks/scalar-auth-selector-block/helpers/oauth.js';
8
+ /**
9
+ * Persists OAuth2 tokens split across the two schemes that care about them:
10
+ *
11
+ * - The **access token** lands on the consuming HTTP bearer scheme, so it is sent as
12
+ * `Authorization: Bearer <token>` without the bearer scheme losing focus.
13
+ * - The **refresh token** stays on the oauth2 scheme, which is the only place that knows
14
+ * how to refresh (token URL, flow, client credentials).
15
+ */
16
+ export declare const storeOAuth2Tokens: (eventBus: WorkspaceEventBus, params: {
17
+ bearerSchemeName: string;
18
+ oauth2Name: string;
19
+ flowType: keyof OAuthFlowsObjectSecret;
20
+ tokens: OAuth2Tokens;
21
+ }) => void;
22
+ /**
23
+ * Runs the OAuth2 authorization flow and stores the resulting tokens on the bearer scheme
24
+ * (access token) and the oauth2 scheme (refresh token).
25
+ *
26
+ * Used by the bearer scheme's "Authorize via OAuth2" shortcut: it defaults the redirect URI
27
+ * (`authorizeOauth2` reads it straight off the flow), kicks off the flow, then routes the
28
+ * tokens through {@link storeOAuth2Tokens}.
29
+ */
30
+ export declare const runOAuth2Authorize: (params: {
31
+ eventBus: WorkspaceEventBus;
32
+ bearerSchemeName: string;
33
+ oauth2Name: string;
34
+ flows: OAuthFlowsObjectSecret;
35
+ flowType: keyof OAuthFlowsObjectSecret;
36
+ scopes: string[];
37
+ server: ServerObject | null;
38
+ proxyUrl: string;
39
+ environment: XScalarEnvironment;
40
+ options?: OAuth2Options;
41
+ }) => Promise<ErrorResponse<OAuth2Tokens>>;
42
+ //# sourceMappingURL=run-oauth2-authorize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-oauth2-authorize.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAC3E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAA;AACvE,OAAO,EAAE,KAAK,sBAAsB,EAA2B,MAAM,yCAAyC,CAAA;AAC9G,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2EAA2E,CAAA;AACnH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8DAA8D,CAAA;AAEhG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8DAA8D,CAAA;AACjG,OAAO,EAAE,KAAK,YAAY,EAAmB,MAAM,sDAAsD,CAAA;AAGzG;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAC5B,UAAU,iBAAiB,EAC3B,QAAQ;IACN,gBAAgB,EAAE,MAAM,CAAA;IACxB,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,sBAAsB,CAAA;IACtC,MAAM,EAAE,YAAY,CAAA;CACrB,KACA,IAiBF,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAAU,QAAQ;IAC/C,QAAQ,EAAE,iBAAiB,CAAA;IAC3B,gBAAgB,EAAE,MAAM,CAAA;IACxB,UAAU,EAAE,MAAM,CAAA;IAClB,KAAK,EAAE,sBAAsB,CAAA;IAC7B,QAAQ,EAAE,MAAM,sBAAsB,CAAA;IACtC,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,MAAM,EAAE,YAAY,GAAG,IAAI,CAAA;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB,WAAW,EAAE,kBAAkB,CAAA;IAC/B,OAAO,CAAC,EAAE,aAAa,CAAA;CACxB,KAAG,OAAO,CAAC,aAAa,CAAC,YAAY,CAAC,CAwCtC,CAAA"}
@@ -0,0 +1,60 @@
1
+ import { authorizeOauth2 } from "./oauth.js";
2
+ import { resolveDefaultOAuth2RedirectUri } from "./resolve-default-oauth2-redirect-url.js";
3
+ import { getEnvironmentVariables } from "@scalar/workspace-store/request-example";
4
+ //#region src/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.ts
5
+ /**
6
+ * Persists OAuth2 tokens split across the two schemes that care about them:
7
+ *
8
+ * - The **access token** lands on the consuming HTTP bearer scheme, so it is sent as
9
+ * `Authorization: Bearer <token>` without the bearer scheme losing focus.
10
+ * - The **refresh token** stays on the oauth2 scheme, which is the only place that knows
11
+ * how to refresh (token URL, flow, client credentials).
12
+ */
13
+ var storeOAuth2Tokens = (eventBus, params) => {
14
+ const { bearerSchemeName, oauth2Name, flowType, tokens } = params;
15
+ eventBus.emit("auth:update:security-scheme-secrets", {
16
+ payload: {
17
+ type: "http",
18
+ "x-scalar-secret-token": tokens.accessToken
19
+ },
20
+ name: bearerSchemeName
21
+ });
22
+ if (tokens.refreshToken) eventBus.emit("auth:update:security-scheme-secrets", {
23
+ payload: {
24
+ type: "oauth2",
25
+ [flowType]: { "x-scalar-secret-refresh-token": tokens.refreshToken }
26
+ },
27
+ name: oauth2Name
28
+ });
29
+ };
30
+ /**
31
+ * Runs the OAuth2 authorization flow and stores the resulting tokens on the bearer scheme
32
+ * (access token) and the oauth2 scheme (refresh token).
33
+ *
34
+ * Used by the bearer scheme's "Authorize via OAuth2" shortcut: it defaults the redirect URI
35
+ * (`authorizeOauth2` reads it straight off the flow), kicks off the flow, then routes the
36
+ * tokens through {@link storeOAuth2Tokens}.
37
+ */
38
+ var runOAuth2Authorize = async (params) => {
39
+ const { eventBus, bearerSchemeName, oauth2Name, flows, flowType, scopes, server, proxyUrl, environment, options } = params;
40
+ const flow = flows[flowType];
41
+ const result = await authorizeOauth2(flow && (flowType === "authorizationCode" || flowType === "implicit") ? {
42
+ ...flows,
43
+ [flowType]: {
44
+ ...flow,
45
+ "x-scalar-secret-redirect-uri": flow["x-scalar-secret-redirect-uri"] || resolveDefaultOAuth2RedirectUri(options ?? {}) || ""
46
+ }
47
+ } : flows, flowType, scopes, server, proxyUrl, getEnvironmentVariables(environment), options?.customFetch, options?.captureOAuth2Callback);
48
+ const tokens = result[1];
49
+ if (tokens?.accessToken) storeOAuth2Tokens(eventBus, {
50
+ bearerSchemeName,
51
+ oauth2Name,
52
+ flowType,
53
+ tokens
54
+ });
55
+ return result;
56
+ };
57
+ //#endregion
58
+ export { runOAuth2Authorize, storeOAuth2Tokens };
59
+
60
+ //# sourceMappingURL=run-oauth2-authorize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-oauth2-authorize.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport type { WorkspaceEventBus } from '@scalar/workspace-store/events'\nimport { type OAuthFlowsObjectSecret, getEnvironmentVariables } from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport type { ServerObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\nimport type { OAuth2Options } from '@/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue'\nimport { type OAuth2Tokens, authorizeOauth2 } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth'\nimport { resolveDefaultOAuth2RedirectUri } from '@/v2/blocks/scalar-auth-selector-block/helpers/resolve-default-oauth2-redirect-url'\n\n/**\n * Persists OAuth2 tokens split across the two schemes that care about them:\n *\n * - The **access token** lands on the consuming HTTP bearer scheme, so it is sent as\n * `Authorization: Bearer <token>` without the bearer scheme losing focus.\n * - The **refresh token** stays on the oauth2 scheme, which is the only place that knows\n * how to refresh (token URL, flow, client credentials).\n */\nexport const storeOAuth2Tokens = (\n eventBus: WorkspaceEventBus,\n params: {\n bearerSchemeName: string\n oauth2Name: string\n flowType: keyof OAuthFlowsObjectSecret\n tokens: OAuth2Tokens\n },\n): void => {\n const { bearerSchemeName, oauth2Name, flowType, tokens } = params\n\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'http', 'x-scalar-secret-token': tokens.accessToken },\n name: bearerSchemeName,\n })\n\n if (tokens.refreshToken) {\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: {\n type: 'oauth2',\n [flowType]: { 'x-scalar-secret-refresh-token': tokens.refreshToken },\n },\n name: oauth2Name,\n })\n }\n}\n\n/**\n * Runs the OAuth2 authorization flow and stores the resulting tokens on the bearer scheme\n * (access token) and the oauth2 scheme (refresh token).\n *\n * Used by the bearer scheme's \"Authorize via OAuth2\" shortcut: it defaults the redirect URI\n * (`authorizeOauth2` reads it straight off the flow), kicks off the flow, then routes the\n * tokens through {@link storeOAuth2Tokens}.\n */\nexport const runOAuth2Authorize = async (params: {\n eventBus: WorkspaceEventBus\n bearerSchemeName: string\n oauth2Name: string\n flows: OAuthFlowsObjectSecret\n flowType: keyof OAuthFlowsObjectSecret\n scopes: string[]\n server: ServerObject | null\n proxyUrl: string\n environment: XScalarEnvironment\n options?: OAuth2Options\n}): Promise<ErrorResponse<OAuth2Tokens>> => {\n const { eventBus, bearerSchemeName, oauth2Name, flows, flowType, scopes, server, proxyUrl, environment, options } =\n params\n\n const flow = flows[flowType]\n\n // authorizeOauth2 reads the redirect URI directly off interactive flows, so default it\n // when unset — a scheme merged in from Scalar config can then authorize without first\n // opening the configuration form.\n const preparedFlows =\n flow && (flowType === 'authorizationCode' || flowType === 'implicit')\n ? {\n ...flows,\n [flowType]: {\n ...flow,\n 'x-scalar-secret-redirect-uri':\n (flow as unknown as Record<string, string | undefined>)['x-scalar-secret-redirect-uri'] ||\n resolveDefaultOAuth2RedirectUri(options ?? {}) ||\n '',\n },\n }\n : flows\n\n const result = await authorizeOauth2(\n preparedFlows,\n flowType,\n scopes,\n server,\n proxyUrl,\n getEnvironmentVariables(environment),\n options?.customFetch,\n options?.captureOAuth2Callback,\n )\n const tokens = result[1]\n\n if (tokens?.accessToken) {\n storeOAuth2Tokens(eventBus, { bearerSchemeName, oauth2Name, flowType, tokens })\n }\n\n return result\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,IAAa,qBACX,UACA,WAMS;CACT,MAAM,EAAE,kBAAkB,YAAY,UAAU,WAAW;CAE3D,SAAS,KAAK,uCAAuC;EACnD,SAAS;GAAE,MAAM;GAAQ,yBAAyB,OAAO;EAAY;EACrE,MAAM;CACR,CAAC;CAED,IAAI,OAAO,cACT,SAAS,KAAK,uCAAuC;EACnD,SAAS;GACP,MAAM;IACL,WAAW,EAAE,iCAAiC,OAAO,aAAa;EACrE;EACA,MAAM;CACR,CAAC;AAEL;;;;;;;;;AAUA,IAAa,qBAAqB,OAAO,WAWG;CAC1C,MAAM,EAAE,UAAU,kBAAkB,YAAY,OAAO,UAAU,QAAQ,QAAQ,UAAU,aAAa,YACtG;CAEF,MAAM,OAAO,MAAM;CAmBnB,MAAM,SAAS,MAAM,gBAbnB,SAAS,aAAa,uBAAuB,aAAa,cACtD;EACE,GAAG;GACF,WAAW;GACV,GAAG;GACH,gCACG,KAAuD,mCACxD,gCAAgC,WAAW,CAAC,CAAC,KAC7C;EACJ;CACF,IACA,OAIJ,UACA,QACA,QACA,UACA,wBAAwB,WAAW,GACnC,SAAS,aACT,SAAS,qBACX;CACA,MAAM,SAAS,OAAO;CAEtB,IAAI,QAAQ,aACV,kBAAkB,UAAU;EAAE;EAAkB;EAAY;EAAU;CAAO,CAAC;CAGhF,OAAO;AACT"}
@@ -1,3 +1,4 @@
1
+ import type { MergedSecuritySchemes, OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example';
1
2
  import type { ComponentsObject, OpenApiDocument, SecurityRequirementObject, SecuritySchemeObject } from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document';
2
3
  /** A single security scheme option used in the auth dropdown */
3
4
  export type SecuritySchemeOption = {
@@ -34,12 +35,27 @@ export declare const formatComplexScheme: (scheme: NonNullable<OpenApiDocument["
34
35
  value: Partial<Record<string, string[]>>;
35
36
  isDeletable: boolean;
36
37
  };
38
+ /**
39
+ * Finds the oauth2 scheme best suited to power a bearer scheme's "Authorize via OAuth2" shortcut:
40
+ * the first scheme with an interactive grant (authorization code / implicit), the kind that sends
41
+ * a user to an IdP login. Prefers the authorization-code grant (which can refresh) over one
42
+ * offering only implicit, so the more capable flow wins even when it is declared later.
43
+ *
44
+ * This only surfaces a convenience shortcut on the bearer form — it never hides the oauth2 scheme,
45
+ * which stays independently selectable in the auth dropdown.
46
+ */
47
+ export declare const getOauth2AcquisitionTarget: (securitySchemes: NonNullable<ComponentsObject["securitySchemes"]> | MergedSecuritySchemes) => {
48
+ name: string;
49
+ flows: OAuthFlowsObjectSecret;
50
+ flowType: "authorizationCode" | "implicit";
51
+ scopes: string[];
52
+ } | null;
37
53
  /**
38
54
  * Generates the options for the security scheme combobox
39
55
  *
40
56
  * Contains either a flat list, or different groups of required, available, and add new
41
57
  */
42
- export declare const getSecuritySchemeOptions: (security: NonNullable<OpenApiDocument["security"]>, securitySchemes: NonNullable<ComponentsObject["securitySchemes"]>,
58
+ export declare const getSecuritySchemeOptions: (security: NonNullable<OpenApiDocument["security"]>, securitySchemes: NonNullable<ComponentsObject["securitySchemes"]> | MergedSecuritySchemes,
43
59
  /** We need to add the selected schemes if they do not already exist in the calculated options */
44
60
  selectedSchemes: SecurityRequirementObject[],
45
61
  /** Allows adding authentication which is not in the document */
@@ -1 +1 @@
1
- {"version":3,"file":"security-scheme.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,yBAAyB,EACzB,oBAAoB,EACrB,MAAM,8DAA8D,CAAA;AAIrE,gEAAgE;AAChE,MAAM,MAAM,oBAAoB,GAAG;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,yBAAyB,CAAA;IAChC,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,OAAO,CAAC,EAAE,oBAAoB,CAAA;CAC/B,CAAA;AAED,mEAAmE;AACnE,MAAM,MAAM,mBAAmB,GAAG;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,oBAAoB,EAAE,CAAA;CAChC,CAAA;AAKD;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GAAI,iBAAiB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,yBAAyB,CAAA;CAAE;;;;;CAK9F,CAAA;AAEF,uCAAuC;AACvC,eAAO,MAAM,mBAAmB,GAAI,QAAQ,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;;;;;CAIxF,CAAA;AA6BJ;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,GACnC,UAAU,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,EAClD,iBAAiB,WAAW,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC;AACjE,iGAAiG;AACjG,iBAAiB,yBAAyB,EAAE;AAC5C,gEAAgE;AAChE,uBAAqB,KACpB,oBAAoB,EAAE,GAAG,mBAAmB,EAkF9C,CAAA"}
1
+ {"version":3,"file":"security-scheme.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAA;AAC5G,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,yBAAyB,EACzB,oBAAoB,EACrB,MAAM,8DAA8D,CAAA;AAIrE,gEAAgE;AAChE,MAAM,MAAM,oBAAoB,GAAG;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,yBAAyB,CAAA;IAChC,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,OAAO,CAAC,EAAE,oBAAoB,CAAA;CAC/B,CAAA;AAED,mEAAmE;AACnE,MAAM,MAAM,mBAAmB,GAAG;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,oBAAoB,EAAE,CAAA;CAChC,CAAA;AAKD;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GAAI,iBAAiB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,yBAAyB,CAAA;CAAE;;;;;CAK9F,CAAA;AAEF,uCAAuC;AACvC,eAAO,MAAM,mBAAmB,GAAI,QAAQ,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;;;;;CAIxF,CAAA;AA6BJ;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,GACrC,iBAAiB,WAAW,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,GAAG,qBAAqB,KACxF;IACD,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,sBAAsB,CAAA;IAC7B,QAAQ,EAAE,mBAAmB,GAAG,UAAU,CAAA;IAC1C,MAAM,EAAE,MAAM,EAAE,CAAA;CACjB,GAAG,IA8BH,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,GACnC,UAAU,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,EAClD,iBAAiB,WAAW,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC,GAAG,qBAAqB;AACzF,iGAAiG;AACjG,iBAAiB,yBAAyB,EAAE;AAC5C,gEAAgE;AAChE,uBAAqB,KACpB,oBAAoB,EAAE,GAAG,mBAAmB,EAkF9C,CAAA"}
@@ -36,6 +36,38 @@ var formatSecurityRequirement = (requirement, securitySchemes) => {
36
36
  }
37
37
  };
38
38
  /**
39
+ * Finds the oauth2 scheme best suited to power a bearer scheme's "Authorize via OAuth2" shortcut:
40
+ * the first scheme with an interactive grant (authorization code / implicit), the kind that sends
41
+ * a user to an IdP login. Prefers the authorization-code grant (which can refresh) over one
42
+ * offering only implicit, so the more capable flow wins even when it is declared later.
43
+ *
44
+ * This only surfaces a convenience shortcut on the bearer form — it never hides the oauth2 scheme,
45
+ * which stays independently selectable in the auth dropdown.
46
+ */
47
+ var getOauth2AcquisitionTarget = (securitySchemes) => {
48
+ let implicitFallback = null;
49
+ for (const [name, schemeRef] of Object.entries(securitySchemes)) {
50
+ const scheme = getResolvedRef(schemeRef);
51
+ if (scheme?.type !== "oauth2") continue;
52
+ const flows = scheme.flows;
53
+ if (!flows) continue;
54
+ const scopes = scheme["x-default-scopes"] ?? [];
55
+ if (flows.authorizationCode) return {
56
+ name,
57
+ flows,
58
+ flowType: "authorizationCode",
59
+ scopes
60
+ };
61
+ if (flows.implicit && !implicitFallback) implicitFallback = {
62
+ name,
63
+ flows,
64
+ flowType: "implicit",
65
+ scopes
66
+ };
67
+ }
68
+ return implicitFallback;
69
+ };
70
+ /**
39
71
  * Generates the options for the security scheme combobox
40
72
  *
41
73
  * Contains either a flat list, or different groups of required, available, and add new
@@ -104,6 +136,6 @@ var getSecuritySchemeOptions = (security, securitySchemes, selectedSchemes, canA
104
136
  return options;
105
137
  };
106
138
  //#endregion
107
- export { formatComplexScheme, formatScheme, getSecuritySchemeOptions };
139
+ export { formatComplexScheme, formatScheme, getOauth2AcquisitionTarget, getSecuritySchemeOptions };
108
140
 
109
141
  //# sourceMappingURL=security-scheme.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"security-scheme.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"sourcesContent":["import { generateHash } from '@scalar/helpers/string/generate-hash'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type {\n ComponentsObject,\n OpenApiDocument,\n SecurityRequirementObject,\n SecuritySchemeObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\nimport { authOptions } from '@/v2/blocks/scalar-auth-selector-block/helpers/auth-options'\n\n/** A single security scheme option used in the auth dropdown */\nexport type SecuritySchemeOption = {\n id: string\n label: string\n value: SecurityRequirementObject\n isDeletable?: boolean\n payload?: SecuritySchemeObject\n}\n\n/** A group of security scheme options used in the auth dropdown */\nexport type SecuritySchemeGroup = {\n label: string\n options: SecuritySchemeOption[]\n}\n\nconst requirementSignature = (requirement: SecurityRequirementObject): string =>\n JSON.stringify(Object.keys(requirement))\n\n/**\n * Format a scheme object into a display object\n *\n * We also add a hash to the id to ensure it is unique across\n * multiple requirements of the same scheme with different scopes\n */\nexport const formatScheme = ({ name, value }: { name: string; value: SecurityRequirementObject }) => ({\n id: generateHash(JSON.stringify(value)),\n label: name,\n value,\n isDeletable: true,\n})\n\n/** Formats complex security schemes */\nexport const formatComplexScheme = (scheme: NonNullable<OpenApiDocument['security']>[number]) =>\n formatScheme({\n name: Object.keys(scheme).join(' & '),\n value: scheme,\n })\n\n/**\n * Formats a security requirement into a SecuritySchemeOption.\n * Handles both simple (single key) and complex (multiple keys) auth schemes.\n */\nconst formatSecurityRequirement = (\n requirement: SecurityRequirementObject,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']>,\n): SecuritySchemeOption | undefined => {\n const keys = Object.keys(requirement)\n\n // Complex auth (multiple keys)\n if (keys.length > 1) {\n return formatComplexScheme(requirement)\n }\n\n // Simple auth (single key)\n if (keys[0]) {\n const scheme = getResolvedRef(securitySchemes[keys[0]])\n if (!scheme) {\n return undefined\n }\n return formatScheme({ name: keys[0], value: requirement })\n }\n\n return undefined\n}\n\n/**\n * Generates the options for the security scheme combobox\n *\n * Contains either a flat list, or different groups of required, available, and add new\n */\nexport const getSecuritySchemeOptions = (\n security: NonNullable<OpenApiDocument['security']>,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']>,\n /** We need to add the selected schemes if they do not already exist in the calculated options */\n selectedSchemes: SecurityRequirementObject[],\n /** Allows adding authentication which is not in the document */\n canAddNewAuth = false,\n): SecuritySchemeOption[] | SecuritySchemeGroup[] => {\n const selectedByRequirement = new Map(\n selectedSchemes.map((selectedScheme) => [requirementSignature(selectedScheme), selectedScheme]),\n )\n\n /**\n * Build required schemes formatted as options and track scheme names in a single pass.\n * We use names (not full IDs) because we want to exclude any scheme that is already\n * required, regardless of its specific scopes or hash.\n */\n const { requiredFormatted, requiredSchemeNames, existingIds } = security.reduce(\n (acc, requirement) => {\n // If a required requirement is selected with scopes, use that selected value to\n // keep a single option entry and avoid a phantom duplicate.\n const requirementValue = selectedByRequirement.get(requirementSignature(requirement)) ?? requirement\n const formatted = formatSecurityRequirement(requirementValue, securitySchemes)\n if (formatted) {\n acc.requiredFormatted.push(formatted)\n acc.existingIds.add(formatted.id)\n }\n for (const name of Object.keys(requirement)) {\n acc.requiredSchemeNames.add(name)\n }\n return acc\n },\n {\n requiredFormatted: [] as SecuritySchemeOption[],\n requiredSchemeNames: new Set<string>(),\n existingIds: new Set<string>(),\n },\n )\n\n // Build available schemes (excluding schemes that are in the required list)\n const availableFormatted: SecuritySchemeOption[] = []\n for (const [name, schemeRef] of Object.entries(securitySchemes)) {\n if (requiredSchemeNames.has(name)) {\n continue\n }\n\n const scheme = getResolvedRef(schemeRef)\n if (scheme) {\n const formatted = formatScheme({ name, value: { [name]: [] } })\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n /**\n * Add selected schemes to available if they do not already exist\n * This ensures that selected schemes with specific scopes are always available as options\n */\n for (const selectedScheme of selectedSchemes) {\n const formatted = formatSecurityRequirement(selectedScheme, securitySchemes)\n if (formatted && !existingIds.has(formatted.id)) {\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n const options = [\n { label: 'Required authentication', options: requiredFormatted },\n { label: 'Available authentication', options: availableFormatted },\n ]\n\n // We don't return the groups if we don't have any required schemes\n if (!canAddNewAuth) {\n return requiredFormatted.length ? options : availableFormatted\n }\n\n // Add new authentication options (unless explicitly hidden)\n options.push({\n label: 'Add new authentication',\n options: Object.entries(authOptions).map(([key, value]) => ({\n id: key,\n label: value.label,\n value: { [key]: [] },\n payload: value.payload,\n isDeletable: false,\n })),\n })\n\n return options\n}\n"],"mappings":";;;;AA0BA,IAAM,wBAAwB,gBAC5B,KAAK,UAAU,OAAO,KAAK,YAAY,CAAC;;;;;;;AAQ1C,IAAa,gBAAgB,EAAE,MAAM,aAAiE;CACpG,IAAI,aAAa,KAAK,UAAU,MAAM,CAAC;CACvC,OAAO;CACP;CACA,aAAa;CACd;;AAGD,IAAa,uBAAuB,WAClC,aAAa;CACX,MAAM,OAAO,KAAK,OAAO,CAAC,KAAK,MAAM;CACrC,OAAO;CACR,CAAC;;;;;AAMJ,IAAM,6BACJ,aACA,oBACqC;CACrC,MAAM,OAAO,O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C,sBAAmB,KAAK,UAAU;AAClC,eAAY,IAAI,UAAU,GAAG;;;CAIjC,MAAM,UAAU,CACd;EAAE,OAAO;EAA2B,SAAS;EAAmB,EAChE;EAAE,OAAO;EAA4B,SAAS;EAAoB,CACnE;AAGD,KAAI,CAAC,cACH,QAAO,kBAAkB,SAAS,UAAU;AAI9C,SAAQ,KAAK;EACX,OAAO;EACP,SAAS,OAAO,QAAQ,YAAY,CAAC,KAAK,CAAC,KAAK,YAAY;GAC1D,IAAI;GACJ,OAAO,MAAM;GACb,OAAO,GAAG,MAAM,EAAE,EAAE;GACpB,SAAS,MAAM;GACf,aAAa;GACd,EAAE;EACJ,CAAC;AAEF,QAAO"}
1
+ {"version":3,"file":"security-scheme.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"sourcesContent":["import { generateHash } from '@scalar/helpers/string/generate-hash'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { MergedSecuritySchemes, OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example'\nimport type {\n ComponentsObject,\n OpenApiDocument,\n SecurityRequirementObject,\n SecuritySchemeObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\n\nimport { authOptions } from '@/v2/blocks/scalar-auth-selector-block/helpers/auth-options'\n\n/** A single security scheme option used in the auth dropdown */\nexport type SecuritySchemeOption = {\n id: string\n label: string\n value: SecurityRequirementObject\n isDeletable?: boolean\n payload?: SecuritySchemeObject\n}\n\n/** A group of security scheme options used in the auth dropdown */\nexport type SecuritySchemeGroup = {\n label: string\n options: SecuritySchemeOption[]\n}\n\nconst requirementSignature = (requirement: SecurityRequirementObject): string =>\n JSON.stringify(Object.keys(requirement))\n\n/**\n * Format a scheme object into a display object\n *\n * We also add a hash to the id to ensure it is unique across\n * multiple requirements of the same scheme with different scopes\n */\nexport const formatScheme = ({ name, value }: { name: string; value: SecurityRequirementObject }) => ({\n id: generateHash(JSON.stringify(value)),\n label: name,\n value,\n isDeletable: true,\n})\n\n/** Formats complex security schemes */\nexport const formatComplexScheme = (scheme: NonNullable<OpenApiDocument['security']>[number]) =>\n formatScheme({\n name: Object.keys(scheme).join(' & '),\n value: scheme,\n })\n\n/**\n * Formats a security requirement into a SecuritySchemeOption.\n * Handles both simple (single key) and complex (multiple keys) auth schemes.\n */\nconst formatSecurityRequirement = (\n requirement: SecurityRequirementObject,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n): SecuritySchemeOption | undefined => {\n const keys = Object.keys(requirement)\n\n // Complex auth (multiple keys)\n if (keys.length > 1) {\n return formatComplexScheme(requirement)\n }\n\n // Simple auth (single key)\n if (keys[0]) {\n const scheme = getResolvedRef(securitySchemes[keys[0]])\n if (!scheme) {\n return undefined\n }\n return formatScheme({ name: keys[0], value: requirement })\n }\n\n return undefined\n}\n\n/**\n * Finds the oauth2 scheme best suited to power a bearer scheme's \"Authorize via OAuth2\" shortcut:\n * the first scheme with an interactive grant (authorization code / implicit), the kind that sends\n * a user to an IdP login. Prefers the authorization-code grant (which can refresh) over one\n * offering only implicit, so the more capable flow wins even when it is declared later.\n *\n * This only surfaces a convenience shortcut on the bearer form — it never hides the oauth2 scheme,\n * which stays independently selectable in the auth dropdown.\n */\nexport const getOauth2AcquisitionTarget = (\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n): {\n name: string\n flows: OAuthFlowsObjectSecret\n flowType: 'authorizationCode' | 'implicit'\n scopes: string[]\n} | null => {\n let implicitFallback: {\n name: string\n flows: OAuthFlowsObjectSecret\n flowType: 'implicit'\n scopes: string[]\n } | null = null\n\n for (const [name, schemeRef] of Object.entries(securitySchemes)) {\n const scheme = getResolvedRef(schemeRef)\n if (scheme?.type !== 'oauth2') {\n continue\n }\n const flows = scheme.flows as OAuthFlowsObjectSecret | undefined\n if (!flows) {\n continue\n }\n const scopes = (scheme as { 'x-default-scopes'?: string[] })['x-default-scopes'] ?? []\n\n // Authorization code can refresh, so it wins outright the moment we find one.\n if (flows.authorizationCode) {\n return { name, flows, flowType: 'authorizationCode', scopes }\n }\n // Otherwise remember the first implicit-only scheme in case no auth-code flow turns up.\n if (flows.implicit && !implicitFallback) {\n implicitFallback = { name, flows, flowType: 'implicit', scopes }\n }\n }\n\n return implicitFallback\n}\n\n/**\n * Generates the options for the security scheme combobox\n *\n * Contains either a flat list, or different groups of required, available, and add new\n */\nexport const getSecuritySchemeOptions = (\n security: NonNullable<OpenApiDocument['security']>,\n securitySchemes: NonNullable<ComponentsObject['securitySchemes']> | MergedSecuritySchemes,\n /** We need to add the selected schemes if they do not already exist in the calculated options */\n selectedSchemes: SecurityRequirementObject[],\n /** Allows adding authentication which is not in the document */\n canAddNewAuth = false,\n): SecuritySchemeOption[] | SecuritySchemeGroup[] => {\n const selectedByRequirement = new Map(\n selectedSchemes.map((selectedScheme) => [requirementSignature(selectedScheme), selectedScheme]),\n )\n\n /**\n * Build required schemes formatted as options and track scheme names in a single pass.\n * We use names (not full IDs) because we want to exclude any scheme that is already\n * required, regardless of its specific scopes or hash.\n */\n const { requiredFormatted, requiredSchemeNames, existingIds } = security.reduce(\n (acc, requirement) => {\n // If a required requirement is selected with scopes, use that selected value to\n // keep a single option entry and avoid a phantom duplicate.\n const requirementValue = selectedByRequirement.get(requirementSignature(requirement)) ?? requirement\n const formatted = formatSecurityRequirement(requirementValue, securitySchemes)\n if (formatted) {\n acc.requiredFormatted.push(formatted)\n acc.existingIds.add(formatted.id)\n }\n for (const name of Object.keys(requirement)) {\n acc.requiredSchemeNames.add(name)\n }\n return acc\n },\n {\n requiredFormatted: [] as SecuritySchemeOption[],\n requiredSchemeNames: new Set<string>(),\n existingIds: new Set<string>(),\n },\n )\n\n // Build available schemes (excluding schemes that are in the required list)\n const availableFormatted: SecuritySchemeOption[] = []\n for (const [name, schemeRef] of Object.entries(securitySchemes)) {\n if (requiredSchemeNames.has(name)) {\n continue\n }\n\n const scheme = getResolvedRef(schemeRef)\n if (scheme) {\n const formatted = formatScheme({ name, value: { [name]: [] } })\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n /**\n * Add selected schemes to available if they do not already exist\n * This ensures that selected schemes with specific scopes are always available as options\n */\n for (const selectedScheme of selectedSchemes) {\n const formatted = formatSecurityRequirement(selectedScheme, securitySchemes)\n if (formatted && !existingIds.has(formatted.id)) {\n availableFormatted.push(formatted)\n existingIds.add(formatted.id)\n }\n }\n\n const options = [\n { label: 'Required authentication', options: requiredFormatted },\n { label: 'Available authentication', options: availableFormatted },\n ]\n\n // We don't return the groups if we don't have any required schemes\n if (!canAddNewAuth) {\n return requiredFormatted.length ? options : availableFormatted\n }\n\n // Add new authentication options (unless explicitly hidden)\n options.push({\n label: 'Add new authentication',\n options: Object.entries(authOptions).map(([key, value]) => ({\n id: key,\n label: value.label,\n value: { [key]: [] },\n payload: value.payload,\n isDeletable: false,\n })),\n })\n\n return options\n}\n"],"mappings":";;;;AA2BA,IAAM,wBAAwB,gBAC5B,KAAK,UAAU,OAAO,KAAK,WAAW,CAAC;;;;;;;AAQzC,IAAa,gBAAgB,EAAE,MAAM,aAAiE;CACpG,IAAI,aAAa,KAAK,UAAU,KAAK,CAAC;CACtC,OAAO;CACP;CACA,aAAa;AACf;;AAGA,IAAa,uBAAuB,WAClC,aAAa;CACX,MAAM,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,KAAK;CACpC,OAAO;AACT,CAAC;;;;;AAMH,IAAM,6BACJ,aACA,oBACqC;CACrC,MAAM,OAAO,OAAO,KAAK,WAAW;CAGpC,IAAI,KAAK,SAAS,GAChB,OAAO,oBAAoB,WAAW;CAIxC,IAAI,KAAK,IAAI;EAEX,IAAI,CADW,eAAe,gBAAgB,KAAK,GAC9C,GACH;EAEF,OAAO,aAAa;GAAE,MAAM,KAAK;GAAI,OAAO;EAAY,CAAC;CAC3D;AAGF;;;;;;;;;;AAWA,IAAa,8BACX,oBAMU;CACV,IAAI,mBAKO;CAE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