@scalar/api-client 3.23.0 → 3.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/components/ScalarAsciiArt/ScalarAsciiArt.vue.js +1 -1
  3. package/dist/components/ScalarAsciiArt/ScalarAsciiArt.vue.js.map +1 -1
  4. package/dist/components/ScalarAsciiArt/ScalarAsciiArt.vue.script.js +2 -2
  5. package/dist/components/ScalarAsciiArt/ScalarAsciiArt.vue.script.js.map +1 -1
  6. package/dist/style.css +162 -122
  7. package/dist/v2/blocks/operation-block/OperationBlock.vue.js.map +1 -1
  8. package/dist/v2/blocks/operation-block/OperationBlock.vue.script.js.map +1 -1
  9. package/dist/v2/blocks/operation-block/components/Header.vue.d.ts.map +1 -1
  10. package/dist/v2/blocks/operation-block/components/Header.vue.js +1 -1
  11. package/dist/v2/blocks/operation-block/components/Header.vue.js.map +1 -1
  12. package/dist/v2/blocks/operation-block/components/Header.vue.script.js.map +1 -1
  13. package/dist/v2/blocks/request-block/RequestBlock.vue.d.ts.map +1 -1
  14. package/dist/v2/blocks/request-block/RequestBlock.vue.js +1 -1
  15. package/dist/v2/blocks/request-block/RequestBlock.vue.js.map +1 -1
  16. package/dist/v2/blocks/request-block/RequestBlock.vue.script.js.map +1 -1
  17. package/dist/v2/blocks/request-block/components/RequestParams.vue.d.ts.map +1 -1
  18. package/dist/v2/blocks/request-block/components/RequestParams.vue.js.map +1 -1
  19. package/dist/v2/blocks/request-block/components/RequestParams.vue.script.js.map +1 -1
  20. package/dist/v2/blocks/request-block/components/RequestTable.vue.d.ts.map +1 -1
  21. package/dist/v2/blocks/request-block/components/RequestTable.vue.js +1 -1
  22. package/dist/v2/blocks/request-block/components/RequestTable.vue.js.map +1 -1
  23. package/dist/v2/blocks/request-block/components/RequestTable.vue.script.js.map +1 -1
  24. package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.js +1 -1
  25. package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.js.map +1 -1
  26. package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js +4 -4
  27. package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js.map +1 -1
  28. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.d.ts.map +1 -1
  29. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.js.map +1 -1
  30. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js +2 -4
  31. package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2.vue.script.js.map +1 -1
  32. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.d.ts.map +1 -1
  33. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.js.map +1 -1
  34. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js +1 -0
  35. package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js.map +1 -1
  36. package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.d.ts.map +1 -1
  37. package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.js +1 -1
  38. package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.js.map +1 -1
  39. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.d.ts.map +1 -1
  40. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.js +1 -1
  41. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.js.map +1 -1
  42. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.d.ts.map +1 -1
  43. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js +2 -0
  44. package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js.map +1 -1
  45. package/dist/v2/components/code-input/CodeInput.vue.js +1 -1
  46. package/dist/v2/components/code-input/CodeInput.vue.js.map +1 -1
  47. package/dist/v2/components/code-input/CodeInput.vue.script.js +4 -4
  48. package/dist/v2/components/code-input/CodeInput.vue.script.js.map +1 -1
  49. package/dist/v2/components/code-input/CodeInputLite.vue.d.ts.map +1 -1
  50. package/dist/v2/components/code-input/CodeInputLite.vue.js +1 -1
  51. package/dist/v2/components/code-input/CodeInputLite.vue.js.map +1 -1
  52. package/dist/v2/components/code-input/CodeInputLite.vue.script.js.map +1 -1
  53. package/dist/v2/constants.js +1 -1
  54. package/dist/v2/features/modal/Modal.vue.d.ts.map +1 -1
  55. package/dist/v2/features/modal/Modal.vue.js.map +1 -1
  56. package/dist/v2/features/modal/Modal.vue.script.js +1 -0
  57. package/dist/v2/features/modal/Modal.vue.script.js.map +1 -1
  58. package/dist/v2/features/modal/modal-events.d.ts +3 -1
  59. package/dist/v2/features/modal/modal-events.d.ts.map +1 -1
  60. package/dist/v2/features/modal/modal-events.js +2 -1
  61. package/dist/v2/features/modal/modal-events.js.map +1 -1
  62. package/dist/v2/workspace-events.d.ts +4 -1
  63. package/dist/v2/workspace-events.d.ts.map +1 -1
  64. package/dist/v2/workspace-events.js +2 -2
  65. package/dist/v2/workspace-events.js.map +1 -1
  66. package/dist/vue-styles.css +45 -45
  67. package/package.json +13 -13
  68. package/dist/v2/blocks/scalar-auth-selector-block/helpers/extract-security-scheme-secrets.d.ts +0 -10
  69. package/dist/v2/blocks/scalar-auth-selector-block/helpers/extract-security-scheme-secrets.d.ts.map +0 -1
  70. package/dist/v2/blocks/scalar-auth-selector-block/helpers/is-allowed-oauth-url.d.ts +0 -3
  71. package/dist/v2/blocks/scalar-auth-selector-block/helpers/is-allowed-oauth-url.d.ts.map +0 -1
  72. package/dist/v2/blocks/scalar-auth-selector-block/helpers/is-allowed-oauth-url.js +0 -8
  73. package/dist/v2/blocks/scalar-auth-selector-block/helpers/is-allowed-oauth-url.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"RequestAuthTab.vue.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { useLoadingState } from '@scalar/components/loading'\nimport { ScalarMarkdownSummary } from '@scalar/components/markdown'\nimport { ScalarModal, useModal } from '@scalar/components/modal'\nimport { ScalarIconGear } from '@scalar/icons'\nimport { useToasts } from '@scalar/use-toasts'\nimport type {\n SecretsApiKey,\n SecretsHttp,\n} from '@scalar/workspace-store/entities/auth'\nimport type {\n ApiReferenceEvents,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { canResetSecretField } from '@scalar/workspace-store/helpers/auth-secret-fields'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n getEnvironmentVariables,\n type MergedSecuritySchemes,\n type OAuthFlowsObjectSecret,\n type SecuritySchemeObjectSecret,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { getDocumentTypeLabel } from '@scalar/workspace-store/schemas/type-guards'\nimport type {\n ApiKeyObject,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { capitalize, computed, ref } from 'vue'\n\nimport { refreshOauth2Token } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth'\nimport { getVisibleOrderedFlowKeys } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth-flows'\nimport {\n runOAuth2Authorize,\n storeOAuth2Tokens,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize'\nimport { getOauth2AcquisitionTarget } from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport {\n DataTable,\n DataTableCell,\n DataTableRow,\n} from '@/v2/components/data-table'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport OAuth2, { type OAuth2Options } from './OAuth2.vue'\nimport OAuth2Metadata from './OAuth2Metadata.vue'\nimport OpenIDConnect from './OpenIDConnect.vue'\nimport RequestAuthDataTableInput from './RequestAuthDataTableInput.vue'\n\nconst {\n environment,\n isStatic,\n proxyUrl,\n selectedSecuritySchemas,\n securitySchemes,\n server,\n eventBus,\n options,\n documentType = 'openapi',\n} = defineProps<{\n /** Current environment configuration */\n environment: XScalarEnvironment\n /** Controls the display of certain borders which are used when we are non-collapsible */\n isStatic: boolean\n /** Proxy URL */\n proxyUrl: string\n /** Selected security schemes*/\n selectedSecuritySchemas: SecurityRequirementObject\n /** Merged security schemes from the document and the config together with the auth store secrets */\n securitySchemes: MergedSecuritySchemes\n /** Current server configuration */\n server: ServerObject | null\n /** Event bus for authentication updates */\n eventBus: WorkspaceEventBus\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst emits = defineEmits<{\n (\n e: 'update:selectedScopes',\n payload: Omit<ApiReferenceEvents['auth:update:selected-scopes'], 'meta'>,\n ): void\n (e: 'upsert:scope', payload: ApiReferenceEvents['auth:upsert:scopes']): void\n (e: 'delete:scope', payload: ApiReferenceEvents['auth:delete:scopes']): void\n}>()\n\nconst { translate } = useLocalization()\n\ntype SecurityItem = {\n scheme: SecuritySchemeObjectSecret | undefined\n name: string\n scopes: string[]\n /** Ordered, non-hidden oauth2/openIdConnect flow keys for this scheme (empty for other types). */\n visibleFlowKeys: (keyof OAuthFlowsObjectSecret)[]\n}\n\n/**\n * Human-readable name of the document type.\n * Used in the missing-type warning so it points at the correct document\n * (e.g. \"AsyncAPI\") instead of always naming OpenAPI.\n */\nconst documentTypeLabel = computed<string>(() =>\n getDocumentTypeLabel(documentType),\n)\n\n/**\n * Resolves security schemes from the OpenAPI document and combines them with their selected scopes.\n * Each item includes the scheme definition, name, and associated scopes.\n */\nconst security = computed<SecurityItem[]>(() =>\n Object.entries(selectedSecuritySchemas).map(([name, scopes = []]) => {\n const scheme = getResolvedRef(securitySchemes[name])\n return {\n scheme,\n name,\n scopes,\n // Compute the visible, ordered flow keys once per scheme so the tabs, the label, and the\n // active-flow tracking all agree on the same set (and we do not filter + sort on every access).\n visibleFlowKeys:\n scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\n ? getVisibleOrderedFlowKeys(scheme.flows)\n : [],\n }\n }),\n)\n\n/** Tracks which OAuth2 flow is currently active when multiple flows are available. */\nconst activeFlow = ref<string>('')\n\n/**\n * Keeps the selected flow in sync with the currently visible flow keys. Validating against the\n * visible set (not every declared flow) means a selection that becomes hidden — e.g. the document\n * is updated to mark the active flow with `x-scalar-ignore` — resets, so the default (first visible)\n * flow activates instead of leaving no tab selected.\n */\nconst selectedFlow = computed<string>(() => {\n const visibleFlowKeys = security.value.flatMap((item) => item.visibleFlowKeys)\n\n return visibleFlowKeys.some((key) => key === activeFlow.value)\n ? activeFlow.value\n : ''\n})\n\nconst setActiveFlow = (flow: string): void => {\n activeFlow.value = flow\n}\n\n/** Determines if multiple auth schemes are configured, which affects the UI layout. */\nconst hasMultipleSchemes = computed<boolean>(() => security.value.length > 1)\n\n/**\n * Generates a human-readable label for the security scheme.\n * Intentionally omits the description here — it is rendered separately as\n * rich text via ScalarMarkdownSummary so markdown formatting is preserved.\n */\nconst generateLabel = (\n name: string,\n scheme: SecuritySchemeObjectSecret,\n): string => {\n const capitalizedName = capitalize(name)\n\n switch (scheme.type) {\n case 'apiKey':\n return `${capitalizedName}: ${scheme.in}`\n\n case 'openIdConnect':\n case 'oauth2': {\n const firstFlow = getVisibleOrderedFlowKeys(scheme.flows)[0]\n const currentFlow = selectedFlow.value || firstFlow\n if (!currentFlow) {\n return capitalizedName\n }\n return `${capitalizedName}: ${currentFlow}`\n }\n\n case 'http':\n return `${capitalizedName}: ${scheme.scheme}`\n\n default:\n return capitalizedName\n }\n}\n\n/**\n * Whether an API key scheme exposes an editable parameter name.\n *\n * OpenAPI `apiKey` and AsyncAPI `httpApiKey` (normalized to `apiKey`) name a query/header/cookie\n * parameter, so the Name input is shown. AsyncAPI `apiKey` places the key in the broker `user` or\n * `password` slot and has no parameter name, so the Name input is hidden and only the value is asked for.\n */\nconst apiKeyHasName = (scheme: { in?: string }): boolean =>\n scheme.in !== 'user' && scheme.in !== 'password'\n\n/**\n * The scheme's type when it is one we do not render inputs for (a type outside both the OpenAPI\n * and AsyncAPI security scheme unions). Read through a helper so the fallback template branch,\n * where the scheme type is narrowed to `never` after the supported cases, can still surface the type.\n */\nconst getUnsupportedSchemeType = (\n scheme: SecurityItem['scheme'],\n): string | undefined => scheme?.type\n\n/**\n * Determines if an OAuth2 flow tab should be active.\n * The first flow is active by default if no flow is explicitly selected.\n */\nconst isFlowActive = (flowKey: string, index: number): boolean =>\n selectedFlow.value === flowKey || (index === 0 && !selectedFlow.value)\n\n/** Computes the container class for static display mode. */\nconst getStaticBorderClass = (): string | false => isStatic && 'border-t'\n\nconst handleHttpSecretsUpdate = (\n payload: Omit<Partial<SecretsHttp>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'http', ...payload },\n name,\n })\n\nconst handleApiKeySecretsUpdate = (\n payload: Omit<Partial<SecretsApiKey>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\nconst handleApiKeySecuritySchemeUpdate = (\n payload: Omit<Partial<ApiKeyObject>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\n/** Handles scope selection updates for OAuth2 */\nconst handleScopesUpdate = (\n name: string,\n event: { scopes?: string[]; scope?: string; selected?: boolean },\n): void => {\n emits('update:selectedScopes', {\n id: Object.keys(selectedSecuritySchemas),\n name,\n ...event,\n })\n}\n\n/** Handles scope-definition upserts (add / rename / description change) */\nconst handleScopeUpsert = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:upsert:scopes'], 'name'>,\n): void => {\n emits('upsert:scope', { ...event, name })\n}\n\n/** Handles scope-definition deletes */\nconst handleScopeDelete = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:delete:scopes'], 'name'>,\n): void => {\n emits('delete:scope', { ...event, name })\n}\n\n/**\n * Computes dynamic classes for OAuth2 flow tabs based on active state.\n */\nconst getFlowTabClasses = (flowKey: string, index: number): string => {\n const baseClasses =\n 'floating-bg text-c-3 relative cursor-pointer border-b border-transparent py-1 text-base font-medium'\n const activeClasses = '!text-c-1 !rounded-none border-b !border-current'\n\n return isFlowActive(flowKey, index)\n ? `${baseClasses} ${activeClasses} ${isStatic ? 'opacity-100' : ''}`\n : baseClasses\n}\n\n/**\n * OAuth2 token-acquisition target (an oauth2 scheme with an interactive grant) sourced from\n * the merged schemes. When the active scheme is HTTP bearer, this powers the inline\n * \"Authorize via OAuth2\" shortcut: the flow's bearer token is written onto the bearer scheme,\n * so the panel never switches to oauth2.\n *\n * The shortcut is purely a convenience, so it is offered for any interactive oauth2 scheme —\n * including one that is also independently selectable in the dropdown (e.g. Scalar Galaxy's\n * `oAuth2`). Whether that oauth2 scheme is *hidden* from the dropdown is a separate decision made\n * in the selector; here we only surface the shortcut.\n */\nconst oauth2Target = computed(() => getOauth2AcquisitionTarget(securitySchemes))\n\n/** Resolved oauth2 scheme object, for embedding its config form behind the gear. */\nconst oauth2Scheme = computed(() =>\n oauth2Target.value\n ? getResolvedRef(securitySchemes[oauth2Target.value.name])\n : undefined,\n)\n\nconst acquisitionLoader = useLoadingState()\nconst { toast } = useToasts()\nconst configModal = useModal()\n/** Bearer scheme that opened the config modal, so its Authorize callback targets it. */\nconst configBearerName = ref<string | undefined>()\n\n/** Runs the OAuth2 flow and writes the resulting bearer token onto the bearer scheme. */\nconst handleAcquisitionAuthorize = async (\n bearerName: string,\n): Promise<void> => {\n const target = oauth2Target.value\n if (!target || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error] = await runOAuth2Authorize({\n eventBus,\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flows: target.flows,\n flowType: target.flowType,\n scopes: target.scopes,\n server,\n proxyUrl,\n environment,\n options,\n })\n await acquisitionLoader.clear()\n if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToauthorize'),\n 'error',\n )\n }\n}\n\n/** Refreshes the OAuth2 token and rewrites it onto the bearer scheme. */\nconst handleAcquisitionRefresh = async (bearerName: string): Promise<void> => {\n const target = oauth2Target.value\n // Only the authorization-code flow carries a refresh token; implicit can't be refreshed.\n if (target?.flowType !== 'authorizationCode' || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error, tokens] = await refreshOauth2Token(\n target.flows,\n target.flowType,\n proxyUrl,\n server,\n getEnvironmentVariables(environment),\n options?.customFetch,\n )\n await acquisitionLoader.clear()\n if (tokens?.accessToken) {\n storeOAuth2Tokens(eventBus, {\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flowType: target.flowType,\n tokens,\n })\n } else if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToRefresh'),\n 'error',\n )\n }\n}\n\nconst openAcquisitionConfig = (bearerName: string): void => {\n configBearerName.value = bearerName\n configModal.show()\n}\n\n/** Closes the config modal and runs Authorize against the bearer scheme that opened it. */\nconst handleConfigAuthorize = (): void => {\n const bearerName = configBearerName.value\n configModal.hide()\n if (bearerName) {\n void handleAcquisitionAuthorize(bearerName)\n }\n}\n</script>\n<template>\n <template\n v-for=\"{ scheme, name, scopes, visibleFlowKeys } in security\"\n :key=\"name\">\n <!--\n Header row for AND'ed schemes: label (bold) and description (rich text) are\n combined.\n -->\n <DataTableRow v-if=\"hasMultipleSchemes && scheme\">\n <DataTableCell\n :aria-label=\"generateLabel(name, scheme)\"\n class=\"max-h-[auto]\">\n <div class=\"bg-b-1 min-w-0 flex-1 px-3 py-1.25\">\n <p class=\"text-c-1 leading-5.5 font-medium\">\n {{ generateLabel(name, scheme) }}\n </p>\n <ScalarMarkdownSummary\n v-if=\"scheme.description\"\n class=\"auth-description text-c-2 w-full\"\n :value=\"scheme.description\" />\n </div>\n </DataTableCell>\n </DataTableRow>\n\n <!-- Description: shown for single auth schemes with descriptions -->\n <DataTableRow v-if=\"scheme?.description && !hasMultipleSchemes\">\n <DataTableCell\n :aria-label=\"scheme.description\"\n class=\"max-h-[auto]\">\n <ScalarMarkdownSummary\n class=\"auth-description bg-b-1 text-c-2 min-w-0 flex-1 px-3 py-1.25\"\n :value=\"scheme.description\" />\n </DataTableCell>\n </DataTableRow>\n\n <!-- HTTP Authentication -->\n <template v-if=\"scheme?.type === 'http'\">\n <!-- Bearer Token -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer'\">\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n :placeholder=\"translate('apiClient.requestAuthTab.token')\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) => handleHttpSecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.bearerToken') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n\n <!-- OAuth2 token-acquisition shortcut (shown when an interactive oauth2 flow exists) -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer' && oauth2Target\">\n <!--\n Authorize stays rightmost so it never moves: Refresh only appears once there is a token,\n and it slots in between the gear and Authorize instead of pushing Authorize aside.\n -->\n <div class=\"flex h-8 items-center gap-2 border-t pr-1 pl-3 text-base\">\n <span class=\"text-c-1 mr-auto\">{{\n translate('apiClient.requestAuthTab.getAToken')\n }}</span>\n <ScalarIconButton\n class=\"h-6 w-6 p-1.25\"\n :icon=\"ScalarIconGear\"\n :label=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \"\n @click=\"openAcquisitionConfig(name)\" />\n <ScalarButton\n v-if=\"\n scheme['x-scalar-secret-token'] &&\n oauth2Target.flowType === 'authorizationCode'\n \"\n class=\"px-3 py-1\"\n :disabled=\"acquisitionLoader.isLoading\"\n size=\"sm\"\n type=\"button\"\n variant=\"outlined\"\n @click=\"handleAcquisitionRefresh(name)\">\n {{ translate('apiClient.requestAuthTab.refresh') }}\n </ScalarButton>\n <ScalarButton\n class=\"text-c-1 px-3 py-1\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n type=\"button\"\n variant=\"gradient\"\n @click=\"handleAcquisitionAuthorize(name)\">\n {{\n translate('apiClient.requestAuthTab.authorizeVia', {\n name: oauth2Target.name,\n })\n }}\n </ScalarButton>\n </div>\n </DataTableRow>\n\n <!-- HTTP Basic Authentication -->\n <template v-else-if=\"scheme?.scheme === 'basic'\">\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-username',\n scheme['x-scalar-secret-username'],\n )\n \"\n class=\"text-c-2\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-username']\"\n placeholder=\"janedoe\"\n required\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-username',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-username': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.username') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-password',\n scheme['x-scalar-secret-password'],\n )\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-password']\"\n placeholder=\"********\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-password',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-password': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.password') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n </template>\n\n <!-- API Key Authentication -->\n <template v-else-if=\"scheme?.type === 'apiKey'\">\n <DataTableRow v-if=\"apiKeyHasName(scheme)\">\n <RequestAuthDataTableInput\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme.name ?? ''\"\n placeholder=\"api-key\"\n @update:modelValue=\"\n (v) => handleApiKeySecuritySchemeUpdate({ name: v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.name') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"\n apiKeyHasName(scheme) ? undefined : getStaticBorderClass()\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n placeholder=\"QUxMIFlPVVIgQkFTRSBBUkUgQkVMT05HIFRPIFVT\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleApiKeySecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.value') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n\n <!-- OAuth 2.0 / OpenID Connect Authentication -->\n <template\n v-else-if=\"scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\">\n <OAuth2Metadata\n v-if=\"\n scheme.type === 'oauth2' && (!isStatic || scheme.oauth2MetadataUrl)\n \"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :name\n :proxyUrl\n :scheme />\n\n <!-- OpenID Connect -->\n <OpenIDConnect\n v-if=\"scheme?.type === 'openIdConnect' && !visibleFlowKeys.length\"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :getStaticBorderClass\n :name\n :proxyUrl\n :scheme />\n\n <!-- Flow selector tabs: shown when multiple visible flows are available -->\n <DataTableRow v-if=\"visibleFlowKeys.length > 1\">\n <div class=\"flex min-h-8 border-t text-base\">\n <div class=\"flex h-8 max-w-full gap-2.5 overflow-x-auto px-3\">\n <button\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\"\n :class=\"getFlowTabClasses(key, ind)\"\n type=\"button\"\n @click=\"setActiveFlow(key)\">\n <span class=\"relative z-10\">{{ key }}</span>\n </button>\n </div>\n </div>\n </DataTableRow>\n\n <!-- OAuth2 flow configuration -->\n <template\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\">\n <OAuth2\n v-if=\"scheme.flows && isFlowActive(key, ind)\"\n :environment\n :eventBus\n :flows=\"scheme.flows\"\n :name\n :options\n :proxyUrl\n :scheme\n :selectedScopes=\"scopes\"\n :server\n :type=\"key\"\n @delete:scope=\"(event) => handleScopeDelete(name, event)\"\n @update:selectedScopes=\"(event) => handleScopesUpdate(name, event)\"\n @upsert:scope=\"(event) => handleScopeUpsert(name, event)\" />\n </template>\n </template>\n\n <!-- Browser WebSocket connections cannot apply these broker credentials. -->\n <div\n v-else-if=\"\n scheme?.type === 'userPassword' ||\n scheme?.type === 'plain' ||\n scheme?.type === 'scramSha256' ||\n scheme?.type === 'scramSha512' ||\n scheme?.type === 'X509' ||\n scheme?.type === 'symmetricEncryption' ||\n scheme?.type === 'asymmetricEncryption' ||\n scheme?.type === 'gssapi'\n \"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.unsupportedCredentials') }}\n </div>\n\n <!-- Mutual TLS credentials are chosen during the browser-managed TLS handshake. -->\n <div\n v-else-if=\"scheme?.type === 'mutualTLS'\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.mutualTlsHint') }}\n </div>\n\n <!-- Scheme has a type we do not render inputs for -->\n <div\n v-else-if=\"getUnsupportedSchemeType(scheme)\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.unsupportedType', {\n type: getUnsupportedSchemeType(scheme) ?? '',\n })\n }}\n </div>\n\n <!-- Scheme is missing type -->\n <div\n v-else\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.missingType', {\n type: documentTypeLabel,\n })\n }}\n </div>\n </template>\n\n <!-- OAuth2 configuration modal (opened from the bearer scheme's gear) -->\n <ScalarModal\n v-if=\"oauth2Target && oauth2Scheme\"\n size=\"sm\"\n :state=\"configModal\"\n :title=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \">\n <DataTable\n :columns=\"['']\"\n presentational>\n <OAuth2\n :environment\n :eventBus\n :flows=\"oauth2Target.flows\"\n hideActions\n :name=\"oauth2Target.name\"\n :options\n :proxyUrl\n :scheme=\"oauth2Scheme\"\n :selectedScopes=\"oauth2Target.scopes\"\n :server\n :type=\"oauth2Target.flowType\"\n @delete:scope=\"(event) => handleScopeDelete(oauth2Target!.name, event)\"\n @update:selectedScopes=\"\n (event) => handleScopesUpdate(oauth2Target!.name, event)\n \"\n @upsert:scope=\"\n (event) => handleScopeUpsert(oauth2Target!.name, event)\n \" />\n </DataTable>\n <div class=\"flex h-8 items-center justify-end gap-2 border-t\">\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n size=\"sm\"\n variant=\"outlined\"\n @click=\"configModal.hide()\">\n {{ translate('apiClient.requestAuthTab.cancel') }}\n </ScalarButton>\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n @click=\"handleConfigAuthorize\">\n {{ translate('apiClient.requestAuthTab.authorize') }}\n </ScalarButton>\n </div>\n </ScalarModal>\n</template>\n"],"mappings":""}
