@scalar/api-client 3.18.0 → 3.19.1
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.
- package/CHANGELOG.md +51 -0
- package/dist/components/HttpMethod/HttpMethod.vue.d.ts +2 -2
- package/dist/components/SectionFilter.vue.d.ts +2 -1
- package/dist/components/SectionFilter.vue.d.ts.map +1 -1
- package/dist/components/SectionFilter.vue.js +1 -1
- package/dist/components/SectionFilter.vue.js.map +1 -1
- package/dist/components/SectionFilter.vue.script.js.map +1 -1
- package/dist/hooks/use-file-dialog.d.ts.map +1 -1
- package/dist/hooks/use-file-dialog.js +1 -0
- package/dist/hooks/use-file-dialog.js.map +1 -1
- package/dist/style.css +136 -90
- package/dist/v2/blocks/operation-block/OperationBlock.vue.d.ts +2 -2
- package/dist/v2/blocks/operation-block/OperationBlock.vue.d.ts.map +1 -1
- package/dist/v2/blocks/operation-block/OperationBlock.vue.js.map +1 -1
- package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js +15 -10
- package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js.map +1 -1
- package/dist/v2/blocks/operation-block/components/Header.vue.d.ts +1 -1
- package/dist/v2/blocks/operation-block/components/Header.vue.js +1 -1
- package/dist/v2/blocks/operation-block/components/Header.vue.js.map +1 -1
- package/dist/v2/blocks/operation-block/components/Header.vue.script.js.map +1 -1
- package/dist/v2/blocks/operation-block/helpers/send-request.d.ts +3 -1
- package/dist/v2/blocks/operation-block/helpers/send-request.d.ts.map +1 -1
- package/dist/v2/blocks/operation-block/helpers/send-request.js +9 -5
- package/dist/v2/blocks/operation-block/helpers/send-request.js.map +1 -1
- package/dist/v2/blocks/operation-block/helpers/validate-path-parameters.d.ts +1 -1
- package/dist/v2/blocks/operation-block/helpers/validate-path-parameters.js +1 -1
- package/dist/v2/blocks/operation-block/helpers/validate-path-parameters.js.map +1 -1
- package/dist/v2/blocks/request-block/RequestBlock.vue.d.ts +3 -1
- package/dist/v2/blocks/request-block/RequestBlock.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/RequestBlock.vue.js +1 -1
- package/dist/v2/blocks/request-block/RequestBlock.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/RequestBlock.vue.script.js +58 -3
- package/dist/v2/blocks/request-block/RequestBlock.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.d.ts +11 -3
- package/dist/v2/blocks/request-block/components/RequestBody.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.js +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js +59 -23
- package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.d.ts +5 -3
- package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.script.js +6 -3
- package/dist/v2/blocks/request-block/components/RequestBodyForm.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.d.ts +1 -1
- package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.script.js +1 -0
- package/dist/v2/blocks/request-block/components/RequestBodyStructured.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js +4 -3
- package/dist/v2/blocks/request-block/components/RequestCodeSnippet.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTable.vue.d.ts +2 -0
- package/dist/v2/blocks/request-block/components/RequestTable.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTable.vue.js +1 -1
- package/dist/v2/blocks/request-block/components/RequestTable.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTable.vue.script.js +7 -3
- package/dist/v2/blocks/request-block/components/RequestTable.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.d.ts +7 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.script.js +17 -5
- package/dist/v2/blocks/request-block/components/RequestTableRow.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.d.ts +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestTableTooltip.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/create-parameter-rows.d.ts +1 -1
- package/dist/v2/blocks/request-block/helpers/create-parameter-rows.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/helpers/create-parameter-rows.js +17 -8
- package/dist/v2/blocks/request-block/helpers/create-parameter-rows.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/fold-structured-body-rows.d.ts +1 -1
- package/dist/v2/blocks/request-block/helpers/fold-structured-body-rows.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/get-form-body-rows.d.ts +3 -1
- package/dist/v2/blocks/request-block/helpers/get-form-body-rows.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/helpers/get-form-body-rows.js +34 -17
- package/dist/v2/blocks/request-block/helpers/get-form-body-rows.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/get-parameter-content.d.ts +1 -1
- package/dist/v2/blocks/request-block/helpers/get-parameter-content.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/get-parameter-schema.d.ts +1 -1
- package/dist/v2/blocks/request-block/helpers/get-parameter-schema.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.d.ts +1 -1
- package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.js +1 -1
- package/dist/v2/blocks/request-block/helpers/get-structured-body-rows.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/group-by.d.ts +3 -4
- package/dist/v2/blocks/request-block/helpers/group-by.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/helpers/group-by.js +12 -10
- package/dist/v2/blocks/request-block/helpers/group-by.js.map +1 -1
- package/dist/v2/blocks/request-block/helpers/validate-parameter.d.ts +1 -1
- package/dist/v2/blocks/request-block/helpers/validate-parameter.js.map +1 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.js +1 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.js.map +1 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js +6 -1
- package/dist/v2/blocks/response-block/ResponseBlock.vue.script.js.map +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.d.ts.map +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.js +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.js.map +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js +42 -16
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js.map +1 -1
- package/dist/v2/blocks/response-block/helpers/media-types.d.ts.map +1 -1
- package/dist/v2/blocks/response-block/helpers/media-types.js +5 -0
- package/dist/v2/blocks/response-block/helpers/media-types.js.map +1 -1
- package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.d.ts +2 -2
- package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.js +1 -1
- package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.script.js +2 -2
- package/dist/v2/blocks/scalar-address-bar-block/components/AddressBar.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-address-bar-block/helpers/refocus-blur-target.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.d.ts +5 -5
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js +10 -7
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.d.ts +16 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.d.ts.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.js +7 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.js.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.script.js +86 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.script.js.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuthScopesInput.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OpenIDConnect.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthDataTable.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.d.ts +5 -5
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js +39 -156
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/auth-options.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/auth-options.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/extract-security-scheme-secrets.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/extract-security-scheme-secrets.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.d.ts +6 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.d.ts.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.js +25 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.js.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.d.ts +1 -2
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.js +2 -2
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js +13 -9
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.d.ts +9 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.d.ts.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.js +36 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.js.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/openid-discovery-to-flows.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.d.ts +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.js.map +1 -1
- package/dist/v2/components/code-input/CodeInput.vue.d.ts +2 -2
- package/dist/v2/components/code-input/CodeInput.vue.d.ts.map +1 -1
- package/dist/v2/components/code-input/CodeInput.vue.js +1 -1
- package/dist/v2/components/code-input/CodeInput.vue.js.map +1 -1
- package/dist/v2/components/code-input/CodeInput.vue.script.js +41 -10
- package/dist/v2/components/code-input/CodeInput.vue.script.js.map +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.d.ts.map +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.js +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.js.map +1 -1
- package/dist/v2/components/code-input/CodeInputLite.vue.script.js +7 -6
- package/dist/v2/components/code-input/CodeInputLite.vue.script.js.map +1 -1
- package/dist/v2/components/code-input/helpers/build-pill-context.d.ts.map +1 -1
- package/dist/v2/components/code-input/helpers/build-pill-context.js.map +1 -1
- package/dist/v2/components/data-table/DataTableCheckbox.vue.d.ts +1 -1
- package/dist/v2/components/data-table/DataTableCheckbox.vue.d.ts.map +1 -1
- package/dist/v2/components/layout/CollapsibleSection.vue.js.map +1 -1
- package/dist/v2/components/layout/CollapsibleSection.vue.script.js.map +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.d.ts +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.d.ts.map +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.js.map +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.script.js +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.script.js.map +1 -1
- package/dist/v2/components/server/ServerDropdownItem.vue.d.ts +1 -1
- package/dist/v2/components/server/ServerDropdownItem.vue.js +1 -1
- package/dist/v2/components/server/ServerDropdownItem.vue.js.map +1 -1
- package/dist/v2/components/server/ServerDropdownItem.vue.script.js.map +1 -1
- package/dist/v2/constants.js +1 -1
- package/dist/v2/features/command-palette/components/CommandActionInput.vue.js.map +1 -1
- package/dist/v2/features/command-palette/components/CommandActionInput.vue.script.js +1 -1
- package/dist/v2/features/command-palette/components/CommandActionInput.vue.script.js.map +1 -1
- package/dist/v2/features/environments/components/EnvironmentColors.vue.js.map +1 -1
- package/dist/v2/features/environments/components/EnvironmentColors.vue.script.js +1 -1
- package/dist/v2/features/environments/components/EnvironmentColors.vue.script.js.map +1 -1
- package/dist/v2/features/modal/Modal.vue.d.ts +1 -1
- package/dist/v2/features/modal/Modal.vue.js.map +1 -1
- package/dist/v2/features/modal/Modal.vue.script.js.map +1 -1
- package/dist/v2/features/modal/helpers/create-api-client-modal.js.map +1 -1
- package/dist/v2/features/modal/helpers/resolve-route-parameters.d.ts +9 -3
- package/dist/v2/features/modal/helpers/resolve-route-parameters.d.ts.map +1 -1
- package/dist/v2/features/modal/helpers/resolve-route-parameters.js +1 -1
- package/dist/v2/features/modal/helpers/resolve-route-parameters.js.map +1 -1
- package/dist/v2/features/modal/hooks/use-modal-sidebar.js +1 -1
- package/dist/v2/features/modal/modal-events.d.ts.map +1 -1
- package/dist/v2/features/modal/modal-events.js +10 -1
- package/dist/v2/features/modal/modal-events.js.map +1 -1
- package/dist/v2/features/operation/Operation.vue.d.ts +1 -1
- package/dist/v2/features/operation/Operation.vue.js.map +1 -1
- package/dist/v2/features/operation/Operation.vue.script.js.map +1 -1
- package/dist/v2/features/search/components/DocumentSearchModal.vue.d.ts +1 -1
- package/dist/v2/features/search/components/DocumentSearchModal.vue.js +1 -1
- package/dist/v2/features/search/components/DocumentSearchModal.vue.js.map +1 -1
- package/dist/v2/features/search/components/DocumentSearchModal.vue.script.js.map +1 -1
- package/dist/v2/features/search/helpers/create-search-index.d.ts +1 -1
- package/dist/v2/features/search/helpers/create-search-index.js.map +1 -1
- package/dist/v2/features/search/hooks/use-document-search.d.ts +1 -1
- package/dist/v2/features/search/hooks/use-document-search.js.map +1 -1
- package/dist/v2/features/search/hooks/use-search-index.d.ts +1 -1
- package/dist/v2/features/search/hooks/use-search-index.js.map +1 -1
- package/dist/vue-styles.css +97 -87
- package/package.json +16 -16
package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.js.map
CHANGED
|
@@ -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 */\
|
|
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 */\nexport const 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,IAAa,+BAA+B,KAAK,OAAO;;CAEtD,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"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error';
|
|
2
2
|
import type { OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example';
|
|
3
|
-
import type { ServerObject } from '@scalar/workspace-store/schemas/v3.
|
|
3
|
+
import type { ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
4
4
|
import type { CustomFetch } from '../../../../v2/blocks/operation-block/helpers/send-request.js';
|
|
5
5
|
type ActiveServerBase = {
|
|
6
6
|
basePath: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,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CAAA;AAEzE;;;GAGG;AACH,eAAO,MAAM,YAAY,GACvB,cAAc,YAAY,GAAG,IAAI,EACjC,uBAAsB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,KAChD,MAIA,CAAA;AAEH;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,GAC9B,cAAc,YAAY,GAAG,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;AAkJD;;;;;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,CAwFrC,CAAA"}
|
|
@@ -92,7 +92,7 @@ var authorizeOauth2 = async (flows, type, selectedScopes, activeServer, proxyUrl
|
|
|
92
92
|
if (!value) return;
|
|
93
93
|
url.searchParams.set(key, value);
|
|
94
94
|
});
|
|
95
|
-
url.searchParams.set("client_id", flow["x-scalar-secret-client-id"]);
|
|
95
|
+
url.searchParams.set("client_id", flow["x-scalar-secret-client-id"].trim());
|
|
96
96
|
url.searchParams.set("state", state);
|
|
97
97
|
if (scopes) url.searchParams.set("scope", scopes);
|
|
98
98
|
if (captureCallback) {
|
|
@@ -168,15 +168,17 @@ var authorizeServers = async (flows, type, scopes, { code, pkce, proxyUrl, custo
|
|
|
168
168
|
if (!flow) return [/* @__PURE__ */ new Error("OAuth2 flow was not defined"), null];
|
|
169
169
|
const formData = new URLSearchParams();
|
|
170
170
|
if (scopes && (type === "clientCredentials" || type === "password")) formData.set("scope", scopes);
|
|
171
|
+
const clientId = flow["x-scalar-secret-client-id"].trim();
|
|
172
|
+
const clientSecret = flow["x-scalar-secret-client-secret"].trim();
|
|
171
173
|
/** Where to add the credentials */
|
|
172
174
|
const addCredentialsToBody = flow["x-scalar-credentials-location"] === "body";
|
|
173
175
|
/**
|
|
174
176
|
* PKCE and client authentication are independent: a confidential client may use both.
|
|
175
177
|
* We send the client_secret whenever one is set, regardless of PKCE (see RFC 9700 Section 2.1.1).
|
|
176
178
|
*/
|
|
177
|
-
const hasClientSecret = Boolean(
|
|
178
|
-
if (addCredentialsToBody || type === "authorizationCode" && !hasClientSecret) formData.set("client_id",
|
|
179
|
-
if (addCredentialsToBody && hasClientSecret) formData.set("client_secret",
|
|
179
|
+
const hasClientSecret = Boolean(clientSecret);
|
|
180
|
+
if (addCredentialsToBody || type === "authorizationCode" && !hasClientSecret) formData.set("client_id", clientId);
|
|
181
|
+
if (addCredentialsToBody && hasClientSecret) formData.set("client_secret", clientSecret);
|
|
180
182
|
if (redirectUri) formData.set("redirect_uri", redirectUri);
|
|
181
183
|
else if ("x-scalar-secret-redirect-uri" in flow && flow["x-scalar-secret-redirect-uri"]) formData.set("redirect_uri", flow["x-scalar-secret-redirect-uri"]);
|
|
182
184
|
if (code) {
|
|
@@ -194,7 +196,7 @@ var authorizeServers = async (flows, type, scopes, { code, pkce, proxyUrl, custo
|
|
|
194
196
|
});
|
|
195
197
|
try {
|
|
196
198
|
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
|
|
197
|
-
if (!addCredentialsToBody && hasClientSecret) headers.Authorization = `Basic ${encode(`${
|
|
199
|
+
if (!addCredentialsToBody && hasClientSecret) headers.Authorization = `Basic ${encode(`${clientId}:${clientSecret}`)}`;
|
|
198
200
|
const tokenUrl = makeUrlAbsolute(flow["x-scalar-secret-token-url"] ?? flow.tokenUrl, getActiveServerBase(activeServer, environmentVariables));
|
|
199
201
|
const responseData = await (await customFetch(shouldUseProxy(proxyUrl, tokenUrl) ? `${proxyUrl}?${new URLSearchParams([["scalar_url", tokenUrl]]).toString()}` : tokenUrl, {
|
|
200
202
|
method: "POST",
|
|
@@ -226,17 +228,19 @@ var refreshOauth2Token = async (flows, type, proxyUrl, activeServer, environment
|
|
|
226
228
|
const formData = new URLSearchParams();
|
|
227
229
|
formData.set("grant_type", "refresh_token");
|
|
228
230
|
formData.set("refresh_token", refreshToken);
|
|
231
|
+
const clientId = flow["x-scalar-secret-client-id"].trim();
|
|
232
|
+
const clientSecret = flow["x-scalar-secret-client-secret"].trim();
|
|
229
233
|
const addCredentialsToBody = flow["x-scalar-credentials-location"] === "body";
|
|
230
234
|
/** A confidential client keeps using its secret on refresh, even when PKCE is enabled. */
|
|
231
|
-
const hasClientSecret = Boolean(
|
|
232
|
-
if (addCredentialsToBody || type === "authorizationCode" && !hasClientSecret) formData.set("client_id",
|
|
233
|
-
if (addCredentialsToBody && hasClientSecret) formData.set("client_secret",
|
|
235
|
+
const hasClientSecret = Boolean(clientSecret);
|
|
236
|
+
if (addCredentialsToBody || type === "authorizationCode" && !hasClientSecret) formData.set("client_id", clientId);
|
|
237
|
+
if (addCredentialsToBody && hasClientSecret) formData.set("client_secret", clientSecret);
|
|
234
238
|
if (flow["x-scalar-security-body"]) Object.entries(flow["x-scalar-security-body"]).forEach(([key, value]) => {
|
|
235
239
|
if (value !== void 0 && value !== null) formData.set(key, String(value));
|
|
236
240
|
});
|
|
237
241
|
try {
|
|
238
242
|
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
|
|
239
|
-
if (!addCredentialsToBody && hasClientSecret) headers.Authorization = `Basic ${encode(`${
|
|
243
|
+
if (!addCredentialsToBody && hasClientSecret) headers.Authorization = `Basic ${encode(`${clientId}:${clientSecret}`)}`;
|
|
240
244
|
const absoluteRefreshUrl = makeUrlAbsolute(flow.refreshUrl || flow["x-scalar-secret-token-url"] || flow.tokenUrl, getActiveServerBase(activeServer, environmentVariables));
|
|
241
245
|
const responseData = await (await customFetch(shouldUseProxy(proxyUrl, absoluteRefreshUrl) ? `${proxyUrl}?${new URLSearchParams([["scalar_url", absoluteRefreshUrl]]).toString()}` : absoluteRefreshUrl, {
|
|
242
246
|
method: "POST",
|
|
@@ -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\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,GAC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AK,CAAC;CAEnC,CAAC;CAGH,IAAI;EACF,MAAM,UAAkC,EACtC,gBAAgB,oCAClB;EAEA,IAAI,CAAC,wBAAwB,iBAC3B,QAAQ,gBAAgB,SAAS,OAAO,GAAG,KAAK,6BAA6B,GAAG,KAAK,kCAAkC;EAIzH,MAAM,qBAAqB,gBADR,KAAK,cAAc,KAAK,gCAAgC,KAAK,UACzB,oBAAoB,cAAc,oBAAoB,CAAC;EAU9G,MAAM,eAAe,OAAM,MALR,YAJP,eAAe,UAAU,kBAAkB,IACnD,GAAG,SAAS,GAAG,IAAI,gBAAgB,CAAC,CAAC,cAAc,kBAAkB,CAAC,CAAC,CAAC,CAAC,SAAS,MAClF,oBAEgC;GAClC,QAAQ;GACR;GACA,MAAM;EACR,CAAC,EAAA,CAC+B,KAAK;EAGrC,MAAM,cAAc,aADF,KAAK,kBAAkB;EAEzC,MAAM,kBAAkB,aAAa;EAErC,IAAI,CAAC,aACH,OAAO,CAAC,IAAI,MAAM,aAAa,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
|
+
{"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.2/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'].trim())\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 // Ignore surrounding copy/paste whitespace without changing stored credentials or other secrets.\n const clientId = flow['x-scalar-secret-client-id'].trim()\n const clientSecret = flow['x-scalar-secret-client-secret'].trim()\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(clientSecret)\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', clientId)\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', clientSecret)\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(`${clientId}:${clientSecret}`)}`\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 // Ignore surrounding copy/paste whitespace without changing stored credentials or other secrets.\n const clientId = flow['x-scalar-secret-client-id'].trim()\n const clientSecret = flow['x-scalar-secret-client-secret'].trim()\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(clientSecret)\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', clientId)\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', clientSecret)\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(`${clientId}:${clientSecret}`)}`\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,MAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI;CAGzD,OAAO,eAAe,IAAI,WAAW,MAAM,GAAG,IAAI;A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,CAAC,IAAI,MAAM,aAAa,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"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { OAuthFlowsObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
2
|
+
import type { OpenIDConnectDiscovery } from './fetch-openid-connect-discovery.js';
|
|
3
|
+
type FlowUpdates = {
|
|
4
|
+
[Key in keyof OAuthFlowsObject]?: Partial<NonNullable<OAuthFlowsObject[Key]>>;
|
|
5
|
+
};
|
|
6
|
+
/** Supplements endpoints in declared flows. Explicit scopes, including an empty scope set, remain authoritative. */
|
|
7
|
+
export declare const oauth2MetadataToFlows: (metadata: OpenIDConnectDiscovery, flows: OAuthFlowsObject) => FlowUpdates;
|
|
8
|
+
export {};
|
|
9
|
+
//# sourceMappingURL=oauth2-metadata-to-flows.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth2-metadata-to-flows.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8DAA8D,CAAA;AAEpG,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAA;AAE9E,KAAK,WAAW,GAAG;KAAG,GAAG,IAAI,MAAM,gBAAgB,CAAC,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC;CAAE,CAAA;AAEpG,oHAAoH;AACpH,eAAO,MAAM,qBAAqB,GAAI,UAAU,sBAAsB,EAAE,OAAO,gBAAgB,KAAG,WA6BjG,CAAA"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.ts
|
|
2
|
+
/** Supplements endpoints in declared flows. Explicit scopes, including an empty scope set, remain authoritative. */
|
|
3
|
+
var oauth2MetadataToFlows = (metadata, flows) => {
|
|
4
|
+
const scopes = Object.fromEntries((metadata.scopes_supported ?? []).map((scope) => [scope, ""]));
|
|
5
|
+
const grants = new Set(metadata.grant_types_supported ?? ["authorization_code", "implicit"]);
|
|
6
|
+
const authorizationUrl = metadata.authorization_endpoint;
|
|
7
|
+
const tokenUrl = metadata.token_endpoint;
|
|
8
|
+
const discovered = {
|
|
9
|
+
...grants.has("implicit") && authorizationUrl ? { implicit: {
|
|
10
|
+
authorizationUrl,
|
|
11
|
+
scopes
|
|
12
|
+
} } : {},
|
|
13
|
+
...grants.has("password") && tokenUrl ? { password: {
|
|
14
|
+
tokenUrl,
|
|
15
|
+
scopes
|
|
16
|
+
} } : {},
|
|
17
|
+
...grants.has("client_credentials") && tokenUrl ? { clientCredentials: {
|
|
18
|
+
tokenUrl,
|
|
19
|
+
scopes
|
|
20
|
+
} } : {},
|
|
21
|
+
...grants.has("authorization_code") && authorizationUrl && tokenUrl ? { authorizationCode: {
|
|
22
|
+
authorizationUrl,
|
|
23
|
+
tokenUrl,
|
|
24
|
+
scopes
|
|
25
|
+
} } : {}
|
|
26
|
+
};
|
|
27
|
+
if (!Object.keys(flows).length) return discovered;
|
|
28
|
+
return Object.fromEntries(Object.entries(flows).filter(([, flow]) => flow).map(([key, flow]) => [key, {
|
|
29
|
+
..."authorizationUrl" in flow && !flow.authorizationUrl && authorizationUrl ? { authorizationUrl } : {},
|
|
30
|
+
..."tokenUrl" in flow && !flow.tokenUrl && tokenUrl ? { tokenUrl } : {}
|
|
31
|
+
}]).filter(([, update]) => Object.keys(update).length > 0));
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { oauth2MetadataToFlows };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=oauth2-metadata-to-flows.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth2-metadata-to-flows.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.ts"],"sourcesContent":["import type { OAuthFlowsObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport type { OpenIDConnectDiscovery } from './fetch-openid-connect-discovery'\n\ntype FlowUpdates = { [Key in keyof OAuthFlowsObject]?: Partial<NonNullable<OAuthFlowsObject[Key]>> }\n\n/** Supplements endpoints in declared flows. Explicit scopes, including an empty scope set, remain authoritative. */\nexport const oauth2MetadataToFlows = (metadata: OpenIDConnectDiscovery, flows: OAuthFlowsObject): FlowUpdates => {\n const scopes = Object.fromEntries((metadata.scopes_supported ?? []).map((scope) => [scope, '']))\n const grants = new Set(metadata.grant_types_supported ?? ['authorization_code', 'implicit'])\n const authorizationUrl = metadata.authorization_endpoint\n const tokenUrl = metadata.token_endpoint\n const discovered: FlowUpdates = {\n ...(grants.has('implicit') && authorizationUrl ? { implicit: { authorizationUrl, scopes } } : {}),\n ...(grants.has('password') && tokenUrl ? { password: { tokenUrl, scopes } } : {}),\n ...(grants.has('client_credentials') && tokenUrl ? { clientCredentials: { tokenUrl, scopes } } : {}),\n ...(grants.has('authorization_code') && authorizationUrl && tokenUrl\n ? { authorizationCode: { authorizationUrl, tokenUrl, scopes } }\n : {}),\n }\n // An empty Flows Object can discover supported grants. Otherwise the API description controls the allowed flows.\n if (!Object.keys(flows).length) {\n return discovered\n }\n return Object.fromEntries(\n Object.entries(flows)\n .filter(([, flow]) => flow)\n .map(([key, flow]): [string, Record<string, string>] => [\n key,\n {\n ...('authorizationUrl' in flow && !flow.authorizationUrl && authorizationUrl ? { authorizationUrl } : {}),\n ...('tokenUrl' in flow && !fl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@ -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
|
+
{"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.2/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"}
|
|
@@ -2,7 +2,7 @@ import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error';
|
|
|
2
2
|
import type { WorkspaceEventBus } from '@scalar/workspace-store/events';
|
|
3
3
|
import { type OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example';
|
|
4
4
|
import type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments';
|
|
5
|
-
import type { ServerObject } from '@scalar/workspace-store/schemas/v3.
|
|
5
|
+
import type { ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
6
6
|
import type { OAuth2Options } from '../../../../v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.js';
|
|
7
7
|
import { type OAuth2Tokens } from '../../../../v2/blocks/scalar-auth-selector-block/helpers/oauth.js';
|
|
8
8
|
/**
|
|
@@ -1 +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
|
+
{"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.2/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,5 +1,5 @@
|
|
|
1
1
|
import type { MergedSecuritySchemes, OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example';
|
|
2
|
-
import type { ComponentsObject, OpenApiDocument, SecurityRequirementObject, SecuritySchemeObject } from '@scalar/workspace-store/schemas/v3.
|
|
2
|
+
import type { ComponentsObject, OpenApiDocument, SecurityRequirementObject, SecuritySchemeObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
3
3
|
/** A single security scheme option used in the auth dropdown */
|
|
4
4
|
export type SecuritySchemeOption = {
|
|
5
5
|
id: string;
|
|
@@ -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":"AAGA,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;AAWrE,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;AAuCJ;;;;;;;;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,IAgCH,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,
|
|
1
|
+
{"version":3,"file":"security-scheme.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/security-scheme.ts"],"names":[],"mappings":"AAGA,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;AAWrE,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;AAuCJ;;;;;;;;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,IAgCH,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,EAuF9C,CAAA"}
|
|
@@ -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 { isHidden } from '@scalar/workspace-store/helpers/is-hidden'\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/**\n * Minimal shape read by `isHidden`. Some scheme union members (AsyncAPI broker schemes) do not\n * structurally carry the ignore extensions, so we cast to this before the check to satisfy the\n * weak-type check without widening `isHidden` itself.\n */\ntype Hideable = { 'x-internal'?: boolean; 'x-scalar-ignore'?: boolean }\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 // Drop the whole AND combination if any of its schemes is hidden via x-scalar-ignore — a\n // partly hidden requirement cannot be configured, so it should not appear as an option.\n const anyHidden = keys.some((key) => {\n const scheme = getResolvedRef(securitySchemes[key])\n return scheme ? isHidden(scheme as Hideable) : false\n })\n if (anyHidden) {\n return undefined\n }\n return formatComplexScheme(requirement)\n }\n\n // Simple auth (single key)\n if (keys[0]) {\n const scheme = getResolvedRef(securitySchemes[keys[0]])\n // Drop schemes that do not exist or are hidden from the auth UI via x-scalar-ignore.\n if (!scheme || isHidden(scheme as Hideable)) {\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 // Skip schemes hidden from the auth UI via x-scalar-ignore, so the shortcut never\n // targets a flow the user cannot see or configure.\n if (scheme?.type !== 'oauth2' || isHidden(scheme)) {\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 && !isHidden(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 && !isHidden(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 // Skip schemes hidden from the auth UI via x-scalar-ignore.\n if (scheme && !isHidden(scheme as Hideable)) {\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":";;;;;AAmCA,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,GAAG;EAOnB,IAJkB,KAAK,MAAM,QAAQ;GACnC,MAAM,SAAS,eAAe,gBAAgB,IAAI;GAClD,OAAO,SAAS,SAAS,MAAkB,IAAI;EACjD,CACI,GACF;EAEF,OAAO,oBAAoB,WAAW;CACxC;CAGA,IAAI,KAAK,IAAI;EACX,MAAM,SAAS,eAAe,gBAAgB,KAAK,GAAG;EAEtD,IAAI,CAAC,UAAU,SAAS,MAAkB,GACxC;EAEF,OAAO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,cAAc,OAAO,QAAQ,eAAe,GAAG;EAC/D,IAAI,oBAAoB,IAAI,IAAI,GAC9B;EAGF,MAAM,SAAS,eAAe,SAAS;EAEvC,IAAI,UAAU,CAAC,SAAS,MAAkB,GAAG;GAC3C,MAAM,YAAY,aAAa;IAAE;IAAM,OAAO,GAAG,OAAO,CAAC,EAAE;GAAE,CAAC;GAC9D,mBAAmB,KAAK,SAAS;GACjC,YAAY,IAAI,UAAU,EAAE;EAC9B;CACF;;;;;CAMA,KAAK,MAAM,kBAAkB,iBAAiB;EAC5C,MAAM,YAAY,0BAA0B,gBAAgB,eAAe;EAC3E,IAAI,aAAa,CAAC,YAAY,IAAI,UAAU,EAAE,GAAG;GAC/C,mBAAmB,KAAK,SAAS;GACjC,YAAY,IAAI,UAAU,EAAE;EAC9B;CACF;CAEA,MAAM,UAAU,CACd;EAAE,OAAO;EAA2B,SAAS;CAAkB,GAC/D;EAAE,OAAO;EAA4B,SAAS;CAAmB,CACnE;CAGA,IAAI,CAAC,eACH,OAAO,kBAAkB,SAAS,UAAU;CAI9C,QAAQ,KAAK;EACX,OAAO;EACP,SAAS,OAAO,QAAQ,WAAW,CAAC,CAAC,KAAK,CAAC,KAAK,YAAY;GAC1D,IAAI;GACJ,OAAO,MAAM;GACb,OAAO,GAAG,MAAM,CAAC,EAAE;GACnB,SAAS,MAAM;GACf,aAAa;EACf,EAAE;CACJ,CAAC;CAED,OAAO;AACT"}
|
|
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 { isHidden } from '@scalar/workspace-store/helpers/is-hidden'\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.2/strict/openapi-document'\n\nimport { authOptions } from '@/v2/blocks/scalar-auth-selector-block/helpers/auth-options'\n\n/**\n * Minimal shape read by `isHidden`. Some scheme union members (AsyncAPI broker schemes) do not\n * structurally carry the ignore extensions, so we cast to this before the check to satisfy the\n * weak-type check without widening `isHidden` itself.\n */\ntype Hideable = { 'x-internal'?: boolean; 'x-scalar-ignore'?: boolean }\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 // Drop the whole AND combination if any of its schemes is hidden via x-scalar-ignore — a\n // partly hidden requirement cannot be configured, so it should not appear as an option.\n const anyHidden = keys.some((key) => {\n const scheme = getResolvedRef(securitySchemes[key])\n return scheme ? isHidden(scheme as Hideable) : false\n })\n if (anyHidden) {\n return undefined\n }\n return formatComplexScheme(requirement)\n }\n\n // Simple auth (single key)\n if (keys[0]) {\n const scheme = getResolvedRef(securitySchemes[keys[0]])\n // Drop schemes that do not exist or are hidden from the auth UI via x-scalar-ignore.\n if (!scheme || isHidden(scheme as Hideable)) {\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 // Skip schemes hidden from the auth UI via x-scalar-ignore, so the shortcut never\n // targets a flow the user cannot see or configure.\n if (scheme?.type !== 'oauth2' || isHidden(scheme)) {\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 && !isHidden(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 && !isHidden(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 requiredFormatted: SecuritySchemeOption[]\n requiredSchemeNames: Set<string>\n existingIds: Set<string>\n }>(\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: [],\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 // Skip schemes hidden from the auth UI via x-scalar-ignore.\n if (scheme && !isHidden(scheme as Hideable)) {\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":";;;;;AAmCA,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,GAAG;EAOnB,IAJkB,KAAK,MAAM,QAAQ;GACnC,MAAM,SAAS,eAAe,gBAAgB,IAAI;GAClD,OAAO,SAAS,SAAS,MAAkB,IAAI;EACjD,CACI,GACF;EAEF,OAAO,oBAAoB,WAAW;CACxC;CAGA,IAAI,KAAK,IAAI;EACX,MAAM,SAAS,eAAe,gBAAgB,KAAK,GAAG;EAEtD,IAAI,CAAC,UAAU,SAAS,MAAkB,GACxC;EAEF,OAAO,aAAa;GAAE,MAAM,KAAK;GAAI,O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;EAC/D,IAAI,oBAAoB,IAAI,IAAI,GAC9B;EAGF,MAAM,SAAS,eAAe,SAAS;EAEvC,IAAI,UAAU,CAAC,SAAS,MAAkB,GAAG;GAC3C,MAAM,YAAY,aAAa;IAAE;IAAM,OAAO,GAAG,OAAO,CAAC,EAAE;GAAE,CAAC;GAC9D,mBAAmB,KAAK,SAAS;GACjC,YAAY,IAAI,UAAU,EAAE;EAC9B;CACF;;;;;CAMA,KAAK,MAAM,kBAAkB,iBAAiB;EAC5C,MAAM,YAAY,0BAA0B,gBAAgB,eAAe;EAC3E,IAAI,aAAa,CAAC,YAAY,IAAI,UAAU,EAAE,GAAG;GAC/C,mBAAmB,KAAK,SAAS;GACjC,YAAY,IAAI,UAAU,EAAE;EAC9B;CACF;CAEA,MAAM,UAAU,CACd;EAAE,OAAO;EAA2B,SAAS;CAAkB,GAC/D;EAAE,OAAO;EAA4B,SAAS;CAAmB,CACnE;CAGA,IAAI,CAAC,eACH,OAAO,kBAAkB,SAAS,UAAU;CAI9C,QAAQ,KAAK;EACX,OAAO;EACP,SAAS,OAAO,QAAQ,WAAW,CAAC,CAAC,KAAK,CAAC,KAAK,YAAY;GAC1D,IAAI;GACJ,OAAO,MAAM;GACb,OAAO,GAAG,MAAM,CAAC,EAAE;GACnB,SAAS,MAAM;GACf,aAAa;EACf,EAAE;CACJ,CAAC;CAED,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CodeMirrorLanguage, type Extension } from '@scalar/use-codemirror';
|
|
1
|
+
import { EditorView, type CodeMirrorLanguage, type Extension } from '@scalar/use-codemirror';
|
|
2
2
|
import type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments';
|
|
3
3
|
import { type Ref } from 'vue';
|
|
4
4
|
import type { ClientLayout } from '../../../v2/types/layout';
|
|
@@ -98,7 +98,7 @@ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
|
|
|
98
98
|
handleSubmit: (value: string, event: KeyboardEvent | FocusEvent) => void;
|
|
99
99
|
handleBlur: (value: string, event: FocusEvent) => void;
|
|
100
100
|
booleanOptions: import("vue").ComputedRef<string[]>;
|
|
101
|
-
codeMirror: Ref<
|
|
101
|
+
codeMirror: Ref<EditorView | null, EditorView | null>;
|
|
102
102
|
codeMirrorRef: Ref<HTMLDivElement | null, HTMLDivElement | null>;
|
|
103
103
|
modelValue: CodeInputModelValue;
|
|
104
104
|
setCodeMirrorContent: (content?: string) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeInput.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/components/code-input/CodeInput.vue"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"CodeInput.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/components/code-input/CodeInput.vue"],"names":[],"mappings":"AAwvBA,OAAO,EAEL,UAAU,EAGV,KAAK,kBAAkB,EACvB,KAAK,SAAS,EACf,MAAM,wBAAwB,CAAA;AAM/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2EAA2E,CAAA;AAEnH,OAAO,EAAyC,KAAK,GAAG,EAAE,MAAM,KAAK,CAAA;AAIrE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAKrD,MAAM,MAAM,mBAAmB,GAC3B,MAAM,GACN,MAAM,GACN,OAAO,GACP,KAAK,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAChC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAE3B;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;wBACkB,OAAO,YAAY;AAAxC,wBAAyC;AAKzC,QAAA,MAAM,YAAY;gBAEJ,mBAAmB;IAC/B,6FAA6F;iBAChF,kBAAkB,GAAG,SAAS;IAC3C,mEAAmE;WAC5D,MAAM,GAAG,MAAM,EAAE;IACxB,sCAAsC;eAC3B,OAAO;IAClB,yBAAyB;YACjB,OAAO;IACf,kDAAkD;aACz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;IAClB,uCAAuC;kBACzB,MAAM;IACpB,8BAA8B;eACnB,OAAO;IAClB,oCAAoC;kBACtB,OAAO;IACrB,kCAAkC;kBACpB,OAAO;IACrB,qBAAqB;WACd,OAAO;IACd,2BAA2B;mBACZ,OAAO;IACtB,+BAA+B;eACpB,kBAAkB;IAC7B,uCAAuC;iBAC1B,SAAS,EAAE;IACxB,sCAAsC;uBACnB,OAAO;IAC1B,wBAAwB;mBACT,OAAO;IACtB,wCAAwC;2BACjB,OAAO;IAC9B,gCAAgC;iBACnB,OAAO;IACpB,wCAAwC;oBACxB,OAAO;IACvB,yHAAyH;mBAC1G,OAAO;IACtB,sDAAsD;uBACnC,OAAO;IAC1B,mDAAmD;wBAC/B,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI;IAC3C,mDAAmD;wBAC/B,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI;IAC3C,0CAA0C;kBAC5B,OAAO;;;;;;cAsCO,UAAU;cAAQ,aAAa;;;cA4tB/C,CAAC,KAAK,IAAiB,KAAK,GAAG;;WAClC,CAAC,KAAK,IAAiB,KAAK,GAAG;EAYtC,CAAC;AACL,KAAK,eAAe,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG;IAChC,QAAO;QACN,MAAM,EAAE,CAAC,CAAC;KACV,CAAA;CACD,CAAC"}
|
|
@@ -3,7 +3,7 @@ import CodeInput_vue_vue_type_script_setup_true_lang_default from "./CodeInput.v
|
|
|
3
3
|
/* empty css */
|
|
4
4
|
/* empty css */
|
|
5
5
|
//#region src/v2/components/code-input/CodeInput.vue
|
|
6
|
-
var CodeInput_default = /*#__PURE__*/ _plugin_vue_export_helper_default(CodeInput_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-
|
|
6
|
+
var CodeInput_default = /*#__PURE__*/ _plugin_vue_export_helper_default(CodeInput_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-dbc85839"]]);
|
|
7
7
|
//#endregion
|
|
8
8
|
export { CodeInput_default as default };
|
|
9
9
|
|