1
+ {"version":3,"file":"RequestAuthTab.vue.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { useLoadingState } from '@scalar/components/loading'\nimport { ScalarMarkdownSummary } from '@scalar/components/markdown'\nimport { ScalarModal, useModal } from '@scalar/components/modal'\nimport { ScalarIconGear } from '@scalar/icons'\nimport { useToasts } from '@scalar/use-toasts'\nimport type {\n SecretsApiKey,\n SecretsHttp,\n} from '@scalar/workspace-store/entities/auth'\nimport type {\n ApiReferenceEvents,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { canResetSecretField } from '@scalar/workspace-store/helpers/auth-secret-fields'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n getEnvironmentVariables,\n type MergedSecuritySchemes,\n type OAuthFlowsObjectSecret,\n type SecuritySchemeObjectSecret,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { getDocumentTypeLabel } from '@scalar/workspace-store/schemas/type-guards'\nimport type {\n ApiKeyObject,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { capitalize, computed, ref } from 'vue'\n\nimport { refreshOauth2Token } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth'\nimport { getVisibleOrderedFlowKeys } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth-flows'\nimport {\n runOAuth2Authorize,\n storeOAuth2Tokens,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize'\nimport { getOauth2AcquisitionTarget } from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport {\n DataTable,\n DataTableCell,\n DataTableRow,\n} from '@/v2/components/data-table'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport OAuth2, { type OAuth2Options } from './OAuth2.vue'\nimport OAuth2Metadata from './OAuth2Metadata.vue'\nimport OpenIDConnect from './OpenIDConnect.vue'\nimport RequestAuthDataTableInput from './RequestAuthDataTableInput.vue'\n\nconst {\n environment,\n isStatic,\n proxyUrl,\n selectedSecuritySchemas,\n securitySchemes,\n server,\n eventBus,\n options,\n documentType = 'openapi',\n} = defineProps<{\n /** Current environment configuration */\n environment: XScalarEnvironment\n /** Controls the display of certain borders which are used when we are non-collapsible */\n isStatic: boolean\n /** Proxy URL */\n proxyUrl: string\n /** Selected security schemes*/\n selectedSecuritySchemas: SecurityRequirementObject\n /** Merged security schemes from the document and the config together with the auth store secrets */\n securitySchemes: MergedSecuritySchemes\n /** Current server configuration */\n server: ServerObject | null\n /** Event bus for authentication updates */\n eventBus: WorkspaceEventBus\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst emits = defineEmits<{\n (\n e: 'update:selectedScopes',\n payload: Omit<ApiReferenceEvents['auth:update:selected-scopes'], 'meta'>,\n ): void\n (e: 'upsert:scope', payload: ApiReferenceEvents['auth:upsert:scopes']): void\n (e: 'delete:scope', payload: ApiReferenceEvents['auth:delete:scopes']): void\n}>()\n\nconst { translate } = useLocalization()\n\ntype SecurityItem = {\n scheme: SecuritySchemeObjectSecret | undefined\n name: string\n scopes: string[]\n /** Ordered, non-hidden oauth2/openIdConnect flow keys for this scheme (empty for other types). */\n visibleFlowKeys: (keyof OAuthFlowsObjectSecret)[]\n}\n\n/**\n * Human-readable name of the document type.\n * Used in the missing-type warning so it points at the correct document\n * (e.g. \"AsyncAPI\") instead of always naming OpenAPI.\n */\nconst documentTypeLabel = computed<string>(() =>\n getDocumentTypeLabel(documentType),\n)\n\n/**\n * Resolves security schemes from the OpenAPI document and combines them with their selected scopes.\n * Each item includes the scheme definition, name, and associated scopes.\n */\nconst security = computed<SecurityItem[]>(() =>\n Object.entries(selectedSecuritySchemas).map(([name, scopes = []]) => {\n const scheme = getResolvedRef(securitySchemes[name])\n return {\n scheme,\n name,\n scopes,\n // Compute the visible, ordered flow keys once per scheme so the tabs, the label, and the\n // active-flow tracking all agree on the same set (and we do not filter + sort on every access).\n visibleFlowKeys:\n scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\n ? getVisibleOrderedFlowKeys(scheme.flows)\n : [],\n }\n }),\n)\n\n/** Tracks which OAuth2 flow is currently active when multiple flows are available. */\nconst activeFlow = ref<string>('')\n\n/**\n * Keeps the selected flow in sync with the currently visible flow keys. Validating against the\n * visible set (not every declared flow) means a selection that becomes hidden — e.g. the document\n * is updated to mark the active flow with `x-scalar-ignore` — resets, so the default (first visible)\n * flow activates instead of leaving no tab selected.\n */\nconst selectedFlow = computed<string>(() => {\n const visibleFlowKeys = security.value.flatMap((item) => item.visibleFlowKeys)\n\n return visibleFlowKeys.some((key) => key === activeFlow.value)\n ? activeFlow.value\n : ''\n})\n\nconst setActiveFlow = (flow: string): void => {\n activeFlow.value = flow\n}\n\n/** Determines if multiple auth schemes are configured, which affects the UI layout. */\nconst hasMultipleSchemes = computed<boolean>(() => security.value.length > 1)\n\n/**\n * Generates a human-readable label for the security scheme.\n * Intentionally omits the description here — it is rendered separately as\n * rich text via ScalarMarkdownSummary so markdown formatting is preserved.\n */\nconst generateLabel = (\n name: string,\n scheme: SecuritySchemeObjectSecret,\n): string => {\n const capitalizedName = capitalize(name)\n\n switch (scheme.type) {\n case 'apiKey':\n return `${capitalizedName}: ${scheme.in}`\n\n case 'openIdConnect':\n case 'oauth2': {\n const firstFlow = getVisibleOrderedFlowKeys(scheme.flows)[0]\n const currentFlow = selectedFlow.value || firstFlow\n if (!currentFlow) {\n return capitalizedName\n }\n return `${capitalizedName}: ${currentFlow}`\n }\n\n case 'http':\n return `${capitalizedName}: ${scheme.scheme}`\n\n default:\n return capitalizedName\n }\n}\n\n/**\n * Whether an API key scheme exposes an editable parameter name.\n *\n * OpenAPI `apiKey` and AsyncAPI `httpApiKey` (normalized to `apiKey`) name a query/header/cookie\n * parameter, so the Name input is shown. AsyncAPI `apiKey` places the key in the broker `user` or\n * `password` slot and has no parameter name, so the Name input is hidden and only the value is asked for.\n */\nconst apiKeyHasName = (scheme: { in?: string }): boolean =>\n scheme.in !== 'user' && scheme.in !== 'password'\n\n/**\n * The scheme's type when it is one we do not render inputs for (a type outside both the OpenAPI\n * and AsyncAPI security scheme unions). Read through a helper so the fallback template branch,\n * where the scheme type is narrowed to `never` after the supported cases, can still surface the type.\n */\nconst getUnsupportedSchemeType = (\n scheme: SecurityItem['scheme'],\n): string | undefined => scheme?.type\n\n/**\n * Determines if an OAuth2 flow tab should be active.\n * The first flow is active by default if no flow is explicitly selected.\n */\nconst isFlowActive = (flowKey: string, index: number): boolean =>\n selectedFlow.value === flowKey || (index === 0 && !selectedFlow.value)\n\n/** Computes the container class for static display mode. */\nconst getStaticBorderClass = (): string | false => isStatic && 'border-t'\n\nconst handleHttpSecretsUpdate = (\n payload: Omit<Partial<SecretsHttp>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'http', ...payload },\n name,\n })\n\nconst handleApiKeySecretsUpdate = (\n payload: Omit<Partial<SecretsApiKey>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\n/** Name edits may update the document or a configured override; tokens remain secrets. */\nconst handleApiKeySecuritySchemeUpdate = (\n payload: Omit<Partial<ApiKeyObject>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\n/** Handles scope selection updates for OAuth2 */\nconst handleScopesUpdate = (\n name: string,\n event: { scopes?: string[]; scope?: string; selected?: boolean },\n): void => {\n emits('update:selectedScopes', {\n id: Object.keys(selectedSecuritySchemas),\n name,\n ...event,\n })\n}\n\n/** Handles scope-definition upserts (add / rename / description change) */\nconst handleScopeUpsert = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:upsert:scopes'], 'name'>,\n): void => {\n emits('upsert:scope', { ...event, name })\n}\n\n/** Handles scope-definition deletes */\nconst handleScopeDelete = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:delete:scopes'], 'name'>,\n): void => {\n emits('delete:scope', { ...event, name })\n}\n\n/**\n * Computes dynamic classes for OAuth2 flow tabs based on active state.\n */\nconst getFlowTabClasses = (flowKey: string, index: number): string => {\n const baseClasses =\n 'floating-bg text-c-3 relative cursor-pointer border-b border-transparent py-1 text-base font-medium'\n const activeClasses = '!text-c-1 !rounded-none border-b !border-current'\n\n return isFlowActive(flowKey, index)\n ? `${baseClasses} ${activeClasses} ${isStatic ? 'opacity-100' : ''}`\n : baseClasses\n}\n\n/**\n * OAuth2 token-acquisition target (an oauth2 scheme with an interactive grant) sourced from\n * the merged schemes. When the active scheme is HTTP bearer, this powers the inline\n * \"Authorize via OAuth2\" shortcut: the flow's bearer token is written onto the bearer scheme,\n * so the panel never switches to oauth2.\n *\n * The shortcut is purely a convenience, so it is offered for any interactive oauth2 scheme —\n * including one that is also independently selectable in the dropdown (e.g. Scalar Galaxy's\n * `oAuth2`). Whether that oauth2 scheme is *hidden* from the dropdown is a separate decision made\n * in the selector; here we only surface the shortcut.\n */\nconst oauth2Target = computed(() => getOauth2AcquisitionTarget(securitySchemes))\n\n/** Resolved oauth2 scheme object, for embedding its config form behind the gear. */\nconst oauth2Scheme = computed(() =>\n oauth2Target.value\n ? getResolvedRef(securitySchemes[oauth2Target.value.name])\n : undefined,\n)\n\nconst acquisitionLoader = useLoadingState()\nconst { toast } = useToasts()\nconst configModal = useModal()\n/** Bearer scheme that opened the config modal, so its Authorize callback targets it. */\nconst configBearerName = ref<string | undefined>()\n\n/** Runs the OAuth2 flow and writes the resulting bearer token onto the bearer scheme. */\nconst handleAcquisitionAuthorize = async (\n bearerName: string,\n): Promise<void> => {\n const target = oauth2Target.value\n if (!target || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error] = await runOAuth2Authorize({\n eventBus,\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flows: target.flows,\n flowType: target.flowType,\n scopes: target.scopes,\n server,\n proxyUrl,\n environment,\n options,\n })\n await acquisitionLoader.clear()\n if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToauthorize'),\n 'error',\n )\n }\n}\n\n/** Refreshes the OAuth2 token and rewrites it onto the bearer scheme. */\nconst handleAcquisitionRefresh = async (bearerName: string): Promise<void> => {\n const target = oauth2Target.value\n // Only the authorization-code flow carries a refresh token; implicit can't be refreshed.\n if (target?.flowType !== 'authorizationCode' || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error, tokens] = await refreshOauth2Token(\n target.flows,\n target.flowType,\n proxyUrl,\n server,\n getEnvironmentVariables(environment),\n options?.customFetch,\n )\n await acquisitionLoader.clear()\n if (tokens?.accessToken) {\n storeOAuth2Tokens(eventBus, {\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flowType: target.flowType,\n tokens,\n })\n } else if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToRefresh'),\n 'error',\n )\n }\n}\n\nconst openAcquisitionConfig = (bearerName: string): void => {\n configBearerName.value = bearerName\n configModal.show()\n}\n\n/** Closes the config modal and runs Authorize against the bearer scheme that opened it. */\nconst handleConfigAuthorize = (): void => {\n const bearerName = configBearerName.value\n configModal.hide()\n if (bearerName) {\n void handleAcquisitionAuthorize(bearerName)\n }\n}\n</script>\n<template>\n <template\n v-for=\"{ scheme, name, scopes, visibleFlowKeys } in security\"\n :key=\"name\">\n <!--\n Header row for AND'ed schemes: label (bold) and description (rich text) are\n combined.\n -->\n <DataTableRow v-if=\"hasMultipleSchemes && scheme\">\n <DataTableCell\n :aria-label=\"generateLabel(name, scheme)\"\n class=\"max-h-[auto]\">\n <div class=\"bg-b-1 min-w-0 flex-1 px-3 py-1.25\">\n <p class=\"text-c-1 leading-5.5 font-medium\">\n {{ generateLabel(name, scheme) }}\n </p>\n <ScalarMarkdownSummary\n v-if=\"scheme.description\"\n class=\"auth-description text-c-2 w-full\"\n :value=\"scheme.description\" />\n </div>\n </DataTableCell>\n </DataTableRow>\n\n <!-- Description: shown for single auth schemes with descriptions -->\n <DataTableRow v-if=\"scheme?.description && !hasMultipleSchemes\">\n <DataTableCell\n :aria-label=\"scheme.description\"\n class=\"max-h-[auto]\">\n <ScalarMarkdownSummary\n class=\"auth-description bg-b-1 text-c-2 min-w-0 flex-1 px-3 py-1.25\"\n :value=\"scheme.description\" />\n </DataTableCell>\n </DataTableRow>\n\n <!-- HTTP Authentication -->\n <template v-if=\"scheme?.type === 'http'\">\n <!-- Bearer Token -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer'\">\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n :placeholder=\"translate('apiClient.requestAuthTab.token')\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) => handleHttpSecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.bearerToken') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n\n <!-- OAuth2 token-acquisition shortcut (shown when an interactive oauth2 flow exists) -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer' && oauth2Target\">\n <!--\n Authorize stays rightmost so it never moves: Refresh only appears once there is a token,\n and it slots in between the gear and Authorize instead of pushing Authorize aside.\n -->\n <div class=\"flex h-8 items-center gap-2 border-t pr-1 pl-3 text-base\">\n <span class=\"text-c-1 mr-auto\">{{\n translate('apiClient.requestAuthTab.getAToken')\n }}</span>\n <ScalarIconButton\n class=\"h-6 w-6 p-1.25\"\n :icon=\"ScalarIconGear\"\n :label=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \"\n @click=\"openAcquisitionConfig(name)\" />\n <ScalarButton\n v-if=\"\n scheme['x-scalar-secret-token'] &&\n oauth2Target.flowType === 'authorizationCode'\n \"\n class=\"px-3 py-1\"\n :disabled=\"acquisitionLoader.isLoading\"\n size=\"sm\"\n type=\"button\"\n variant=\"outlined\"\n @click=\"handleAcquisitionRefresh(name)\">\n {{ translate('apiClient.requestAuthTab.refresh') }}\n </ScalarButton>\n <ScalarButton\n class=\"text-c-1 px-3 py-1\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n type=\"button\"\n variant=\"gradient\"\n @click=\"handleAcquisitionAuthorize(name)\">\n {{\n translate('apiClient.requestAuthTab.authorizeVia', {\n name: oauth2Target.name,\n })\n }}\n </ScalarButton>\n </div>\n </DataTableRow>\n\n <!-- HTTP Basic Authentication -->\n <template v-else-if=\"scheme?.scheme === 'basic'\">\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-username',\n scheme['x-scalar-secret-username'],\n )\n \"\n class=\"text-c-2\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-username']\"\n placeholder=\"janedoe\"\n required\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-username',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-username': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.username') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-password',\n scheme['x-scalar-secret-password'],\n )\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-password']\"\n placeholder=\"********\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-password',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-password': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.password') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n </template>\n\n <!-- API Key Authentication -->\n <template v-else-if=\"scheme?.type === 'apiKey'\">\n <DataTableRow v-if=\"apiKeyHasName(scheme)\">\n <RequestAuthDataTableInput\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme.name ?? ''\"\n placeholder=\"api-key\"\n @update:modelValue=\"\n (v) => handleApiKeySecuritySchemeUpdate({ name: v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.name') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"\n apiKeyHasName(scheme) ? undefined : getStaticBorderClass()\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n placeholder=\"QUxMIFlPVVIgQkFTRSBBUkUgQkVMT05HIFRPIFVT\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleApiKeySecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.value') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n\n <!-- OAuth 2.0 / OpenID Connect Authentication -->\n <template\n v-else-if=\"scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\">\n <OAuth2Metadata\n v-if=\"\n scheme.type === 'oauth2' && (!isStatic || scheme.oauth2MetadataUrl)\n \"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :name\n :proxyUrl\n :scheme />\n\n <!-- OpenID Connect -->\n <OpenIDConnect\n v-if=\"scheme?.type === 'openIdConnect' && !visibleFlowKeys.length\"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :getStaticBorderClass\n :name\n :proxyUrl\n :scheme />\n\n <!-- Flow selector tabs: shown when multiple visible flows are available -->\n <DataTableRow v-if=\"visibleFlowKeys.length > 1\">\n <div class=\"flex min-h-8 border-t text-base\">\n <div class=\"flex h-8 max-w-full gap-2.5 overflow-x-auto px-3\">\n <button\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\"\n :class=\"getFlowTabClasses(key, ind)\"\n type=\"button\"\n @click=\"setActiveFlow(key)\">\n <span class=\"relative z-10\">{{ key }}</span>\n </button>\n </div>\n </div>\n </DataTableRow>\n\n <!-- OAuth2 flow configuration -->\n <template\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\">\n <OAuth2\n v-if=\"scheme.flows && isFlowActive(key, ind)\"\n :environment\n :eventBus\n :flows=\"scheme.flows\"\n :name\n :options\n :proxyUrl\n :scheme\n :selectedScopes=\"scopes\"\n :server\n :type=\"key\"\n @delete:scope=\"(event) => handleScopeDelete(name, event)\"\n @update:selectedScopes=\"(event) => handleScopesUpdate(name, event)\"\n @upsert:scope=\"(event) => handleScopeUpsert(name, event)\" />\n </template>\n </template>\n\n <!-- Browser WebSocket connections cannot apply these broker credentials. -->\n <div\n v-else-if=\"\n scheme?.type === 'userPassword' ||\n scheme?.type === 'plain' ||\n scheme?.type === 'scramSha256' ||\n scheme?.type === 'scramSha512' ||\n scheme?.type === 'X509' ||\n scheme?.type === 'symmetricEncryption' ||\n scheme?.type === 'asymmetricEncryption' ||\n scheme?.type === 'gssapi'\n \"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.unsupportedCredentials') }}\n </div>\n\n <!-- Mutual TLS credentials are chosen during the browser-managed TLS handshake. -->\n <div\n v-else-if=\"scheme?.type === 'mutualTLS'\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.mutualTlsHint') }}\n </div>\n\n <!-- Scheme has a type we do not render inputs for -->\n <div\n v-else-if=\"getUnsupportedSchemeType(scheme)\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.unsupportedType', {\n type: getUnsupportedSchemeType(scheme) ?? '',\n })\n }}\n </div>\n\n <!-- Scheme is missing type -->\n <div\n v-else\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.missingType', {\n type: documentTypeLabel,\n })\n }}\n </div>\n </template>\n\n <!-- OAuth2 configuration modal (opened from the bearer scheme's gear) -->\n <ScalarModal\n v-if=\"oauth2Target && oauth2Scheme\"\n size=\"sm\"\n :state=\"configModal\"\n :title=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \">\n <DataTable\n :columns=\"['']\"\n presentational>\n <OAuth2\n :environment\n :eventBus\n :flows=\"oauth2Target.flows\"\n hideActions\n :name=\"oauth2Target.name\"\n :options\n :proxyUrl\n :scheme=\"oauth2Scheme\"\n :selectedScopes=\"oauth2Target.scopes\"\n :server\n :type=\"oauth2Target.flowType\"\n @delete:scope=\"(event) => handleScopeDelete(oauth2Target!.name, event)\"\n @update:selectedScopes=\"\n (event) => handleScopesUpdate(oauth2Target!.name, event)\n \"\n @upsert:scope=\"\n (event) => handleScopeUpsert(oauth2Target!.name, event)\n \" />\n </DataTable>\n <div class=\"flex h-8 items-center justify-end gap-2 border-t\">\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n size=\"sm\"\n variant=\"outlined\"\n @click=\"configModal.hide()\">\n {{ translate('apiClient.requestAuthTab.cancel') }}\n </ScalarButton>\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n @click=\"handleConfigAuthorize\">\n {{ translate('apiClient.requestAuthTab.authorize') }}\n </ScalarButton>\n </div>\n </ScalarModal>\n</template>\n"],"mappings":""}
@@ -159,6 +159,7 @@ var RequestAuthTab_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ d
159
159
  },
160
160
  name
161
161
  });
162
+ /** Name edits may update the document or a configured override; tokens remain secrets. */
162
163
  const handleApiKeySecuritySchemeUpdate = (payload, name) => __props.eventBus.emit("auth:update:security-scheme", {
163
164
  payload: {
164
165
  type: "apiKey",
@@ -1 +1 @@
1
- {"version":3,"file":"RequestAuthTab.vue.script.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { useLoadingState } from '@scalar/components/loading'\nimport { ScalarMarkdownSummary } from '@scalar/components/markdown'\nimport { ScalarModal, useModal } from '@scalar/components/modal'\nimport { ScalarIconGear } from '@scalar/icons'\nimport { useToasts } from '@scalar/use-toasts'\nimport type {\n SecretsApiKey,\n SecretsHttp,\n} from '@scalar/workspace-store/entities/auth'\nimport type {\n ApiReferenceEvents,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { canResetSecretField } from '@scalar/workspace-store/helpers/auth-secret-fields'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n getEnvironmentVariables,\n type MergedSecuritySchemes,\n type OAuthFlowsObjectSecret,\n type SecuritySchemeObjectSecret,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { getDocumentTypeLabel } from '@scalar/workspace-store/schemas/type-guards'\nimport type {\n ApiKeyObject,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { capitalize, computed, ref } from 'vue'\n\nimport { refreshOauth2Token } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth'\nimport { getVisibleOrderedFlowKeys } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth-flows'\nimport {\n runOAuth2Authorize,\n storeOAuth2Tokens,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize'\nimport { getOauth2AcquisitionTarget } from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport {\n DataTable,\n DataTableCell,\n DataTableRow,\n} from '@/v2/components/data-table'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport OAuth2, { type OAuth2Options } from './OAuth2.vue'\nimport OAuth2Metadata from './OAuth2Metadata.vue'\nimport OpenIDConnect from './OpenIDConnect.vue'\nimport RequestAuthDataTableInput from './RequestAuthDataTableInput.vue'\n\nconst {\n environment,\n isStatic,\n proxyUrl,\n selectedSecuritySchemas,\n securitySchemes,\n server,\n eventBus,\n options,\n documentType = 'openapi',\n} = defineProps<{\n /** Current environment configuration */\n environment: XScalarEnvironment\n /** Controls the display of certain borders which are used when we are non-collapsible */\n isStatic: boolean\n /** Proxy URL */\n proxyUrl: string\n /** Selected security schemes*/\n selectedSecuritySchemas: SecurityRequirementObject\n /** Merged security schemes from the document and the config together with the auth store secrets */\n securitySchemes: MergedSecuritySchemes\n /** Current server configuration */\n server: ServerObject | null\n /** Event bus for authentication updates */\n eventBus: WorkspaceEventBus\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst emits = defineEmits<{\n (\n e: 'update:selectedScopes',\n payload: Omit<ApiReferenceEvents['auth:update:selected-scopes'], 'meta'>,\n ): void\n (e: 'upsert:scope', payload: ApiReferenceEvents['auth:upsert:scopes']): void\n (e: 'delete:scope', payload: ApiReferenceEvents['auth:delete:scopes']): void\n}>()\n\nconst { translate } = useLocalization()\n\ntype SecurityItem = {\n scheme: SecuritySchemeObjectSecret | undefined\n name: string\n scopes: string[]\n /** Ordered, non-hidden oauth2/openIdConnect flow keys for this scheme (empty for other types). */\n visibleFlowKeys: (keyof OAuthFlowsObjectSecret)[]\n}\n\n/**\n * Human-readable name of the document type.\n * Used in the missing-type warning so it points at the correct document\n * (e.g. \"AsyncAPI\") instead of always naming OpenAPI.\n */\nconst documentTypeLabel = computed<string>(() =>\n getDocumentTypeLabel(documentType),\n)\n\n/**\n * Resolves security schemes from the OpenAPI document and combines them with their selected scopes.\n * Each item includes the scheme definition, name, and associated scopes.\n */\nconst security = computed<SecurityItem[]>(() =>\n Object.entries(selectedSecuritySchemas).map(([name, scopes = []]) => {\n const scheme = getResolvedRef(securitySchemes[name])\n return {\n scheme,\n name,\n scopes,\n // Compute the visible, ordered flow keys once per scheme so the tabs, the label, and the\n // active-flow tracking all agree on the same set (and we do not filter + sort on every access).\n visibleFlowKeys:\n scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\n ? getVisibleOrderedFlowKeys(scheme.flows)\n : [],\n }\n }),\n)\n\n/** Tracks which OAuth2 flow is currently active when multiple flows are available. */\nconst activeFlow = ref<string>('')\n\n/**\n * Keeps the selected flow in sync with the currently visible flow keys. Validating against the\n * visible set (not every declared flow) means a selection that becomes hidden — e.g. the document\n * is updated to mark the active flow with `x-scalar-ignore` — resets, so the default (first visible)\n * flow activates instead of leaving no tab selected.\n */\nconst selectedFlow = computed<string>(() => {\n const visibleFlowKeys = security.value.flatMap((item) => item.visibleFlowKeys)\n\n return visibleFlowKeys.some((key) => key === activeFlow.value)\n ? activeFlow.value\n : ''\n})\n\nconst setActiveFlow = (flow: string): void => {\n activeFlow.value = flow\n}\n\n/** Determines if multiple auth schemes are configured, which affects the UI layout. */\nconst hasMultipleSchemes = computed<boolean>(() => security.value.length > 1)\n\n/**\n * Generates a human-readable label for the security scheme.\n * Intentionally omits the description here — it is rendered separately as\n * rich text via ScalarMarkdownSummary so markdown formatting is preserved.\n */\nconst generateLabel = (\n name: string,\n scheme: SecuritySchemeObjectSecret,\n): string => {\n const capitalizedName = capitalize(name)\n\n switch (scheme.type) {\n case 'apiKey':\n return `${capitalizedName}: ${scheme.in}`\n\n case 'openIdConnect':\n case 'oauth2': {\n const firstFlow = getVisibleOrderedFlowKeys(scheme.flows)[0]\n const currentFlow = selectedFlow.value || firstFlow\n if (!currentFlow) {\n return capitalizedName\n }\n return `${capitalizedName}: ${currentFlow}`\n }\n\n case 'http':\n return `${capitalizedName}: ${scheme.scheme}`\n\n default:\n return capitalizedName\n }\n}\n\n/**\n * Whether an API key scheme exposes an editable parameter name.\n *\n * OpenAPI `apiKey` and AsyncAPI `httpApiKey` (normalized to `apiKey`) name a query/header/cookie\n * parameter, so the Name input is shown. AsyncAPI `apiKey` places the key in the broker `user` or\n * `password` slot and has no parameter name, so the Name input is hidden and only the value is asked for.\n */\nconst apiKeyHasName = (scheme: { in?: string }): boolean =>\n scheme.in !== 'user' && scheme.in !== 'password'\n\n/**\n * The scheme's type when it is one we do not render inputs for (a type outside both the OpenAPI\n * and AsyncAPI security scheme unions). Read through a helper so the fallback template branch,\n * where the scheme type is narrowed to `never` after the supported cases, can still surface the type.\n */\nconst getUnsupportedSchemeType = (\n scheme: SecurityItem['scheme'],\n): string | undefined => scheme?.type\n\n/**\n * Determines if an OAuth2 flow tab should be active.\n * The first flow is active by default if no flow is explicitly selected.\n */\nconst isFlowActive = (flowKey: string, index: number): boolean =>\n selectedFlow.value === flowKey || (index === 0 && !selectedFlow.value)\n\n/** Computes the container class for static display mode. */\nconst getStaticBorderClass = (): string | false => isStatic && 'border-t'\n\nconst handleHttpSecretsUpdate = (\n payload: Omit<Partial<SecretsHttp>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'http', ...payload },\n name,\n })\n\nconst handleApiKeySecretsUpdate = (\n payload: Omit<Partial<SecretsApiKey>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\nconst handleApiKeySecuritySchemeUpdate = (\n payload: Omit<Partial<ApiKeyObject>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\n/** Handles scope selection updates for OAuth2 */\nconst handleScopesUpdate = (\n name: string,\n event: { scopes?: string[]; scope?: string; selected?: boolean },\n): void => {\n emits('update:selectedScopes', {\n id: Object.keys(selectedSecuritySchemas),\n name,\n ...event,\n })\n}\n\n/** Handles scope-definition upserts (add / rename / description change) */\nconst handleScopeUpsert = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:upsert:scopes'], 'name'>,\n): void => {\n emits('upsert:scope', { ...event, name })\n}\n\n/** Handles scope-definition deletes */\nconst handleScopeDelete = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:delete:scopes'], 'name'>,\n): void => {\n emits('delete:scope', { ...event, name })\n}\n\n/**\n * Computes dynamic classes for OAuth2 flow tabs based on active state.\n */\nconst getFlowTabClasses = (flowKey: string, index: number): string => {\n const baseClasses =\n 'floating-bg text-c-3 relative cursor-pointer border-b border-transparent py-1 text-base font-medium'\n const activeClasses = '!text-c-1 !rounded-none border-b !border-current'\n\n return isFlowActive(flowKey, index)\n ? `${baseClasses} ${activeClasses} ${isStatic ? 'opacity-100' : ''}`\n : baseClasses\n}\n\n/**\n * OAuth2 token-acquisition target (an oauth2 scheme with an interactive grant) sourced from\n * the merged schemes. When the active scheme is HTTP bearer, this powers the inline\n * \"Authorize via OAuth2\" shortcut: the flow's bearer token is written onto the bearer scheme,\n * so the panel never switches to oauth2.\n *\n * The shortcut is purely a convenience, so it is offered for any interactive oauth2 scheme —\n * including one that is also independently selectable in the dropdown (e.g. Scalar Galaxy's\n * `oAuth2`). Whether that oauth2 scheme is *hidden* from the dropdown is a separate decision made\n * in the selector; here we only surface the shortcut.\n */\nconst oauth2Target = computed(() => getOauth2AcquisitionTarget(securitySchemes))\n\n/** Resolved oauth2 scheme object, for embedding its config form behind the gear. */\nconst oauth2Scheme = computed(() =>\n oauth2Target.value\n ? getResolvedRef(securitySchemes[oauth2Target.value.name])\n : undefined,\n)\n\nconst acquisitionLoader = useLoadingState()\nconst { toast } = useToasts()\nconst configModal = useModal()\n/** Bearer scheme that opened the config modal, so its Authorize callback targets it. */\nconst configBearerName = ref<string | undefined>()\n\n/** Runs the OAuth2 flow and writes the resulting bearer token onto the bearer scheme. */\nconst handleAcquisitionAuthorize = async (\n bearerName: string,\n): Promise<void> => {\n const target = oauth2Target.value\n if (!target || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error] = await runOAuth2Authorize({\n eventBus,\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flows: target.flows,\n flowType: target.flowType,\n scopes: target.scopes,\n server,\n proxyUrl,\n environment,\n options,\n })\n await acquisitionLoader.clear()\n if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToauthorize'),\n 'error',\n )\n }\n}\n\n/** Refreshes the OAuth2 token and rewrites it onto the bearer scheme. */\nconst handleAcquisitionRefresh = async (bearerName: string): Promise<void> => {\n const target = oauth2Target.value\n // Only the authorization-code flow carries a refresh token; implicit can't be refreshed.\n if (target?.flowType !== 'authorizationCode' || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error, tokens] = await refreshOauth2Token(\n target.flows,\n target.flowType,\n proxyUrl,\n server,\n getEnvironmentVariables(environment),\n options?.customFetch,\n )\n await acquisitionLoader.clear()\n if (tokens?.accessToken) {\n storeOAuth2Tokens(eventBus, {\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flowType: target.flowType,\n tokens,\n })\n } else if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToRefresh'),\n 'error',\n )\n }\n}\n\nconst openAcquisitionConfig = (bearerName: string): void => {\n configBearerName.value = bearerName\n configModal.show()\n}\n\n/** Closes the config modal and runs Authorize against the bearer scheme that opened it. */\nconst handleConfigAuthorize = (): void => {\n const bearerName = configBearerName.value\n configModal.hide()\n if (bearerName) {\n void handleAcquisitionAuthorize(bearerName)\n }\n}\n</script>\n<template>\n <template\n v-for=\"{ scheme, name, scopes, visibleFlowKeys } in security\"\n :key=\"name\">\n <!--\n Header row for AND'ed schemes: label (bold) and description (rich text) are\n combined.\n -->\n <DataTableRow v-if=\"hasMultipleSchemes && scheme\">\n <DataTableCell\n :aria-label=\"generateLabel(name, scheme)\"\n class=\"max-h-[auto]\">\n <div class=\"bg-b-1 min-w-0 flex-1 px-3 py-1.25\">\n <p class=\"text-c-1 leading-5.5 font-medium\">\n {{ generateLabel(name, scheme) }}\n </p>\n <ScalarMarkdownSummary\n v-if=\"scheme.description\"\n class=\"auth-description text-c-2 w-full\"\n :value=\"scheme.description\" />\n </div>\n </DataTableCell>\n </DataTableRow>\n\n <!-- Description: shown for single auth schemes with descriptions -->\n <DataTableRow v-if=\"scheme?.description && !hasMultipleSchemes\">\n <DataTableCell\n :aria-label=\"scheme.description\"\n class=\"max-h-[auto]\">\n <ScalarMarkdownSummary\n class=\"auth-description bg-b-1 text-c-2 min-w-0 flex-1 px-3 py-1.25\"\n :value=\"scheme.description\" />\n </DataTableCell>\n </DataTableRow>\n\n <!-- HTTP Authentication -->\n <template v-if=\"scheme?.type === 'http'\">\n <!-- Bearer Token -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer'\">\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n :placeholder=\"translate('apiClient.requestAuthTab.token')\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) => handleHttpSecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.bearerToken') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n\n <!-- OAuth2 token-acquisition shortcut (shown when an interactive oauth2 flow exists) -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer' && oauth2Target\">\n <!--\n Authorize stays rightmost so it never moves: Refresh only appears once there is a token,\n and it slots in between the gear and Authorize instead of pushing Authorize aside.\n -->\n <div class=\"flex h-8 items-center gap-2 border-t pr-1 pl-3 text-base\">\n <span class=\"text-c-1 mr-auto\">{{\n translate('apiClient.requestAuthTab.getAToken')\n }}</span>\n <ScalarIconButton\n class=\"h-6 w-6 p-1.25\"\n :icon=\"ScalarIconGear\"\n :label=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \"\n @click=\"openAcquisitionConfig(name)\" />\n <ScalarButton\n v-if=\"\n scheme['x-scalar-secret-token'] &&\n oauth2Target.flowType === 'authorizationCode'\n \"\n class=\"px-3 py-1\"\n :disabled=\"acquisitionLoader.isLoading\"\n size=\"sm\"\n type=\"button\"\n variant=\"outlined\"\n @click=\"handleAcquisitionRefresh(name)\">\n {{ translate('apiClient.requestAuthTab.refresh') }}\n </ScalarButton>\n <ScalarButton\n class=\"text-c-1 px-3 py-1\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n type=\"button\"\n variant=\"gradient\"\n @click=\"handleAcquisitionAuthorize(name)\">\n {{\n translate('apiClient.requestAuthTab.authorizeVia', {\n name: oauth2Target.name,\n })\n }}\n </ScalarButton>\n </div>\n </DataTableRow>\n\n <!-- HTTP Basic Authentication -->\n <template v-else-if=\"scheme?.scheme === 'basic'\">\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-username',\n scheme['x-scalar-secret-username'],\n )\n \"\n class=\"text-c-2\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-username']\"\n placeholder=\"janedoe\"\n required\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-username',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-username': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.username') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-password',\n scheme['x-scalar-secret-password'],\n )\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-password']\"\n placeholder=\"********\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-password',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-password': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.password') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n </template>\n\n <!-- API Key Authentication -->\n <template v-else-if=\"scheme?.type === 'apiKey'\">\n <DataTableRow v-if=\"apiKeyHasName(scheme)\">\n <RequestAuthDataTableInput\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme.name ?? ''\"\n placeholder=\"api-key\"\n @update:modelValue=\"\n (v) => handleApiKeySecuritySchemeUpdate({ name: v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.name') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"\n apiKeyHasName(scheme) ? undefined : getStaticBorderClass()\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n placeholder=\"QUxMIFlPVVIgQkFTRSBBUkUgQkVMT05HIFRPIFVT\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleApiKeySecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.value') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n\n <!-- OAuth 2.0 / OpenID Connect Authentication -->\n <template\n v-else-if=\"scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\">\n <OAuth2Metadata\n v-if=\"\n scheme.type === 'oauth2' && (!isStatic || scheme.oauth2MetadataUrl)\n \"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :name\n :proxyUrl\n :scheme />\n\n <!-- OpenID Connect -->\n <OpenIDConnect\n v-if=\"scheme?.type === 'openIdConnect' && !visibleFlowKeys.length\"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :getStaticBorderClass\n :name\n :proxyUrl\n :scheme />\n\n <!-- Flow selector tabs: shown when multiple visible flows are available -->\n <DataTableRow v-if=\"visibleFlowKeys.length > 1\">\n <div class=\"flex min-h-8 border-t text-base\">\n <div class=\"flex h-8 max-w-full gap-2.5 overflow-x-auto px-3\">\n <button\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\"\n :class=\"getFlowTabClasses(key, ind)\"\n type=\"button\"\n @click=\"setActiveFlow(key)\">\n <span class=\"relative z-10\">{{ key }}</span>\n </button>\n </div>\n </div>\n </DataTableRow>\n\n <!-- OAuth2 flow configuration -->\n <template\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\">\n <OAuth2\n v-if=\"scheme.flows && isFlowActive(key, ind)\"\n :environment\n :eventBus\n :flows=\"scheme.flows\"\n :name\n :options\n :proxyUrl\n :scheme\n :selectedScopes=\"scopes\"\n :server\n :type=\"key\"\n @delete:scope=\"(event) => handleScopeDelete(name, event)\"\n @update:selectedScopes=\"(event) => handleScopesUpdate(name, event)\"\n @upsert:scope=\"(event) => handleScopeUpsert(name, event)\" />\n </template>\n </template>\n\n <!-- Browser WebSocket connections cannot apply these broker credentials. -->\n <div\n v-else-if=\"\n scheme?.type === 'userPassword' ||\n scheme?.type === 'plain' ||\n scheme?.type === 'scramSha256' ||\n scheme?.type === 'scramSha512' ||\n scheme?.type === 'X509' ||\n scheme?.type === 'symmetricEncryption' ||\n scheme?.type === 'asymmetricEncryption' ||\n scheme?.type === 'gssapi'\n \"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.unsupportedCredentials') }}\n </div>\n\n <!-- Mutual TLS credentials are chosen during the browser-managed TLS handshake. -->\n <div\n v-else-if=\"scheme?.type === 'mutualTLS'\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.mutualTlsHint') }}\n </div>\n\n <!-- Scheme has a type we do not render inputs for -->\n <div\n v-else-if=\"getUnsupportedSchemeType(scheme)\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.unsupportedType', {\n type: getUnsupportedSchemeType(scheme) ?? '',\n })\n }}\n </div>\n\n <!-- Scheme is missing type -->\n <div\n v-else\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.missingType', {\n type: documentTypeLabel,\n })\n }}\n </div>\n </template>\n\n <!-- OAuth2 configuration modal (opened from the bearer scheme's gear) -->\n <ScalarModal\n v-if=\"oauth2Target && oauth2Scheme\"\n size=\"sm\"\n :state=\"configModal\"\n :title=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \">\n <DataTable\n :columns=\"['']\"\n presentational>\n <OAuth2\n :environment\n :eventBus\n :flows=\"oauth2Target.flows\"\n hideActions\n :name=\"oauth2Target.name\"\n :options\n :proxyUrl\n :scheme=\"oauth2Scheme\"\n :selectedScopes=\"oauth2Target.scopes\"\n :server\n :type=\"oauth2Target.flowType\"\n @delete:scope=\"(event) => handleScopeDelete(oauth2Target!.name, event)\"\n @update:selectedScopes=\"\n (event) => handleScopesUpdate(oauth2Target!.name, event)\n \"\n @upsert:scope=\"\n (event) => handleScopeUpsert(oauth2Target!.name, event)\n \" />\n </DataTable>\n <div class=\"flex h-8 items-center justify-end gap-2 border-t\">\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n size=\"sm\"\n variant=\"outlined\"\n @click=\"configModal.hide()\">\n {{ translate('apiClient.requestAuthTab.cancel') }}\n </ScalarButton>\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n @click=\"handleConfigAuthorize\">\n {{ translate('apiClient.requestAuthTab.authorize') }}\n </ScalarButton>\n </div>\n </ScalarModal>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmFA,MAAM,QAAQ;EASd,MAAM,EAAE,cAAc,gBAAgB;EAetC,MAAM,oBAAoB,eACxB,qBAAqB,QAAA,YAAY,CACnC;;;;;EAMA,MAAM,WAAW,eACf,OAAO,QAAQ,QAAA,uBAAuB,CAAC,CAAC,KAAK,CAAC,MAAM,SAAS,CAAC,OAAO;GACnE,MAAM,SAAS,eAAe,QAAA,gBAAgB,KAAK;GACnD,OAAO;IACL;IACA;IACA;IAGA,iBACE,QAAQ,SAAS,YAAY,QAAQ,SAAS,kBAC1C,0BAA0B,OAAO,KAAK,IACtC,CAAC;GACT;EACF,CAAC,CACH;;EAGA,MAAM,aAAa,IAAY,EAAE;;;;;;;EAQjC,MAAM,eAAe,eAAuB;GAG1C,OAFwB,SAAS,MAAM,SAAS,SAAS,KAAK,eAEvD,CAAA,CAAgB,MAAM,QAAQ,QAAQ,WAAW,KAAK,IACzD,WAAW,QACX;EACN,CAAC;EAED,MAAM,iBAAiB,SAAuB;GAC5C,WAAW,QAAQ;EACrB;;EAGA,MAAM,qBAAqB,eAA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CAAA,CAAA;;QAEd,YAMe,MAAA,YAAA,GAAA;KALb,OAAM;KACL,QAAQ,MAAA,iBAAA;KACT,MAAK;KACJ,SAAO;;4BAC6C,CAAA,gBAAA,gBAAlD,MAAA,SAAA,CAAS,CAAA,oCAAA,CAAA,GAAA,CAAA,CAAA,CAAA"}
1
+ {"version":3,"file":"RequestAuthTab.vue.script.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { useLoadingState } from '@scalar/components/loading'\nimport { ScalarMarkdownSummary } from '@scalar/components/markdown'\nimport { ScalarModal, useModal } from '@scalar/components/modal'\nimport { ScalarIconGear } from '@scalar/icons'\nimport { useToasts } from '@scalar/use-toasts'\nimport type {\n SecretsApiKey,\n SecretsHttp,\n} from '@scalar/workspace-store/entities/auth'\nimport type {\n ApiReferenceEvents,\n WorkspaceEventBus,\n} from '@scalar/workspace-store/events'\nimport { canResetSecretField } from '@scalar/workspace-store/helpers/auth-secret-fields'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n getEnvironmentVariables,\n type MergedSecuritySchemes,\n type OAuthFlowsObjectSecret,\n type SecuritySchemeObjectSecret,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { getDocumentTypeLabel } from '@scalar/workspace-store/schemas/type-guards'\nimport type {\n ApiKeyObject,\n SecurityRequirementObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { capitalize, computed, ref } from 'vue'\n\nimport { refreshOauth2Token } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth'\nimport { getVisibleOrderedFlowKeys } from '@/v2/blocks/scalar-auth-selector-block/helpers/oauth-flows'\nimport {\n runOAuth2Authorize,\n storeOAuth2Tokens,\n} from '@/v2/blocks/scalar-auth-selector-block/helpers/run-oauth2-authorize'\nimport { getOauth2AcquisitionTarget } from '@/v2/blocks/scalar-auth-selector-block/helpers/security-scheme'\nimport {\n DataTable,\n DataTableCell,\n DataTableRow,\n} from '@/v2/components/data-table'\nimport { useLocalization } from '@/v2/features/localization'\n\nimport OAuth2, { type OAuth2Options } from './OAuth2.vue'\nimport OAuth2Metadata from './OAuth2Metadata.vue'\nimport OpenIDConnect from './OpenIDConnect.vue'\nimport RequestAuthDataTableInput from './RequestAuthDataTableInput.vue'\n\nconst {\n environment,\n isStatic,\n proxyUrl,\n selectedSecuritySchemas,\n securitySchemes,\n server,\n eventBus,\n options,\n documentType = 'openapi',\n} = defineProps<{\n /** Current environment configuration */\n environment: XScalarEnvironment\n /** Controls the display of certain borders which are used when we are non-collapsible */\n isStatic: boolean\n /** Proxy URL */\n proxyUrl: string\n /** Selected security schemes*/\n selectedSecuritySchemas: SecurityRequirementObject\n /** Merged security schemes from the document and the config together with the auth store secrets */\n securitySchemes: MergedSecuritySchemes\n /** Current server configuration */\n server: ServerObject | null\n /** Event bus for authentication updates */\n eventBus: WorkspaceEventBus\n /** Any config options required for the OAuth2 flow */\n options?: OAuth2Options\n /** Type of the document the schemes belong to, used to label the missing-type warning */\n documentType?: 'openapi' | 'asyncapi'\n}>()\n\nconst emits = defineEmits<{\n (\n e: 'update:selectedScopes',\n payload: Omit<ApiReferenceEvents['auth:update:selected-scopes'], 'meta'>,\n ): void\n (e: 'upsert:scope', payload: ApiReferenceEvents['auth:upsert:scopes']): void\n (e: 'delete:scope', payload: ApiReferenceEvents['auth:delete:scopes']): void\n}>()\n\nconst { translate } = useLocalization()\n\ntype SecurityItem = {\n scheme: SecuritySchemeObjectSecret | undefined\n name: string\n scopes: string[]\n /** Ordered, non-hidden oauth2/openIdConnect flow keys for this scheme (empty for other types). */\n visibleFlowKeys: (keyof OAuthFlowsObjectSecret)[]\n}\n\n/**\n * Human-readable name of the document type.\n * Used in the missing-type warning so it points at the correct document\n * (e.g. \"AsyncAPI\") instead of always naming OpenAPI.\n */\nconst documentTypeLabel = computed<string>(() =>\n getDocumentTypeLabel(documentType),\n)\n\n/**\n * Resolves security schemes from the OpenAPI document and combines them with their selected scopes.\n * Each item includes the scheme definition, name, and associated scopes.\n */\nconst security = computed<SecurityItem[]>(() =>\n Object.entries(selectedSecuritySchemas).map(([name, scopes = []]) => {\n const scheme = getResolvedRef(securitySchemes[name])\n return {\n scheme,\n name,\n scopes,\n // Compute the visible, ordered flow keys once per scheme so the tabs, the label, and the\n // active-flow tracking all agree on the same set (and we do not filter + sort on every access).\n visibleFlowKeys:\n scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\n ? getVisibleOrderedFlowKeys(scheme.flows)\n : [],\n }\n }),\n)\n\n/** Tracks which OAuth2 flow is currently active when multiple flows are available. */\nconst activeFlow = ref<string>('')\n\n/**\n * Keeps the selected flow in sync with the currently visible flow keys. Validating against the\n * visible set (not every declared flow) means a selection that becomes hidden — e.g. the document\n * is updated to mark the active flow with `x-scalar-ignore` — resets, so the default (first visible)\n * flow activates instead of leaving no tab selected.\n */\nconst selectedFlow = computed<string>(() => {\n const visibleFlowKeys = security.value.flatMap((item) => item.visibleFlowKeys)\n\n return visibleFlowKeys.some((key) => key === activeFlow.value)\n ? activeFlow.value\n : ''\n})\n\nconst setActiveFlow = (flow: string): void => {\n activeFlow.value = flow\n}\n\n/** Determines if multiple auth schemes are configured, which affects the UI layout. */\nconst hasMultipleSchemes = computed<boolean>(() => security.value.length > 1)\n\n/**\n * Generates a human-readable label for the security scheme.\n * Intentionally omits the description here — it is rendered separately as\n * rich text via ScalarMarkdownSummary so markdown formatting is preserved.\n */\nconst generateLabel = (\n name: string,\n scheme: SecuritySchemeObjectSecret,\n): string => {\n const capitalizedName = capitalize(name)\n\n switch (scheme.type) {\n case 'apiKey':\n return `${capitalizedName}: ${scheme.in}`\n\n case 'openIdConnect':\n case 'oauth2': {\n const firstFlow = getVisibleOrderedFlowKeys(scheme.flows)[0]\n const currentFlow = selectedFlow.value || firstFlow\n if (!currentFlow) {\n return capitalizedName\n }\n return `${capitalizedName}: ${currentFlow}`\n }\n\n case 'http':\n return `${capitalizedName}: ${scheme.scheme}`\n\n default:\n return capitalizedName\n }\n}\n\n/**\n * Whether an API key scheme exposes an editable parameter name.\n *\n * OpenAPI `apiKey` and AsyncAPI `httpApiKey` (normalized to `apiKey`) name a query/header/cookie\n * parameter, so the Name input is shown. AsyncAPI `apiKey` places the key in the broker `user` or\n * `password` slot and has no parameter name, so the Name input is hidden and only the value is asked for.\n */\nconst apiKeyHasName = (scheme: { in?: string }): boolean =>\n scheme.in !== 'user' && scheme.in !== 'password'\n\n/**\n * The scheme's type when it is one we do not render inputs for (a type outside both the OpenAPI\n * and AsyncAPI security scheme unions). Read through a helper so the fallback template branch,\n * where the scheme type is narrowed to `never` after the supported cases, can still surface the type.\n */\nconst getUnsupportedSchemeType = (\n scheme: SecurityItem['scheme'],\n): string | undefined => scheme?.type\n\n/**\n * Determines if an OAuth2 flow tab should be active.\n * The first flow is active by default if no flow is explicitly selected.\n */\nconst isFlowActive = (flowKey: string, index: number): boolean =>\n selectedFlow.value === flowKey || (index === 0 && !selectedFlow.value)\n\n/** Computes the container class for static display mode. */\nconst getStaticBorderClass = (): string | false => isStatic && 'border-t'\n\nconst handleHttpSecretsUpdate = (\n payload: Omit<Partial<SecretsHttp>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'http', ...payload },\n name,\n })\n\nconst handleApiKeySecretsUpdate = (\n payload: Omit<Partial<SecretsApiKey>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme-secrets', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\n/** Name edits may update the document or a configured override; tokens remain secrets. */\nconst handleApiKeySecuritySchemeUpdate = (\n payload: Omit<Partial<ApiKeyObject>, 'type'>,\n name: string,\n): void =>\n eventBus.emit('auth:update:security-scheme', {\n payload: { type: 'apiKey', ...payload },\n name,\n })\n\n/** Handles scope selection updates for OAuth2 */\nconst handleScopesUpdate = (\n name: string,\n event: { scopes?: string[]; scope?: string; selected?: boolean },\n): void => {\n emits('update:selectedScopes', {\n id: Object.keys(selectedSecuritySchemas),\n name,\n ...event,\n })\n}\n\n/** Handles scope-definition upserts (add / rename / description change) */\nconst handleScopeUpsert = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:upsert:scopes'], 'name'>,\n): void => {\n emits('upsert:scope', { ...event, name })\n}\n\n/** Handles scope-definition deletes */\nconst handleScopeDelete = (\n name: string,\n event: Omit<ApiReferenceEvents['auth:delete:scopes'], 'name'>,\n): void => {\n emits('delete:scope', { ...event, name })\n}\n\n/**\n * Computes dynamic classes for OAuth2 flow tabs based on active state.\n */\nconst getFlowTabClasses = (flowKey: string, index: number): string => {\n const baseClasses =\n 'floating-bg text-c-3 relative cursor-pointer border-b border-transparent py-1 text-base font-medium'\n const activeClasses = '!text-c-1 !rounded-none border-b !border-current'\n\n return isFlowActive(flowKey, index)\n ? `${baseClasses} ${activeClasses} ${isStatic ? 'opacity-100' : ''}`\n : baseClasses\n}\n\n/**\n * OAuth2 token-acquisition target (an oauth2 scheme with an interactive grant) sourced from\n * the merged schemes. When the active scheme is HTTP bearer, this powers the inline\n * \"Authorize via OAuth2\" shortcut: the flow's bearer token is written onto the bearer scheme,\n * so the panel never switches to oauth2.\n *\n * The shortcut is purely a convenience, so it is offered for any interactive oauth2 scheme —\n * including one that is also independently selectable in the dropdown (e.g. Scalar Galaxy's\n * `oAuth2`). Whether that oauth2 scheme is *hidden* from the dropdown is a separate decision made\n * in the selector; here we only surface the shortcut.\n */\nconst oauth2Target = computed(() => getOauth2AcquisitionTarget(securitySchemes))\n\n/** Resolved oauth2 scheme object, for embedding its config form behind the gear. */\nconst oauth2Scheme = computed(() =>\n oauth2Target.value\n ? getResolvedRef(securitySchemes[oauth2Target.value.name])\n : undefined,\n)\n\nconst acquisitionLoader = useLoadingState()\nconst { toast } = useToasts()\nconst configModal = useModal()\n/** Bearer scheme that opened the config modal, so its Authorize callback targets it. */\nconst configBearerName = ref<string | undefined>()\n\n/** Runs the OAuth2 flow and writes the resulting bearer token onto the bearer scheme. */\nconst handleAcquisitionAuthorize = async (\n bearerName: string,\n): Promise<void> => {\n const target = oauth2Target.value\n if (!target || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error] = await runOAuth2Authorize({\n eventBus,\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flows: target.flows,\n flowType: target.flowType,\n scopes: target.scopes,\n server,\n proxyUrl,\n environment,\n options,\n })\n await acquisitionLoader.clear()\n if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToauthorize'),\n 'error',\n )\n }\n}\n\n/** Refreshes the OAuth2 token and rewrites it onto the bearer scheme. */\nconst handleAcquisitionRefresh = async (bearerName: string): Promise<void> => {\n const target = oauth2Target.value\n // Only the authorization-code flow carries a refresh token; implicit can't be refreshed.\n if (target?.flowType !== 'authorizationCode' || acquisitionLoader.isLoading) {\n return\n }\n acquisitionLoader.start()\n const [error, tokens] = await refreshOauth2Token(\n target.flows,\n target.flowType,\n proxyUrl,\n server,\n getEnvironmentVariables(environment),\n options?.customFetch,\n )\n await acquisitionLoader.clear()\n if (tokens?.accessToken) {\n storeOAuth2Tokens(eventBus, {\n bearerSchemeName: bearerName,\n oauth2Name: target.name,\n flowType: target.flowType,\n tokens,\n })\n } else if (error) {\n toast(\n error?.message ?? translate('apiClient.requestAuthTab.failedToRefresh'),\n 'error',\n )\n }\n}\n\nconst openAcquisitionConfig = (bearerName: string): void => {\n configBearerName.value = bearerName\n configModal.show()\n}\n\n/** Closes the config modal and runs Authorize against the bearer scheme that opened it. */\nconst handleConfigAuthorize = (): void => {\n const bearerName = configBearerName.value\n configModal.hide()\n if (bearerName) {\n void handleAcquisitionAuthorize(bearerName)\n }\n}\n</script>\n<template>\n <template\n v-for=\"{ scheme, name, scopes, visibleFlowKeys } in security\"\n :key=\"name\">\n <!--\n Header row for AND'ed schemes: label (bold) and description (rich text) are\n combined.\n -->\n <DataTableRow v-if=\"hasMultipleSchemes && scheme\">\n <DataTableCell\n :aria-label=\"generateLabel(name, scheme)\"\n class=\"max-h-[auto]\">\n <div class=\"bg-b-1 min-w-0 flex-1 px-3 py-1.25\">\n <p class=\"text-c-1 leading-5.5 font-medium\">\n {{ generateLabel(name, scheme) }}\n </p>\n <ScalarMarkdownSummary\n v-if=\"scheme.description\"\n class=\"auth-description text-c-2 w-full\"\n :value=\"scheme.description\" />\n </div>\n </DataTableCell>\n </DataTableRow>\n\n <!-- Description: shown for single auth schemes with descriptions -->\n <DataTableRow v-if=\"scheme?.description && !hasMultipleSchemes\">\n <DataTableCell\n :aria-label=\"scheme.description\"\n class=\"max-h-[auto]\">\n <ScalarMarkdownSummary\n class=\"auth-description bg-b-1 text-c-2 min-w-0 flex-1 px-3 py-1.25\"\n :value=\"scheme.description\" />\n </DataTableCell>\n </DataTableRow>\n\n <!-- HTTP Authentication -->\n <template v-if=\"scheme?.type === 'http'\">\n <!-- Bearer Token -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer'\">\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n :placeholder=\"translate('apiClient.requestAuthTab.token')\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) => handleHttpSecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.bearerToken') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n\n <!-- OAuth2 token-acquisition shortcut (shown when an interactive oauth2 flow exists) -->\n <DataTableRow v-if=\"scheme.scheme === 'bearer' && oauth2Target\">\n <!--\n Authorize stays rightmost so it never moves: Refresh only appears once there is a token,\n and it slots in between the gear and Authorize instead of pushing Authorize aside.\n -->\n <div class=\"flex h-8 items-center gap-2 border-t pr-1 pl-3 text-base\">\n <span class=\"text-c-1 mr-auto\">{{\n translate('apiClient.requestAuthTab.getAToken')\n }}</span>\n <ScalarIconButton\n class=\"h-6 w-6 p-1.25\"\n :icon=\"ScalarIconGear\"\n :label=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \"\n @click=\"openAcquisitionConfig(name)\" />\n <ScalarButton\n v-if=\"\n scheme['x-scalar-secret-token'] &&\n oauth2Target.flowType === 'authorizationCode'\n \"\n class=\"px-3 py-1\"\n :disabled=\"acquisitionLoader.isLoading\"\n size=\"sm\"\n type=\"button\"\n variant=\"outlined\"\n @click=\"handleAcquisitionRefresh(name)\">\n {{ translate('apiClient.requestAuthTab.refresh') }}\n </ScalarButton>\n <ScalarButton\n class=\"text-c-1 px-3 py-1\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n type=\"button\"\n variant=\"gradient\"\n @click=\"handleAcquisitionAuthorize(name)\">\n {{\n translate('apiClient.requestAuthTab.authorizeVia', {\n name: oauth2Target.name,\n })\n }}\n </ScalarButton>\n </div>\n </DataTableRow>\n\n <!-- HTTP Basic Authentication -->\n <template v-else-if=\"scheme?.scheme === 'basic'\">\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-username',\n scheme['x-scalar-secret-username'],\n )\n \"\n class=\"text-c-2\"\n :environment\n :modelValue=\"scheme['x-scalar-secret-username']\"\n placeholder=\"janedoe\"\n required\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-username',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-username': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.username') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-password',\n scheme['x-scalar-secret-password'],\n )\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-password']\"\n placeholder=\"********\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-password',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleHttpSecretsUpdate({ 'x-scalar-secret-password': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.password') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n </template>\n\n <!-- API Key Authentication -->\n <template v-else-if=\"scheme?.type === 'apiKey'\">\n <DataTableRow v-if=\"apiKeyHasName(scheme)\">\n <RequestAuthDataTableInput\n :containerClass=\"getStaticBorderClass()\"\n :environment\n :modelValue=\"scheme.name ?? ''\"\n placeholder=\"api-key\"\n @update:modelValue=\"\n (v) => handleApiKeySecuritySchemeUpdate({ name: v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.name') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n <DataTableRow>\n <RequestAuthDataTableInput\n :canReset=\"\n canResetSecretField(\n scheme,\n 'x-scalar-secret-token',\n scheme['x-scalar-secret-token'],\n )\n \"\n :containerClass=\"\n apiKeyHasName(scheme) ? undefined : getStaticBorderClass()\n \"\n :environment\n :modelValue=\"scheme['x-scalar-secret-token']\"\n placeholder=\"QUxMIFlPVVIgQkFTRSBBUkUgQkVMT05HIFRPIFVT\"\n type=\"password\"\n @reset=\"\n eventBus.emit('auth:reset:security-scheme-secret', {\n name,\n field: 'x-scalar-secret-token',\n })\n \"\n @update:modelValue=\"\n (v) =>\n handleApiKeySecretsUpdate({ 'x-scalar-secret-token': v }, name)\n \">\n {{ translate('apiClient.requestAuthTab.value') }}\n </RequestAuthDataTableInput>\n </DataTableRow>\n </template>\n\n <!-- OAuth 2.0 / OpenID Connect Authentication -->\n <template\n v-else-if=\"scheme?.type === 'oauth2' || scheme?.type === 'openIdConnect'\">\n <OAuth2Metadata\n v-if=\"\n scheme.type === 'oauth2' && (!isStatic || scheme.oauth2MetadataUrl)\n \"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :name\n :proxyUrl\n :scheme />\n\n <!-- OpenID Connect -->\n <OpenIDConnect\n v-if=\"scheme?.type === 'openIdConnect' && !visibleFlowKeys.length\"\n :customFetch=\"options?.customFetch\"\n :environment\n :eventBus\n :getStaticBorderClass\n :name\n :proxyUrl\n :scheme />\n\n <!-- Flow selector tabs: shown when multiple visible flows are available -->\n <DataTableRow v-if=\"visibleFlowKeys.length > 1\">\n <div class=\"flex min-h-8 border-t text-base\">\n <div class=\"flex h-8 max-w-full gap-2.5 overflow-x-auto px-3\">\n <button\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\"\n :class=\"getFlowTabClasses(key, ind)\"\n type=\"button\"\n @click=\"setActiveFlow(key)\">\n <span class=\"relative z-10\">{{ key }}</span>\n </button>\n </div>\n </div>\n </DataTableRow>\n\n <!-- OAuth2 flow configuration -->\n <template\n v-for=\"(key, ind) in visibleFlowKeys\"\n :key=\"key\">\n <OAuth2\n v-if=\"scheme.flows && isFlowActive(key, ind)\"\n :environment\n :eventBus\n :flows=\"scheme.flows\"\n :name\n :options\n :proxyUrl\n :scheme\n :selectedScopes=\"scopes\"\n :server\n :type=\"key\"\n @delete:scope=\"(event) => handleScopeDelete(name, event)\"\n @update:selectedScopes=\"(event) => handleScopesUpdate(name, event)\"\n @upsert:scope=\"(event) => handleScopeUpsert(name, event)\" />\n </template>\n </template>\n\n <!-- Browser WebSocket connections cannot apply these broker credentials. -->\n <div\n v-else-if=\"\n scheme?.type === 'userPassword' ||\n scheme?.type === 'plain' ||\n scheme?.type === 'scramSha256' ||\n scheme?.type === 'scramSha512' ||\n scheme?.type === 'X509' ||\n scheme?.type === 'symmetricEncryption' ||\n scheme?.type === 'asymmetricEncryption' ||\n scheme?.type === 'gssapi'\n \"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.unsupportedCredentials') }}\n </div>\n\n <!-- Mutual TLS credentials are chosen during the browser-managed TLS handshake. -->\n <div\n v-else-if=\"scheme?.type === 'mutualTLS'\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{ translate('apiClient.requestAuthTab.mutualTlsHint') }}\n </div>\n\n <!-- Scheme has a type we do not render inputs for -->\n <div\n v-else-if=\"getUnsupportedSchemeType(scheme)\"\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.unsupportedType', {\n type: getUnsupportedSchemeType(scheme) ?? '',\n })\n }}\n </div>\n\n <!-- Scheme is missing type -->\n <div\n v-else\n class=\"text-c-3 flex items-center justify-center border-t p-4 px-4 text-center text-xs text-balance\">\n {{\n translate('apiClient.requestAuthTab.missingType', {\n type: documentTypeLabel,\n })\n }}\n </div>\n </template>\n\n <!-- OAuth2 configuration modal (opened from the bearer scheme's gear) -->\n <ScalarModal\n v-if=\"oauth2Target && oauth2Scheme\"\n size=\"sm\"\n :state=\"configModal\"\n :title=\"\n translate('apiClient.requestAuthTab.configure', {\n name: oauth2Target.name,\n })\n \">\n <DataTable\n :columns=\"['']\"\n presentational>\n <OAuth2\n :environment\n :eventBus\n :flows=\"oauth2Target.flows\"\n hideActions\n :name=\"oauth2Target.name\"\n :options\n :proxyUrl\n :scheme=\"oauth2Scheme\"\n :selectedScopes=\"oauth2Target.scopes\"\n :server\n :type=\"oauth2Target.flowType\"\n @delete:scope=\"(event) => handleScopeDelete(oauth2Target!.name, event)\"\n @update:selectedScopes=\"\n (event) => handleScopesUpdate(oauth2Target!.name, event)\n \"\n @upsert:scope=\"\n (event) => handleScopeUpsert(oauth2Target!.name, event)\n \" />\n </DataTable>\n <div class=\"flex h-8 items-center justify-end gap-2 border-t\">\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n size=\"sm\"\n variant=\"outlined\"\n @click=\"configModal.hide()\">\n {{ translate('apiClient.requestAuthTab.cancel') }}\n </ScalarButton>\n <ScalarButton\n class=\"p-0 px-2 py-0.5\"\n :loader=\"acquisitionLoader\"\n size=\"sm\"\n @click=\"handleConfigAuthorize\">\n {{ translate('apiClient.requestAuthTab.authorize') }}\n </ScalarButton>\n </div>\n </ScalarModal>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmFA,MAAM,QAAQ;EASd,MAAM,EAAE,cAAc,gBAAgB;EAetC,MAAM,oBAAoB,eACxB,qBAAqB,QAAA,YAAY,CACnC;;;;;EAMA,MAAM,WAAW,eACf,OAAO,QAAQ,QAAA,uBAAuB,CAAC,CAAC,KAAK,CAAC,MAAM,SAAS,CAAC,OAAO;GACnE,MAAM,SAAS,eAAe,QAAA,gBAAgB,KAAK;GACnD,OAAO;IACL;IACA;IACA;IAGA,iBACE,QAAQ,SAAS,YAAY,QAAQ,SAAS,kBAC1C,0BAA0B,OAAO,KAAK,IACtC,CAAC;GACT;EACF,CAAC,CACH;;EAGA,MAAM,aAAa,IAAY,EAAE;;;;;;;EAQjC,MAAM,eAAe,eAAuB;GAG1C,OAFwB,SAAS,MAAM,SAAS,SAAS,KAAK,eAEvD,CAAA,CAAgB,MAAM,QAAQ,QAAQ,WAAW,KAAK,IACzD,WAAW,QACX;EACN,CAAC;EAED,MAAM,iBAAiB,SAAuB;GAC5C,WAAW,QAAQ;EACrB;;EAGA,MAAM,qBAAqB,eAAwB,SAAS,MAAM,SAAS,CAAC;;;;;;EAO5E,MAAM,iBACJ,MACA,WACW;GACX,MAAM,kBAAkB,WAAW,IAAI;GAEvC,QAAQ,OAAO,MAAf;IACE,KAAK,UACH,OAAO,GAAG,gBAAgB,IAAI,OAAO;IAEvC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A,CAAA,CAAA,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-oauth2-metadata.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAI3E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kDAAkD,CAAA;AAGnF,OAAO,EACL,KAAK,sBAAsB,IAAI,2BAA2B,EAE3D,MAAM,kCAAkC,CAAA;AAGzC,4FAA4F;AAC5F,eAAO,MAAM,mBAAmB,GAC9B,KAAK,MAAM,EACX,UAAU,MAAM,EAChB,cAAa,WAAmB,KAC/B,OAAO,CAAC,aAAa,CAAC,2BAA2B,CAAC,CAuBpD,CAAA"}
1
+ {"version":3,"file":"fetch-oauth2-metadata.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAK3E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kDAAkD,CAAA;AAGnF,OAAO,EACL,KAAK,sBAAsB,IAAI,2BAA2B,EAE3D,MAAM,kCAAkC,CAAA;AAEzC,4FAA4F;AAC5F,eAAO,MAAM,mBAAmB,GAC9B,KAAK,MAAM,EACX,UAAU,MAAM,EAChB,cAAa,WAAmB,KAC/B,OAAO,CAAC,aAAa,CAAC,2BAA2B,CAAC,CAuBpD,CAAA"}
@@ -1,5 +1,5 @@
1
- import { isAllowedOAuthUrl } from "./is-allowed-oauth-url.js";
2
1
  import { OpenIDConnectDiscoverySchema } from "./fetch-openid-connect-discovery.js";
2
+ import { isAllowedOAuthUrl } from "@scalar/helpers/url/is-allowed-oauth-url";
3
3
  import { redirectToProxy } from "@scalar/helpers/url/redirect-to-proxy";
4
4
  import { coerceValue } from "@scalar/workspace-store/schemas/typebox-coerce";
5
5
  //#region src/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.ts
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-oauth2-metadata.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { redirectToProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport { coerceValue } from '@scalar/workspace-store/schemas/typebox-coerce'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\n// RFC 8414 and OIDC share these consumed fields; this alias does not imply OIDC issuer semantics.\nimport {\n type OpenIDConnectDiscovery as AuthorizationServerMetadata,\n OpenIDConnectDiscoverySchema as AuthorizationServerMetadataSchema,\n} from './fetch-openid-connect-discovery'\nimport { isAllowedOAuthUrl } from './is-allowed-oauth-url'\n\n/** Fetches the exact RFC8414 metadata URL, without applying OIDC issuer URL conventions. */\nexport const fetchOAuth2Metadata = async (\n url: string,\n proxyUrl: string,\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<AuthorizationServerMetadata>> => {\n try {\n const metadataUrl = new URL(url.trim())\n if (!isAllowedOAuthUrl(metadataUrl)) {\n return [new Error('OAuth2 metadata URL must use HTTPS or HTTP for local development URLs'), null]\n }\n const response = await customFetch(redirectToProxy(proxyUrl, metadataUrl.href))\n if (!response.ok) {\n return [new Error(`Failed to fetch OAuth2 metadata: ${response.status} ${response.statusText}`), null]\n }\n const data = coerceValue(AuthorizationServerMetadataSchema, await response.json())\n if (!data.authorization_endpoint && !data.token_endpoint && !data.device_authorization_endpoint) {\n return [new Error('Invalid OAuth2 metadata: missing or invalid endpoints'), null]\n }\n for (const endpoint of [data.authorization_endpoint, data.token_endpoint, data.device_authorization_endpoint]) {\n if (endpoint && !isAllowedOAuthUrl(new URL(endpoint))) {\n return [new Error('OAuth2 metadata endpoints must use HTTPS or HTTP for local development URLs'), null]\n }\n }\n return [null, data]\n } catch (error) {\n return [error instanceof Error ? error : new Error('Failed to fetch OAuth2 metadata'), null]\n }\n}\n"],"mappings":";;;;;;AAcA,IAAa,sBAAsB,OACjC,KACA,UACA,cAA2B,UAC6B;CACxD,IAAI;EACF,MAAM,cAAc,IAAI,IAAI,IAAI,KAAK,CAAC;EACtC,IAAI,CAAC,kBAAkB,WAAW,GAChC,OAAO,iBAAC,IAAI,MAAM,uEAAuE,GAAG,IAAI;EAElG,MAAM,WAAW,MAAM,YAAY,gBAAgB,UAAU,YAAY,IAAI,CAAC;EAC9E,IAAI,CAAC,SAAS,IACZ,OAAO,iBAAC,IAAI,MAAM,oCAAoC,SAAS,OAAO,GAAG,SAAS,YAAY,GAAG,IAAI;EAEvG,MAAM,OAAO,YAAY,8BAAmC,MAAM,SAAS,KAAK,CAAC;EACjF,IAAI,CAAC,KAAK,0BAA0B,CAAC,KAAK,kBAAkB,CAAC,KAAK,+BAChE,OAAO,iBAAC,IAAI,MAAM,uDAAuD,GAAG,IAAI;EAElF,KAAK,MAAM,YAAY;GAAC,KAAK;GAAwB,KAAK;GAAgB,KAAK;EAA6B,GAC1G,IAAI,YAAY,CAAC,kBAAkB,IAAI,IAAI,QAAQ,CAAC,GAClD,OAAO,iBAAC,IAAI,MAAM,6EAA6E,GAAG,IAAI;EAG1G,OAAO,CAAC,MAAM,IAAI;CACpB,SAAS,OAAO;EACd,OAAO,CAAC,iBAAiB,QAAQ,wBAAQ,IAAI,MAAM,iCAAiC,GAAG,IAAI;CAC7F;AACF"}
1
+ {"version":3,"file":"fetch-oauth2-metadata.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { isAllowedOAuthUrl } from '@scalar/helpers/url/is-allowed-oauth-url'\nimport { redirectToProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport { coerceValue } from '@scalar/workspace-store/schemas/typebox-coerce'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\n// RFC 8414 and OIDC share these consumed fields; this alias does not imply OIDC issuer semantics.\nimport {\n type OpenIDConnectDiscovery as AuthorizationServerMetadata,\n OpenIDConnectDiscoverySchema as AuthorizationServerMetadataSchema,\n} from './fetch-openid-connect-discovery'\n\n/** Fetches the exact RFC8414 metadata URL, without applying OIDC issuer URL conventions. */\nexport const fetchOAuth2Metadata = async (\n url: string,\n proxyUrl: string,\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<AuthorizationServerMetadata>> => {\n try {\n const metadataUrl = new URL(url.trim())\n if (!isAllowedOAuthUrl(metadataUrl)) {\n return [new Error('OAuth2 metadata URL must use HTTPS or HTTP for local development URLs'), null]\n }\n const response = await customFetch(redirectToProxy(proxyUrl, metadataUrl.href))\n if (!response.ok) {\n return [new Error(`Failed to fetch OAuth2 metadata: ${response.status} ${response.statusText}`), null]\n }\n const data = coerceValue(AuthorizationServerMetadataSchema, await response.json())\n if (!data.authorization_endpoint && !data.token_endpoint && !data.device_authorization_endpoint) {\n return [new Error('Invalid OAuth2 metadata: missing or invalid endpoints'), null]\n }\n for (const endpoint of [data.authorization_endpoint, data.token_endpoint, data.device_authorization_endpoint]) {\n if (endpoint && !isAllowedOAuthUrl(new URL(endpoint))) {\n return [new Error('OAuth2 metadata endpoints must use HTTPS or HTTP for local development URLs'), null]\n }\n }\n return [null, data]\n } catch (error) {\n return [error instanceof Error ? error : new Error('Failed to fetch OAuth2 metadata'), null]\n }\n}\n"],"mappings":";;;;;;AAcA,IAAa,sBAAsB,OACjC,KACA,UACA,cAA2B,UAC6B;CACxD,IAAI;EACF,MAAM,cAAc,IAAI,IAAI,IAAI,KAAK,CAAC;EACtC,IAAI,CAAC,kBAAkB,WAAW,GAChC,OAAO,iBAAC,IAAI,MAAM,uEAAuE,GAAG,IAAI;EAElG,MAAM,WAAW,MAAM,YAAY,gBAAgB,UAAU,YAAY,IAAI,CAAC;EAC9E,IAAI,CAAC,SAAS,IACZ,OAAO,iBAAC,IAAI,MAAM,oCAAoC,SAAS,OAAO,GAAG,SAAS,YAAY,GAAG,IAAI;EAEvG,MAAM,OAAO,YAAY,8BAAmC,MAAM,SAAS,KAAK,CAAC;EACjF,IAAI,CAAC,KAAK,0BAA0B,CAAC,KAAK,kBAAkB,CAAC,KAAK,+BAChE,OAAO,iBAAC,IAAI,MAAM,uDAAuD,GAAG,IAAI;EAElF,KAAK,MAAM,YAAY;GAAC,KAAK;GAAwB,KAAK;GAAgB,KAAK;EAA6B,GAC1G,IAAI,YAAY,CAAC,kBAAkB,IAAI,IAAI,QAAQ,CAAC,GAClD,OAAO,iBAAC,IAAI,MAAM,6EAA6E,GAAG,IAAI;EAG1G,OAAO,CAAC,MAAM,IAAI;CACpB,SAAS,OAAO;EACd,OAAO,CAAC,iBAAiB,QAAQ,wBAAQ,IAAI,MAAM,iCAAiC,GAAG,IAAI;CAC7F;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-device-authorization.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAK3E,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAA;AACjG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8DAA8D,CAAA;AAEhG,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kDAAkD,CAAA;AAGnF,OAAO,EAAE,KAAK,YAAY,EAAuB,MAAM,SAAS,CAAA;AAOhE,uFAAuF;AACvF,MAAM,MAAM,yBAAyB,GAAG;IACtC,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,EAAE,MAAM,CAAA;IACvB,uBAAuB,CAAC,EAAE,MAAM,CAAA;CACjC,CAAA;AAED,6CAA6C;AAC7C,MAAM,MAAM,0BAA0B,GAAG;IACvC,QAAQ,EAAE,CAAC,MAAM,EAAE,yBAAyB,KAAK,IAAI,CAAA;IACrD,MAAM,EAAE,WAAW,CAAA;CACpB,CAAA;AA4BD,oGAAoG;AACpG,eAAO,MAAM,eAAe,GAC1B,MAAM,kCAAkC,EACxC,QAAQ,MAAM,EAAE,EAChB,QAAQ,YAAY,GAAG,IAAI,EAC3B,UAAU,MAAM,EAChB,aAAa,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACnC,cAAa,WAAmB,EAChC,UAAU,0BAA0B,KACnC,OAAO,CAAC,aAAa,CAAC,YAAY,CAAC,CAgIrC,CAAA"}
1
+ {"version":3,"file":"oauth-device-authorization.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAM3E,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAA;AACjG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8DAA8D,CAAA;AAEhG,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kDAAkD,CAAA;AAEnF,OAAO,EAAE,KAAK,YAAY,EAAuB,MAAM,SAAS,CAAA;AAOhE,uFAAuF;AACvF,MAAM,MAAM,yBAAyB,GAAG;IACtC,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,EAAE,MAAM,CAAA;IACvB,uBAAuB,CAAC,EAAE,MAAM,CAAA;CACjC,CAAA;AAED,6CAA6C;AAC7C,MAAM,MAAM,0BAA0B,GAAG;IACvC,QAAQ,EAAE,CAAC,MAAM,EAAE,yBAAyB,KAAK,IAAI,CAAA;IACrD,MAAM,EAAE,WAAW,CAAA;CACpB,CAAA;AA4BD,oGAAoG;AACpG,eAAO,MAAM,eAAe,GAC1B,MAAM,kCAAkC,EACxC,QAAQ,MAAM,EAAE,EAChB,QAAQ,YAAY,GAAG,IAAI,EAC3B,UAAU,MAAM,EAChB,aAAa,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACnC,cAAa,WAAmB,EAChC,UAAU,0BAA0B,KACnC,OAAO,CAAC,aAAa,CAAC,YAAY,CAAC,CAgIrC,CAAA"}
@@ -1,9 +1,9 @@
1
1
  import { oauthClientAuthorization } from "./oauth-client-authorization.js";
2
- import { isAllowedOAuthUrl } from "./is-allowed-oauth-url.js";
3
2
  import { getActiveServerBase } from "./oauth.js";
4
3
  import { makeUrlAbsolute } from "@scalar/helpers/url/make-url-absolute";
5
4
  import { replaceEnvVariables } from "@scalar/helpers/regex/replace-variables";
6
5
  import { isObject } from "@scalar/helpers/object/is-object";
6
+ import { isAllowedOAuthUrl } from "@scalar/helpers/url/is-allowed-oauth-url";
7
7
  import { redirectToProxy } from "@scalar/helpers/url/redirect-to-proxy";
8
8
  //#region src/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.ts
9
9
  var REQUEST_TIMEOUT_MS = 3e4;
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-device-authorization.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { isObject } from '@scalar/helpers/object/is-object'\nimport { replaceEnvVariables } from '@scalar/helpers/regex/replace-variables'\nimport { makeUrlAbsolute } from '@scalar/helpers/url/make-url-absolute'\nimport { redirectToProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport type { OAuthFlowDeviceAuthorizationSecret } from '@scalar/workspace-store/request-example'\nimport type { ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\nimport { isAllowedOAuthUrl } from './is-allowed-oauth-url'\nimport { type OAuth2Tokens, getActiveServerBase } from './oauth'\nimport { oauthClientAuthorization } from './oauth-client-authorization'\n\nconst REQUEST_TIMEOUT_MS = 30_000\n// Maximum delay supported by the browser timer API.\nconst MAX_TIMEOUT_MS = 2_147_483_647\n\n/** Information the user needs to approve a device without exposing the device code. */\nexport type DeviceAuthorizationPrompt = {\n userCode: string\n verificationUri: string\n verificationUriComplete?: string\n}\n\n/** Device flow UI and cancellation hooks. */\nexport type DeviceAuthorizationOptions = {\n onPrompt: (prompt: DeviceAuthorizationPrompt) => void\n signal: AbortSignal\n}\n\n/** Waits between polls, releasing the timer immediately when cancelled or expired. */\nconst waitForPoll = (milliseconds: number, signal: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n signal.throwIfAborted()\n const abort = (): void => {\n clearTimeout(timer)\n reject(signal.reason)\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', abort)\n resolve()\n }, milliseconds)\n signal.addEventListener('abort', abort, { once: true })\n })\n\nconst verificationUrl = (value: unknown): string => {\n if (typeof value !== 'string') {\n throw new Error('Missing device verification URL')\n }\n const url = new URL(value)\n if (!isAllowedOAuthUrl(url)) {\n throw new Error('Device verification URL must use HTTPS or HTTP for local development URLs')\n }\n return url.href\n}\n\n/** Performs the RFC8628 device grant, respecting expiry, pending responses, and polling backoff. */\nexport const authorizeDevice = async (\n flow: OAuthFlowDeviceAuthorizationSecret,\n scopes: string[],\n server: ServerObject | null,\n proxyUrl: string,\n environment: Record<string, string>,\n customFetch: CustomFetch = fetch,\n options?: DeviceAuthorizationOptions,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n try {\n if (!options) {\n throw new Error('Device authorization requires a verification prompt')\n }\n const resolveValue = (value: string): string => replaceEnvVariables(value, environment)\n const endpoint = (value: string): string =>\n redirectToProxy(proxyUrl, makeUrlAbsolute(resolveValue(value), getActiveServerBase(server, environment)))\n const tokenUrl = flow['x-scalar-secret-token-url'] ?? flow.tokenUrl\n if (!tokenUrl.trim()) {\n throw new Error('Token URL is required')\n }\n const clientId = resolveValue(flow['x-scalar-secret-client-id'])\n const clientSecret = resolveValue(flow['x-scalar-secret-client-secret'])\n const headers: Record<string, string> = { 'Content-Type': 'application/x-www-form-urlencoded' }\n const credentials = new URLSearchParams()\n if (clientSecret && flow['x-scalar-credentials-location'] !== 'body') {\n headers.Authorization = oauthClientAuthorization(clientId, clientSecret)\n } else {\n credentials.set('client_id', clientId)\n if (clientSecret) {\n credentials.set('client_secret', clientSecret)\n }\n }\n const deviceBody = new URLSearchParams(credentials)\n if (scopes.length) {\n deviceBody.set('scope', scopes.join(' '))\n }\n const response = await customFetch(endpoint(flow.deviceAuthorizationUrl), {\n method: 'POST',\n headers,\n body: deviceBody,\n signal: AbortSignal.any([options.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]),\n })\n const data: unknown = await response.json()\n options.signal.throwIfAborted()\n if (!isObject(data)) {\n throw new Error('Invalid device authorization response')\n }\n if (!response.ok) {\n throw new Error(String(data.error_description ?? data.error ?? 'Device authorization failed'))\n }\n if (\n typeof data.device_code !== 'string' ||\n !data.device_code ||\n typeof data.user_code !== 'string' ||\n !data.user_code ||\n typeof data.expires_in !== 'number' ||\n !Number.isFinite(data.expires_in) ||\n data.expires_in <= 0 ||\n (data.interval !== undefined &&\n (typeof data.interval !== 'number' || !Number.isFinite(data.interval) || data.interval < 0))\n ) {\n throw new Error('Invalid device authorization response')\n }\n const lifetime = Math.min(data.expires_in * 1000, MAX_TIMEOUT_MS)\n const expiresAt = Date.now() + lifetime\n const expiry = AbortSignal.timeout(lifetime)\n const signal = AbortSignal.any([options.signal, expiry])\n options.onPrompt({\n userCode: data.user_code,\n verificationUri: verificationUrl(data.verification_uri),\n ...(data.verification_uri_complete\n ? { verificationUriComplete: verificationUrl(data.verification_uri_complete) }\n : {}),\n })\n const body = new URLSearchParams(credentials)\n for (const [key, value] of Object.entries(flow['x-scalar-security-body'] ?? {})) {\n body.set(key, resolveValue(value))\n }\n body.set('grant_type', 'urn:ietf:params:oauth:grant-type:device_code')\n body.set('device_code', data.device_code)\n let interval = typeof data.interval === 'number' ? Math.max(1000, data.interval * 1000) : 5000\n try {\n while (Date.now() < expiresAt) {\n await waitForPoll(Math.min(interval, expiresAt - Date.now()), signal)\n signal.throwIfAborted()\n if (Date.now() >= expiresAt) {\n throw new Error('Device authorization expired')\n }\n // Connection timeouts require a lower polling frequency (RFC8628 section 3.5).\n const tokenResponse = await customFetch(endpoint(tokenUrl), {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]),\n }).catch((error: unknown) => {\n signal.throwIfAborted()\n if (error instanceof Error && error.name === 'TimeoutError') {\n return null\n }\n throw error\n })\n if (!tokenResponse) {\n // Saturating at expiry never schedules an earlier poll: the loop expires instead.\n interval = Math.min(interval * 2, expiresAt - Date.now())\n continue\n }\n const token: unknown = await tokenResponse.json()\n if (!isObject(token)) {\n throw new Error('Invalid device token response')\n }\n if (token.error === 'authorization_pending') {\n continue\n }\n if (token.error === 'slow_down') {\n interval = Math.min(interval + 5000, expiresAt - Date.now())\n continue\n }\n const accessToken = token[flow['x-tokenName'] || 'access_token']\n if (tokenResponse.ok && typeof accessToken === 'string' && accessToken) {\n return [\n null,\n { accessToken, ...(typeof token.refresh_token === 'string' ? { refreshToken: token.refresh_token } : {}) },\n ]\n }\n throw new Error(String(token.error_description ?? token.error ?? 'Failed to get an access token'))\n }\n throw new Error('Device authorization expired')\n } catch (error) {\n if (expiry.aborted && !options.signal.aborted) {\n throw new Error('Device authorization expired')\n }\n throw error\n }\n } catch (error) {\n return [error instanceof Error ? error : new Error('Device authorization failed', { cause: error }), null]\n }\n}\n"],"mappings":";;;;;;;;AAcA,IAAM,qBAAqB;AAE3B,IAAM,iBAAiB;;AAgBvB,IAAM,eAAe,cAAsB,WACzC,IAAI,SAAS,SAAS,WAAW;CAC/B,OAAO,eAAe;CACtB,MAAM,cAAoB;EACxB,aAAa,KAAK;EAClB,OAAO,OAAO,MAAM;CACtB;CACA,MAAM,QAAQ,iBAAiB;EAC7B,OAAO,oBAAoB,SAAS,KAAK;EACzC,QAAQ;CACV,GAAG,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;CACF,SAAS,OAAO;EACd,OAAO,CAAC,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,+BAA+B,EAAE,OAAO,MAAM,CAAC,GAAG,IAAI;CAC3G;AACF"}
1
+ {"version":3,"file":"oauth-device-authorization.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth-device-authorization.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { isObject } from '@scalar/helpers/object/is-object'\nimport { replaceEnvVariables } from '@scalar/helpers/regex/replace-variables'\nimport { isAllowedOAuthUrl } from '@scalar/helpers/url/is-allowed-oauth-url'\nimport { makeUrlAbsolute } from '@scalar/helpers/url/make-url-absolute'\nimport { redirectToProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport type { OAuthFlowDeviceAuthorizationSecret } from '@scalar/workspace-store/request-example'\nimport type { ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\nimport { type OAuth2Tokens, getActiveServerBase } from './oauth'\nimport { oauthClientAuthorization } from './oauth-client-authorization'\n\nconst REQUEST_TIMEOUT_MS = 30_000\n// Maximum delay supported by the browser timer API.\nconst MAX_TIMEOUT_MS = 2_147_483_647\n\n/** Information the user needs to approve a device without exposing the device code. */\nexport type DeviceAuthorizationPrompt = {\n userCode: string\n verificationUri: string\n verificationUriComplete?: string\n}\n\n/** Device flow UI and cancellation hooks. */\nexport type DeviceAuthorizationOptions = {\n onPrompt: (prompt: DeviceAuthorizationPrompt) => void\n signal: AbortSignal\n}\n\n/** Waits between polls, releasing the timer immediately when cancelled or expired. */\nconst waitForPoll = (milliseconds: number, signal: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n signal.throwIfAborted()\n const abort = (): void => {\n clearTimeout(timer)\n reject(signal.reason)\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', abort)\n resolve()\n }, milliseconds)\n signal.addEventListener('abort', abort, { once: true })\n })\n\nconst verificationUrl = (value: unknown): string => {\n if (typeof value !== 'string') {\n throw new Error('Missing device verification URL')\n }\n const url = new URL(value)\n if (!isAllowedOAuthUrl(url)) {\n throw new Error('Device verification URL must use HTTPS or HTTP for local development URLs')\n }\n return url.href\n}\n\n/** Performs the RFC8628 device grant, respecting expiry, pending responses, and polling backoff. */\nexport const authorizeDevice = async (\n flow: OAuthFlowDeviceAuthorizationSecret,\n scopes: string[],\n server: ServerObject | null,\n proxyUrl: string,\n environment: Record<string, string>,\n customFetch: CustomFetch = fetch,\n options?: DeviceAuthorizationOptions,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n try {\n if (!options) {\n throw new Error('Device authorization requires a verification prompt')\n }\n const resolveValue = (value: string): string => replaceEnvVariables(value, environment)\n const endpoint = (value: string): string =>\n redirectToProxy(proxyUrl, makeUrlAbsolute(resolveValue(value), getActiveServerBase(server, environment)))\n const tokenUrl = flow['x-scalar-secret-token-url'] ?? flow.tokenUrl\n if (!tokenUrl.trim()) {\n throw new Error('Token URL is required')\n }\n const clientId = resolveValue(flow['x-scalar-secret-client-id'])\n const clientSecret = resolveValue(flow['x-scalar-secret-client-secret'])\n const headers: Record<string, string> = { 'Content-Type': 'application/x-www-form-urlencoded' }\n const credentials = new URLSearchParams()\n if (clientSecret && flow['x-scalar-credentials-location'] !== 'body') {\n headers.Authorization = oauthClientAuthorization(clientId, clientSecret)\n } else {\n credentials.set('client_id', clientId)\n if (clientSecret) {\n credentials.set('client_secret', clientSecret)\n }\n }\n const deviceBody = new URLSearchParams(credentials)\n if (scopes.length) {\n deviceBody.set('scope', scopes.join(' '))\n }\n const response = await customFetch(endpoint(flow.deviceAuthorizationUrl), {\n method: 'POST',\n headers,\n body: deviceBody,\n signal: AbortSignal.any([options.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]),\n })\n const data: unknown = await response.json()\n options.signal.throwIfAborted()\n if (!isObject(data)) {\n throw new Error('Invalid device authorization response')\n }\n if (!response.ok) {\n throw new Error(String(data.error_description ?? data.error ?? 'Device authorization failed'))\n }\n if (\n typeof data.device_code !== 'string' ||\n !data.device_code ||\n typeof data.user_code !== 'string' ||\n !data.user_code ||\n typeof data.expires_in !== 'number' ||\n !Number.isFinite(data.expires_in) ||\n data.expires_in <= 0 ||\n (data.interval !== undefined &&\n (typeof data.interval !== 'number' || !Number.isFinite(data.interval) || data.interval < 0))\n ) {\n throw new Error('Invalid device authorization response')\n }\n const lifetime = Math.min(data.expires_in * 1000, MAX_TIMEOUT_MS)\n const expiresAt = Date.now() + lifetime\n const expiry = AbortSignal.timeout(lifetime)\n const signal = AbortSignal.any([options.signal, expiry])\n options.onPrompt({\n userCode: data.user_code,\n verificationUri: verificationUrl(data.verification_uri),\n ...(data.verification_uri_complete\n ? { verificationUriComplete: verificationUrl(data.verification_uri_complete) }\n : {}),\n })\n const body = new URLSearchParams(credentials)\n for (const [key, value] of Object.entries(flow['x-scalar-security-body'] ?? {})) {\n body.set(key, resolveValue(value))\n }\n body.set('grant_type', 'urn:ietf:params:oauth:grant-type:device_code')\n body.set('device_code', data.device_code)\n let interval = typeof data.interval === 'number' ? Math.max(1000, data.interval * 1000) : 5000\n try {\n while (Date.now() < expiresAt) {\n await waitForPoll(Math.min(interval, expiresAt - Date.now()), signal)\n signal.throwIfAborted()\n if (Date.now() >= expiresAt) {\n throw new Error('Device authorization expired')\n }\n // Connection timeouts require a lower polling frequency (RFC8628 section 3.5).\n const tokenResponse = await customFetch(endpoint(tokenUrl), {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]),\n }).catch((error: unknown) => {\n signal.throwIfAborted()\n if (error instanceof Error && error.name === 'TimeoutError') {\n return null\n }\n throw error\n })\n if (!tokenResponse) {\n // Saturating at expiry never schedules an earlier poll: the loop expires instead.\n interval = Math.min(interval * 2, expiresAt - Date.now())\n continue\n }\n const token: unknown = await tokenResponse.json()\n if (!isObject(token)) {\n throw new Error('Invalid device token response')\n }\n if (token.error === 'authorization_pending') {\n continue\n }\n if (token.error === 'slow_down') {\n interval = Math.min(interval + 5000, expiresAt - Date.now())\n continue\n }\n const accessToken = token[flow['x-tokenName'] || 'access_token']\n if (tokenResponse.ok && typeof accessToken === 'string' && accessToken) {\n return [\n null,\n { accessToken, ...(typeof token.refresh_token === 'string' ? { refreshToken: token.refresh_token } : {}) },\n ]\n }\n throw new Error(String(token.error_description ?? token.error ?? 'Failed to get an access token'))\n }\n throw new Error('Device authorization expired')\n } catch (error) {\n if (expiry.aborted && !options.signal.aborted) {\n throw new Error('Device authorization expired')\n }\n throw error\n }\n } catch (error) {\n return [error instanceof Error ? error : new Error('Device authorization failed', { cause: error }), null]\n }\n}\n"],"mappings":";;;;;;;;AAcA,IAAM,qBAAqB;AAE3B,IAAM,iBAAiB;;AAgBvB,IAAM,eAAe,cAAsB,WACzC,IAAI,SAAS,SAAS,WAAW;CAC/B,OAAO,eAAe;CACtB,MAAM,cAAoB;EACxB,aAAa,KAAK;EAClB,OAAO,OAAO,MAAM;CACtB;CACA,MAAM,QAAQ,iBAAiB;EAC7B,OAAO,oBAAoB,SAAS,KAAK;EACzC,QAAQ;CACV,GAAG,YAAY;CACf,OAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;AACxD,CAAC;AAEH,IAAM,mBAAmB,UAA2B;CAClD,IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,MAAM,iCAAiC;CAEnD,MAAM,MAAM,IAAI,IAAI,KAAK;CACzB,IAAI,CAAC,kBAAkB,GAAG,GACxB,MAAM,IAAI,MAAM,2EAA2E;CAE7F,OAAO,IAAI;AACb;;AAGA,IAAa,kBAAkB,OAC7B,MACA,QACA,QACA,UACA,aACA,cAA2B,OAC3B,YACyC;CACzC,IAAI;EACF,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,qDAAqD;EAEvE,MAAM,gBAAgB,UAA0B,oBAAoB,OAAO,WAAW;EACtF,MAAM,YA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,CAAC,CA4FrC,CAAA"}
@@ -4,6 +4,7 @@ import { authorizeDevice } from "./oauth-device-authorization.js";
4
4
  import { getServerVariables } from "@scalar/workspace-store/request-example";
5
5
  import { makeUrlAbsolute } from "@scalar/helpers/url/make-url-absolute";
6
6
  import { replaceEnvVariables, replacePathVariables } from "@scalar/helpers/regex/replace-variables";
7
+ import { isAllowedOAuthUrl } from "@scalar/helpers/url/is-allowed-oauth-url";
7
8
  import { isRelativePath } from "@scalar/helpers/url/is-relative-path";
8
9
  import { shouldUseProxy } from "@scalar/helpers/url/redirect-to-proxy";
9
10
  import { fromUint8Array } from "js-base64";
@@ -69,6 +70,7 @@ var authorizeOauth2 = async (flows, type, selectedScopes, activeServer, proxyUrl
69
70
  if (!authUrl.trim()) return [/* @__PURE__ */ new Error("Authorization URL is required"), null];
70
71
  const authorizationUrl = makeUrlAbsolute(authUrl, getActiveServerBase(activeServer, environmentVariables));
71
72
  const url = new URL(authorizationUrl);
73
+ if (!isAllowedOAuthUrl(url)) return [/* @__PURE__ */ new Error("Authorization URL must use HTTPS or HTTP for local development URLs"), null];
72
74
  /** Special PKCE state */
73
75
  let pkce = null;
74
76
  if (type === "implicit") url.searchParams.set("response_type", "token");