@backstage/backend-defaults 0.18.0 → 0.18.1-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/dist/CreateBackend.cjs.js +5 -2
- package/dist/CreateBackend.cjs.js.map +1 -1
- package/dist/PackageDiscoveryService.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/actions/DefaultActionsService.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/actions/actionsServiceFactory.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/actionsRegistry/DefaultActionsRegistryService.cjs.js +6 -0
- package/dist/alpha/entrypoints/actionsRegistry/DefaultActionsRegistryService.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/actionsRegistry/actionFilters.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/actionsRegistry/actionsRegistryServiceFactory.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/instanceMetadata/instanceMetadataServiceFactory.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/metrics/DefaultMetricsService.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/metrics/metricsServiceFactory.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/tracing/DefaultTracingService.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/tracing/tracingServiceFactory.cjs.js.map +1 -1
- package/dist/discoveryFeatureLoader.cjs.js.map +1 -1
- package/dist/entrypoints/auditor/DefaultAuditorService.cjs.js.map +1 -1
- package/dist/entrypoints/auditor/WinstonRootAuditorService.cjs.js.map +1 -1
- package/dist/entrypoints/auditor/auditorServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/auditor/utils.cjs.js.map +1 -1
- package/dist/entrypoints/auth/DefaultAuthService.cjs.js.map +1 -1
- package/dist/entrypoints/auth/JwksClient.cjs.js.map +1 -1
- package/dist/entrypoints/auth/authServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/auth/external/ExternalAuthTokenHandler.cjs.js.map +1 -1
- package/dist/entrypoints/auth/external/helpers.cjs.js.map +1 -1
- package/dist/entrypoints/auth/external/jwks.cjs.js.map +1 -1
- package/dist/entrypoints/auth/external/legacy.cjs.js.map +1 -1
- package/dist/entrypoints/auth/external/static.cjs.js.map +1 -1
- package/dist/entrypoints/auth/helpers.cjs.js.map +1 -1
- package/dist/entrypoints/auth/plugin/PluginTokenHandler.cjs.js.map +1 -1
- package/dist/entrypoints/auth/plugin/keys/DatabaseKeyStore.cjs.js.map +1 -1
- package/dist/entrypoints/auth/plugin/keys/DatabasePluginKeySource.cjs.js.map +1 -1
- package/dist/entrypoints/auth/plugin/keys/StaticConfigPluginKeySource.cjs.js.map +1 -1
- package/dist/entrypoints/auth/plugin/keys/createPluginKeySource.cjs.js.map +1 -1
- package/dist/entrypoints/auth/user/UserTokenHandler.cjs.js.map +1 -1
- package/dist/entrypoints/cache/CacheClient.cjs.js.map +1 -1
- package/dist/entrypoints/cache/CacheManager.cjs.js.map +1 -1
- package/dist/entrypoints/cache/cacheServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/cache/providers/infinispan/InfinispanKeyvStore.cjs.js.map +1 -1
- package/dist/entrypoints/cache/providers/infinispan/InfinispanOptionsMapper.cjs.js.map +1 -1
- package/dist/entrypoints/cache/types.cjs.js.map +1 -1
- package/dist/entrypoints/database/DatabaseManager.cjs.js.map +1 -1
- package/dist/entrypoints/database/connectors/defaultNameOverride.cjs.js.map +1 -1
- package/dist/entrypoints/database/connectors/mergeDatabaseConfig.cjs.js.map +1 -1
- package/dist/entrypoints/database/connectors/mysql.cjs.js.map +1 -1
- package/dist/entrypoints/database/connectors/postgres.cjs.js +68 -6
- package/dist/entrypoints/database/connectors/postgres.cjs.js.map +1 -1
- package/dist/entrypoints/database/connectors/sqlite3.cjs.js.map +1 -1
- package/dist/entrypoints/database/databaseServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/discovery/HostDiscovery.cjs.js.map +1 -1
- package/dist/entrypoints/discovery/SrvResolvers.cjs.js.map +1 -1
- package/dist/entrypoints/discovery/discoveryServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/discovery/parsing.cjs.js.map +1 -1
- package/dist/entrypoints/httpAuth/httpAuthServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/httpRouter/http/createAuthIntegrationRouter.cjs.js.map +1 -1
- package/dist/entrypoints/httpRouter/http/createCookieAuthRefreshMiddleware.cjs.js.map +1 -1
- package/dist/entrypoints/httpRouter/http/createCredentialsBarrier.cjs.js.map +1 -1
- package/dist/entrypoints/httpRouter/http/createLifecycleMiddleware.cjs.js.map +1 -1
- package/dist/entrypoints/httpRouter/http/createRateLimitMiddleware.cjs.js.map +1 -1
- package/dist/entrypoints/httpRouter/httpRouterServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/lifecycle/lifecycleServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/logger/loggerServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/permissions/permissionsServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/permissionsRegistry/permissionsRegistryServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/rootConfig/createConfigSecretEnumerator.cjs.js.map +1 -1
- package/dist/entrypoints/rootConfig/rootConfigServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/rootHealth/rootHealthServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/DefaultRootHttpRouter.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/createHealthRouter.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/http/MiddlewareFactory.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/http/applyInternalErrorFilter.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/http/config.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/http/createHttpServer.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/http/getGeneratedCertificate.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/http/readCorsOptions.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/http/readHelmetOptions.cjs.js.map +1 -1
- package/dist/entrypoints/rootHttpRouter/rootHttpRouterServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/rootLifecycle/rootLifecycleServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/rootLogger/WinstonLogger.cjs.js.map +1 -1
- package/dist/entrypoints/rootLogger/config.cjs.js.map +1 -1
- package/dist/entrypoints/rootLogger/rootLoggerServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/rootLogger/types.cjs.js.map +1 -1
- package/dist/entrypoints/rootLogger/utils.cjs.js.map +1 -1
- package/dist/entrypoints/rootSystemMetadata/lib/DefaultRootSystemMetadataService.cjs.js.map +1 -1
- package/dist/entrypoints/rootSystemMetadata/rootSystemMetadataServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/database/migrateBackendTasks.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/database/tables.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/DefaultSchedulerService.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/LocalTaskWorker.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/PluginTaskSchedulerImpl.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/PluginTaskSchedulerJanitor.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/TaskStatePoller.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/TaskWorker.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/types.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/lib/util.cjs.js.map +1 -1
- package/dist/entrypoints/scheduler/schedulerServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/AwsCodeCommitUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/AwsS3UrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/AzureBlobStorageUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/AzureUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/BitbucketCloudUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/BitbucketServerUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/FetchUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/GerritUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/GiteaUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/GithubUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/GitlabUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/GoogleGcsUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/HarnessUrlReader.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/ReadUrlResponseFactory.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/UrlReaderPredicateMux.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/UrlReaders.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/tree/ReadTreeResponseFactory.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/tree/ReadableArrayResponse.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/tree/TarArchiveResponse.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/tree/ZipArchiveResponse.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/tree/util.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/util.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/urlReaderServiceFactory.cjs.js.map +1 -1
- package/dist/entrypoints/userInfo/CachedUserInfoService.cjs.js.map +1 -1
- package/dist/entrypoints/userInfo/DefaultUserInfoService.cjs.js.map +1 -1
- package/dist/entrypoints/userInfo/userInfoServiceFactory.cjs.js.map +1 -1
- package/dist/index.d.ts +13 -1
- package/dist/lib/RateLimitStoreFactory.cjs.js.map +1 -1
- package/dist/lib/escapeRegExp.cjs.js.map +1 -1
- package/dist/lib/rateLimitMiddleware.cjs.js.map +1 -1
- package/dist/package.json.cjs.js +1 -1
- package/dist/package.json.cjs.js.map +1 -1
- package/package.json +18 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HostDiscovery.cjs.js","sources":["../../../src/entrypoints/discovery/HostDiscovery.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport {\n DiscoveryService,\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { readHttpServerOptions } from '../rootHttpRouter/http/config';\nimport { SrvResolvers } from './SrvResolvers';\nimport { trimEnd } from 'lodash';\nimport { getEndpoints } from './parsing';\n\ntype Resolver = (pluginId: string) => Promise<string>;\n\n/**\n * A list of target base URLs and their associated plugins.\n *\n * @public\n */\nexport interface HostDiscoveryEndpoint {\n /**\n * The target base URL to use for the given set of plugins. Note that this\n * needs to be a full URL _including_ the protocol and path parts that fully\n * address the root of a plugin's API endpoints.\n *\n * @remarks\n *\n * Can be either a single URL or an object where you can explicitly give a\n * dedicated URL for internal (as seen from the backend) and/or external (as\n * seen from the frontend) lookups.\n *\n * The default behavior is to use the backend base URL for external lookups,\n * and a URL formed from the `.listen` and `.https` configs for internal\n * lookups. Adding discovery endpoints as described here overrides one or both\n * of those behaviors for a given set of plugins.\n *\n * URLs can be in the form of a regular HTTP or HTTPS URL if you are using\n * A/AAAA/CNAME records or IP addresses. Specifically for internal URLs, if\n * you add `+src` to the protocol part then the hostname is treated as an SRV\n * record name and resolved. For example, if you pass in\n * `http+srv://<record>/path` then the record part is resolved into an\n * actual host and port (with random weighted choice as usual when there is\n * more than one match).\n *\n * Any strings with `{{pluginId}}` or `{{ pluginId }}` placeholders in them\n * will have them replaced with the plugin ID.\n *\n * Example URLs:\n *\n * - `https://internal.example.com/secure/api/{{ pluginId }}`\n * - `http+srv://backstage-plugin-{{pluginId}}.http.services.company.net/api/{{pluginId}}`\n * (can only be used in the `internal` key)\n */\n target:\n | string\n | {\n internal?: string;\n external?: string;\n };\n\n /**\n * Array of plugins which use that target base URL.\n *\n * The special value `*` can be used to match all plugins.\n */\n plugins: string[];\n}\n\n/**\n * Options for the {@link HostDiscovery} class.\n *\n * @public\n */\nexport interface HostDiscoveryOptions {\n /**\n * The logger to use.\n */\n logger: LoggerService;\n\n /**\n * A default set of endpoints to use.\n *\n * @remarks\n *\n * These endpoints have lower priority than any that are defined in\n * app-config, but higher priority than the fallback ones.\n *\n * This parameter is useful for example if you want to provide a shared\n * library of core services to your plugin developers, which is set up for the\n * default behaviors in your org. This alleviates the need for replicating any\n * given set of endpoint config in every backend that you deploy.\n */\n defaultEndpoints?: HostDiscoveryEndpoint[];\n}\n\n/**\n * A basic {@link @backstage/backend-plugin-api#DiscoveryService} implementation\n * that can handle plugins that are hosted in a single or multiple deployments.\n *\n * @public\n * @remarks\n *\n * Configuration is read from the `backend` config section, specifically the\n * `.baseUrl` for discovering the external URL, and the `.listen` and `.https`\n * config for the internal one. The fixed base path for these is `/api`, meaning\n * for example the default full internal path for the `catalog` plugin typically\n * will be `http://localhost:7007/api/catalog`.\n *\n * Those defaults can be overridden by providing a target and corresponding\n * plugins in `discovery.endpoints`, e.g.:\n *\n * ```yaml\n * discovery:\n * endpoints:\n * # Set a static internal and external base URL for a plugin\n * - target: https://internal.example.com/internal-catalog\n * plugins: [catalog]\n * # Sets a dynamic internal and external base URL pattern for two plugins\n * - target: https://internal.example.com/secure/api/{{pluginId}}\n * plugins: [auth, permission]\n * # Sets a dynamic base URL pattern for only the internal resolution for all\n * # other plugins, while leaving the external resolution unaffected\n * - target:\n * internal: http+srv://backstage-plugin-{{pluginId}}.http.${SERVICE_DOMAIN}/api/{{pluginId}}\n * plugins: [*]\n * ```\n */\nexport class HostDiscovery implements DiscoveryService {\n #srvResolver: SrvResolvers;\n #internalResolvers: Map<string, Resolver> = new Map();\n #externalResolvers: Map<string, Resolver> = new Map();\n #internalFallbackResolver: Resolver = async () => {\n throw new Error('Not initialized');\n };\n #externalFallbackResolver: Resolver = async () => {\n throw new Error('Not initialized');\n };\n\n static fromConfig(config: RootConfigService, options?: HostDiscoveryOptions) {\n // The getExternalBaseUrl implementation relies on the backend base URL\n // being a valid, non-local URL that others will be able to route to.\n const baseUrl = config.getString('backend.baseUrl');\n try {\n const { hostname } = new URL(baseUrl);\n const isLocalhost =\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === '::1' ||\n hostname === '::';\n if (isLocalhost && process.env.NODE_ENV === 'production') {\n options?.logger?.warn(\n `backend.baseUrl is set to a localhost URL and NODE_ENV is '${process.env.NODE_ENV}'. This is likely a misconfiguration — localhost URLs are not reachable by other services in a deployed environment. Prefer setting it to a routable URL that can be resolved and reached both by your app and by other plugin deployments / services.`,\n );\n }\n } catch {\n options?.logger?.warn(\n `backend.baseUrl config value '${baseUrl}' does not appear to be a valid URL.`,\n );\n }\n\n const discovery = new HostDiscovery(new SrvResolvers());\n\n discovery.#updateResolvers(config, options?.defaultEndpoints);\n config.subscribe?.(() => {\n try {\n discovery.#updateResolvers(config, options?.defaultEndpoints);\n } catch (e) {\n options?.logger.error(`Failed to update discovery service: ${e}`);\n }\n });\n\n return discovery;\n }\n\n private constructor(srvResolver: SrvResolvers) {\n this.#srvResolver = srvResolver;\n this.#internalResolvers = new Map();\n this.#externalResolvers = new Map();\n this.#internalFallbackResolver = () => {\n throw new Error('Not initialized');\n };\n this.#externalFallbackResolver = () => {\n throw new Error('Not initialized');\n };\n }\n\n async getBaseUrl(pluginId: string): Promise<string> {\n const resolver =\n this.#internalResolvers.get(pluginId) ??\n this.#internalResolvers.get('*') ??\n this.#internalFallbackResolver;\n return await resolver(pluginId);\n }\n\n async getExternalBaseUrl(pluginId: string): Promise<string> {\n const resolver =\n this.#externalResolvers.get(pluginId) ??\n this.#externalResolvers.get('*') ??\n this.#externalFallbackResolver;\n return await resolver(pluginId);\n }\n\n #updateResolvers(config: Config, defaultEndpoints?: HostDiscoveryEndpoint[]) {\n this.#updateFallbackResolvers(config);\n this.#updatePluginResolvers(config, defaultEndpoints);\n }\n\n #updateFallbackResolvers(config: Config) {\n const backendBaseUrl = trimEnd(config.getString('backend.baseUrl'), '/');\n\n const {\n listen: { host: listenHost = '::', port: listenPort },\n } = readHttpServerOptions(config.getConfig('backend'));\n const protocol = config.has('backend.https') ? 'https' : 'http';\n\n // Translate bind-all to localhost, and support IPv6\n let host = listenHost;\n if (host === '::' || host === '') {\n // We use localhost instead of ::1, since IPv6-compatible systems should default\n // to using IPv6 when they see localhost, but if the system doesn't support IPv6\n // things will still work.\n host = 'localhost';\n } else if (host === '0.0.0.0') {\n host = '127.0.0.1';\n }\n if (host.includes(':')) {\n host = `[${host}]`;\n }\n\n this.#internalFallbackResolver = this.#makeResolver(\n `${protocol}://${host}:${listenPort}/api/{{pluginId}}`,\n false,\n );\n this.#externalFallbackResolver = this.#makeResolver(\n `${backendBaseUrl}/api/{{pluginId}}`,\n false,\n );\n }\n\n #updatePluginResolvers(\n config: Config,\n defaultEndpoints?: HostDiscoveryEndpoint[],\n ) {\n // Start out with the default endpoints, if any\n const endpoints = defaultEndpoints?.slice() ?? [];\n\n // Allow config to override the default endpoints\n endpoints.push(...getEndpoints(config));\n\n // Build up a new set of resolvers\n const internalResolvers: Map<string, Resolver> = new Map();\n const externalResolvers: Map<string, Resolver> = new Map();\n for (const { target, plugins } of endpoints) {\n let internalResolver: Resolver | undefined;\n let externalResolver: Resolver | undefined;\n\n if (typeof target === 'string') {\n internalResolver = externalResolver = this.#makeResolver(target, false);\n } else {\n if (target.internal) {\n internalResolver = this.#makeResolver(target.internal, true);\n }\n if (target.external) {\n externalResolver = this.#makeResolver(target.external, false);\n }\n }\n\n if (internalResolver) {\n for (const pluginId of plugins) {\n internalResolvers.set(pluginId, internalResolver);\n }\n }\n if (externalResolver) {\n for (const pluginId of plugins) {\n externalResolvers.set(pluginId, externalResolver);\n }\n }\n }\n\n // Only persist if no errors were thrown above\n this.#internalResolvers = internalResolvers;\n this.#externalResolvers = externalResolvers;\n }\n\n #makeResolver(urlPattern: string, allowSrv: boolean): Resolver {\n const withPluginId = (pluginId: string, url: string) => {\n return url.replace(\n /\\{\\{\\s*pluginId\\s*\\}\\}/g,\n encodeURIComponent(pluginId),\n );\n };\n\n if (!this.#srvResolver.isSrvUrl(urlPattern)) {\n return async pluginId => withPluginId(pluginId, urlPattern);\n }\n\n if (!allowSrv) {\n throw new Error(\n `SRV resolver URLs cannot be used in the target for external endpoints`,\n );\n }\n\n const lazyResolvers = new Map<string, () => Promise<string>>();\n return async pluginId => {\n let lazyResolver = lazyResolvers.get(pluginId);\n if (!lazyResolver) {\n lazyResolver = this.#srvResolver.getResolver(\n withPluginId(pluginId, urlPattern),\n );\n lazyResolvers.set(pluginId, lazyResolver);\n }\n return await lazyResolver();\n };\n }\n}\n"],"names":["SrvResolvers","config","trimEnd","readHttpServerOptions","getEndpoints"],"mappings":";;;;;;;AA8IO,MAAM,aAAA,CAA0C;AAAA,EACrD,YAAA;AAAA,EACA,kBAAA,uBAAgD,GAAA,EAAI;AAAA,EACpD,kBAAA,uBAAgD,GAAA,EAAI;AAAA,EACpD,4BAAsC,YAAY;AAChD,IAAA,MAAM,IAAI,MAAM,iBAAiB,CAAA;AAAA,EACnC,CAAA;AAAA,EACA,4BAAsC,YAAY;AAChD,IAAA,MAAM,IAAI,MAAM,iBAAiB,CAAA;AAAA,EACnC,CAAA;AA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MAAM,IAAI,KAAA;AAAA,QACR,CAAA,qEAAA;AAAA,OACF;AAAA,IACF;AAEA,IAAA,MAAM,aAAA,uBAAoB,GAAA,EAAmC;AAC7D,IAAA,OAAO,OAAM,QAAA,KAAY;AACvB,MAAA,IAAI,YAAA,GAAe,aAAA,CAAc,GAAA,CAAI,QAAQ,CAAA;AAC7C,MAAA,IAAI,CAAC,YAAA,EAAc;AACjB,QAAA,YAAA,GAAe,KAAK,YAAA,CAAa,WAAA;AAAA,UAC/B,YAAA,CAAa,UAAU,UAAU;AAAA,SACnC;AACA,QAAA,aAAA,CAAc,GAAA,CAAI,UAAU,YAAY,CAAA;AAAA,MAC1C;AACA,MAAA,OAAO,MAAM,YAAA,EAAa;AAAA,IAC5B,CAAA;AAAA,EACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"HostDiscovery.cjs.js","sources":["../../../src/entrypoints/discovery/HostDiscovery.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport {\n DiscoveryService,\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { readHttpServerOptions } from '../rootHttpRouter/http/config';\nimport { SrvResolvers } from './SrvResolvers';\nimport { trimEnd } from 'lodash';\nimport { getEndpoints } from './parsing';\n\ntype Resolver = (pluginId: string) => Promise<string>;\n\n/**\n * A list of target base URLs and their associated plugins.\n *\n * @public\n */\nexport interface HostDiscoveryEndpoint {\n /**\n * The target base URL to use for the given set of plugins. Note that this\n * needs to be a full URL _including_ the protocol and path parts that fully\n * address the root of a plugin's API endpoints.\n *\n * @remarks\n *\n * Can be either a single URL or an object where you can explicitly give a\n * dedicated URL for internal (as seen from the backend) and/or external (as\n * seen from the frontend) lookups.\n *\n * The default behavior is to use the backend base URL for external lookups,\n * and a URL formed from the `.listen` and `.https` configs for internal\n * lookups. Adding discovery endpoints as described here overrides one or both\n * of those behaviors for a given set of plugins.\n *\n * URLs can be in the form of a regular HTTP or HTTPS URL if you are using\n * A/AAAA/CNAME records or IP addresses. Specifically for internal URLs, if\n * you add `+src` to the protocol part then the hostname is treated as an SRV\n * record name and resolved. For example, if you pass in\n * `http+srv://<record>/path` then the record part is resolved into an\n * actual host and port (with random weighted choice as usual when there is\n * more than one match).\n *\n * Any strings with `{{pluginId}}` or `{{ pluginId }}` placeholders in them\n * will have them replaced with the plugin ID.\n *\n * Example URLs:\n *\n * - `https://internal.example.com/secure/api/{{ pluginId }}`\n * - `http+srv://backstage-plugin-{{pluginId}}.http.services.company.net/api/{{pluginId}}`\n * (can only be used in the `internal` key)\n */\n target:\n | string\n | {\n internal?: string;\n external?: string;\n };\n\n /**\n * Array of plugins which use that target base URL.\n *\n * The special value `*` can be used to match all plugins.\n */\n plugins: string[];\n}\n\n/**\n * Options for the {@link HostDiscovery} class.\n *\n * @public\n */\nexport interface HostDiscoveryOptions {\n /**\n * The logger to use.\n */\n logger: LoggerService;\n\n /**\n * A default set of endpoints to use.\n *\n * @remarks\n *\n * These endpoints have lower priority than any that are defined in\n * app-config, but higher priority than the fallback ones.\n *\n * This parameter is useful for example if you want to provide a shared\n * library of core services to your plugin developers, which is set up for the\n * default behaviors in your org. This alleviates the need for replicating any\n * given set of endpoint config in every backend that you deploy.\n */\n defaultEndpoints?: HostDiscoveryEndpoint[];\n}\n\n/**\n * A basic {@link @backstage/backend-plugin-api#DiscoveryService} implementation\n * that can handle plugins that are hosted in a single or multiple deployments.\n *\n * @public\n * @remarks\n *\n * Configuration is read from the `backend` config section, specifically the\n * `.baseUrl` for discovering the external URL, and the `.listen` and `.https`\n * config for the internal one. The fixed base path for these is `/api`, meaning\n * for example the default full internal path for the `catalog` plugin typically\n * will be `http://localhost:7007/api/catalog`.\n *\n * Those defaults can be overridden by providing a target and corresponding\n * plugins in `discovery.endpoints`, e.g.:\n *\n * ```yaml\n * discovery:\n * endpoints:\n * # Set a static internal and external base URL for a plugin\n * - target: https://internal.example.com/internal-catalog\n * plugins: [catalog]\n * # Sets a dynamic internal and external base URL pattern for two plugins\n * - target: https://internal.example.com/secure/api/{{pluginId}}\n * plugins: [auth, permission]\n * # Sets a dynamic base URL pattern for only the internal resolution for all\n * # other plugins, while leaving the external resolution unaffected\n * - target:\n * internal: http+srv://backstage-plugin-{{pluginId}}.http.${SERVICE_DOMAIN}/api/{{pluginId}}\n * plugins: [*]\n * ```\n */\nexport class HostDiscovery implements DiscoveryService {\n #srvResolver: SrvResolvers;\n #internalResolvers: Map<string, Resolver> = new Map();\n #externalResolvers: Map<string, Resolver> = new Map();\n #internalFallbackResolver: Resolver = async () => {\n throw new Error('Not initialized');\n };\n #externalFallbackResolver: Resolver = async () => {\n throw new Error('Not initialized');\n };\n\n static fromConfig(config: RootConfigService, options?: HostDiscoveryOptions) {\n // The getExternalBaseUrl implementation relies on the backend base URL\n // being a valid, non-local URL that others will be able to route to.\n const baseUrl = config.getString('backend.baseUrl');\n try {\n const { hostname } = new URL(baseUrl);\n const isLocalhost =\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === '::1' ||\n hostname === '::';\n if (isLocalhost && process.env.NODE_ENV === 'production') {\n options?.logger?.warn(\n `backend.baseUrl is set to a localhost URL and NODE_ENV is '${process.env.NODE_ENV}'. This is likely a misconfiguration — localhost URLs are not reachable by other services in a deployed environment. Prefer setting it to a routable URL that can be resolved and reached both by your app and by other plugin deployments / services.`,\n );\n }\n } catch {\n options?.logger?.warn(\n `backend.baseUrl config value '${baseUrl}' does not appear to be a valid URL.`,\n );\n }\n\n const discovery = new HostDiscovery(new SrvResolvers());\n\n discovery.#updateResolvers(config, options?.defaultEndpoints);\n config.subscribe?.(() => {\n try {\n discovery.#updateResolvers(config, options?.defaultEndpoints);\n } catch (e) {\n options?.logger.error(`Failed to update discovery service: ${e}`);\n }\n });\n\n return discovery;\n }\n\n private constructor(srvResolver: SrvResolvers) {\n this.#srvResolver = srvResolver;\n this.#internalResolvers = new Map();\n this.#externalResolvers = new Map();\n this.#internalFallbackResolver = () => {\n throw new Error('Not initialized');\n };\n this.#externalFallbackResolver = () => {\n throw new Error('Not initialized');\n };\n }\n\n async getBaseUrl(pluginId: string): Promise<string> {\n const resolver =\n this.#internalResolvers.get(pluginId) ??\n this.#internalResolvers.get('*') ??\n this.#internalFallbackResolver;\n return await resolver(pluginId);\n }\n\n async getExternalBaseUrl(pluginId: string): Promise<string> {\n const resolver =\n this.#externalResolvers.get(pluginId) ??\n this.#externalResolvers.get('*') ??\n this.#externalFallbackResolver;\n return await resolver(pluginId);\n }\n\n #updateResolvers(config: Config, defaultEndpoints?: HostDiscoveryEndpoint[]) {\n this.#updateFallbackResolvers(config);\n this.#updatePluginResolvers(config, defaultEndpoints);\n }\n\n #updateFallbackResolvers(config: Config) {\n const backendBaseUrl = trimEnd(config.getString('backend.baseUrl'), '/');\n\n const {\n listen: { host: listenHost = '::', port: listenPort },\n } = readHttpServerOptions(config.getConfig('backend'));\n const protocol = config.has('backend.https') ? 'https' : 'http';\n\n // Translate bind-all to localhost, and support IPv6\n let host = listenHost;\n if (host === '::' || host === '') {\n // We use localhost instead of ::1, since IPv6-compatible systems should default\n // to using IPv6 when they see localhost, but if the system doesn't support IPv6\n // things will still work.\n host = 'localhost';\n } else if (host === '0.0.0.0') {\n host = '127.0.0.1';\n }\n if (host.includes(':')) {\n host = `[${host}]`;\n }\n\n this.#internalFallbackResolver = this.#makeResolver(\n `${protocol}://${host}:${listenPort}/api/{{pluginId}}`,\n false,\n );\n this.#externalFallbackResolver = this.#makeResolver(\n `${backendBaseUrl}/api/{{pluginId}}`,\n false,\n );\n }\n\n #updatePluginResolvers(\n config: Config,\n defaultEndpoints?: HostDiscoveryEndpoint[],\n ) {\n // Start out with the default endpoints, if any\n const endpoints = defaultEndpoints?.slice() ?? [];\n\n // Allow config to override the default endpoints\n endpoints.push(...getEndpoints(config));\n\n // Build up a new set of resolvers\n const internalResolvers: Map<string, Resolver> = new Map();\n const externalResolvers: Map<string, Resolver> = new Map();\n for (const { target, plugins } of endpoints) {\n let internalResolver: Resolver | undefined;\n let externalResolver: Resolver | undefined;\n\n if (typeof target === 'string') {\n internalResolver = externalResolver = this.#makeResolver(target, false);\n } else {\n if (target.internal) {\n internalResolver = this.#makeResolver(target.internal, true);\n }\n if (target.external) {\n externalResolver = this.#makeResolver(target.external, false);\n }\n }\n\n if (internalResolver) {\n for (const pluginId of plugins) {\n internalResolvers.set(pluginId, internalResolver);\n }\n }\n if (externalResolver) {\n for (const pluginId of plugins) {\n externalResolvers.set(pluginId, externalResolver);\n }\n }\n }\n\n // Only persist if no errors were thrown above\n this.#internalResolvers = internalResolvers;\n this.#externalResolvers = externalResolvers;\n }\n\n #makeResolver(urlPattern: string, allowSrv: boolean): Resolver {\n const withPluginId = (pluginId: string, url: string) => {\n return url.replace(\n /\\{\\{\\s*pluginId\\s*\\}\\}/g,\n encodeURIComponent(pluginId),\n );\n };\n\n if (!this.#srvResolver.isSrvUrl(urlPattern)) {\n return async pluginId => withPluginId(pluginId, urlPattern);\n }\n\n if (!allowSrv) {\n throw new Error(\n `SRV resolver URLs cannot be used in the target for external endpoints`,\n );\n }\n\n const lazyResolvers = new Map<string, () => Promise<string>>();\n return async pluginId => {\n let lazyResolver = lazyResolvers.get(pluginId);\n if (!lazyResolver) {\n lazyResolver = this.#srvResolver.getResolver(\n withPluginId(pluginId, urlPattern),\n );\n lazyResolvers.set(pluginId, lazyResolver);\n }\n return await lazyResolver();\n };\n }\n}\n"],"names":["SrvResolvers","config","trimEnd","readHttpServerOptions","getEndpoints"],"mappings":";;;;;;;AA8IO,MAAM,aAAA,CAA0C;AAAA,EACrD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A,QACA,mBAAmB,QAAQ;AAAA,OAC7B;AAAA,IACF,CAAA;AAEA,IAAA,IAAI,CAAC,IAAA,CAAK,YAAA,CAAa,QAAA,CAAS,UAAU,CAAA,EAAG;AAC3C,MAAA,OAAO,OAAM,QAAA,KAAY,YAAA,CAAa,QAAA,EAAU,UAAU,CAAA;AAAA,IAC5D;AAEA,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,qEAAA;AAAA,OACF;AAAA,IACF;AAEA,IAAA,MAAM,aAAA,uBAAoB,GAAA,EAAmC;AAC7D,IAAA,OAAO,OAAM,QAAA,KAAY;AACvB,MAAA,IAAI,YAAA,GAAe,aAAA,CAAc,GAAA,CAAI,QAAQ,CAAA;AAC7C,MAAA,IAAI,CAAC,YAAA,EAAc;AACjB,QAAA,YAAA,GAAe,KAAK,YAAA,CAAa,WAAA;AAAA,UAC/B,YAAA,CAAa,UAAU,UAAU;AAAA,SACnC;AACA,QAAA,aAAA,CAAc,GAAA,CAAI,UAAU,YAAY,CAAA;AAAA,MAC1C;AACA,MAAA,OAAO,MAAM,YAAA,EAAa;AAAA,IAC5B,CAAA;AAAA,EACF;AACF;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SrvResolvers.cjs.js","sources":["../../../src/entrypoints/discovery/SrvResolvers.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ForwardedError, InputError, NotFoundError } from '@backstage/errors';\nimport { resolveSrv, SrvRecord } from 'node:dns';\n\nconst PROTOCOL_SUFFIX = '+srv:';\n\n/**\n * Helps with resolution and caching of SRV lookups.\n *\n * Supports URLs on the form `http+srv://myplugin.services.region.example.net/api/myplugin`\n */\nexport class SrvResolvers {\n readonly #cache: Map<string, Promise<SrvRecord[]>>;\n readonly #cacheTtlMillis: number;\n readonly #resolveSrv: (host: string) => Promise<SrvRecord[]>;\n\n constructor(options?: {\n resolveSrv?: (host: string) => Promise<SrvRecord[]>;\n cacheTtlMillis?: number;\n }) {\n this.#cache = new Map();\n this.#cacheTtlMillis = options?.cacheTtlMillis ?? 1000;\n this.#resolveSrv =\n options?.resolveSrv ??\n (host =>\n new Promise((resolve, reject) => {\n resolveSrv(host, (err, result) => {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n }));\n }\n\n isSrvUrl(url: string): boolean {\n try {\n this.#parseSrvUrl(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get a resolver function for a given SRV form URL.\n *\n * @param url An SRV form URL, e.g. `http+srv://myplugin.services.region.example.net/api/myplugin`\n * @returns A function that returns resolved URLs, e.g. `http://1234abcd.region.example.net:8080/api/myplugin`\n */\n getResolver(url: string): () => Promise<string> {\n const { protocol, host, path } = this.#parseSrvUrl(url);\n return () =>\n this.#resolveHost(host).then(\n resolved => `${protocol}://${resolved}${path}`,\n );\n }\n\n /**\n * Attempts to parse out the relevant parts of an SRV URL.\n */\n #parseSrvUrl(url: string): { protocol: string; host: string; path: string } {\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch {\n throw new InputError(\n `SRV resolver expected a valid URL starting with http(s)+srv:// but got '${url}'`,\n );\n }\n if (!parsedUrl.protocol?.endsWith(PROTOCOL_SUFFIX) || !parsedUrl.hostname) {\n throw new InputError(\n `SRV resolver expected a URL with protocol http(s)+srv:// but got '${url}'`,\n );\n }\n if (parsedUrl.port) {\n throw new InputError(\n `SRV resolver URLs cannot contain a port but got '${url}'`,\n );\n }\n if (parsedUrl.username || parsedUrl.password) {\n throw new InputError(\n `SRV resolver URLs cannot contain username or password but got '${url}'`,\n );\n }\n if (parsedUrl.search || parsedUrl.hash) {\n throw new InputError(\n `SRV resolver URLs cannot contain search params or a hash but got '${url}'`,\n );\n }\n\n const protocol = parsedUrl.protocol.substring(\n 0,\n parsedUrl.protocol.length - PROTOCOL_SUFFIX.length,\n );\n const host = parsedUrl.hostname;\n const path = parsedUrl.pathname.replace(/\\/+$/, '');\n\n if (!['http', 'https'].includes(protocol)) {\n throw new InputError(\n `SRV URLs must be based on http or https but got '${url}'`,\n );\n }\n\n return { protocol, host, path };\n }\n\n /**\n * Resolves a single SRV record name to a host:port string.\n */\n #resolveHost(host: string): Promise<string> {\n let records = this.#cache.get(host);\n if (!records) {\n records = this.#resolveSrv(host).then(\n result => {\n if (!result.length) {\n throw new NotFoundError(`No SRV records found for ${host}`);\n }\n return result;\n },\n err => {\n throw new ForwardedError(`Failed SRV resolution for ${host}`, err);\n },\n );\n this.#cache.set(host, records);\n setTimeout(() => {\n this.#cache.delete(host);\n }, this.#cacheTtlMillis);\n }\n\n return records.then(rs => {\n const r = this.#pickRandomRecord(rs);\n return `${r.name}:${r.port}`;\n });\n }\n\n /**\n * Among a set of records, pick one at random.\n *\n * This assumes that the set is not empty.\n *\n * Since this contract only ever returns a single record, the best it can do\n * is to pick weighted-randomly among the highest-priority records. In order\n * to be smarter than that, the caller would have to be able to make decisions\n * on the whole set of records.\n */\n #pickRandomRecord(allRecords: SrvRecord[]): SrvRecord {\n // Lowest priority number means highest priority\n const lowestPriority = allRecords.reduce(\n (acc, r) => Math.min(acc, r.priority),\n Number.MAX_SAFE_INTEGER,\n );\n const records = allRecords.filter(r => r.priority === lowestPriority);\n\n const totalWeight = records.reduce((acc, r) => acc + r.weight, 0);\n const targetWeight = Math.random() * totalWeight;\n\n // Just as a fallback, we expect the loop below to always find a result\n let result = records[0];\n let currentWeight = 0;\n\n for (const record of records) {\n currentWeight += record.weight;\n if (targetWeight <= currentWeight) {\n result = record;\n break;\n }\n }\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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,kBAAkB,UAAA,EAAoC;AAEpD,IAAA,MAAM,iBAAiB,UAAA,CAAW,MAAA;AAAA,MAChC,CAAC,GAAA,EAAK,CAAA,KAAM,KAAK,GAAA,CAAI,GAAA,EAAK,EAAE,QAAQ,CAAA;AAAA,MACpC,MAAA,CAAO;AAAA,KACT;AACA,IAAA,MAAM,UAAU,UAAA,CAAW,MAAA,CAAO,CAAA,CAAA,KAAK,CAAA,CAAE,aAAa,cAAc,CAAA;AAEpE,IAAA,MAAM,WAAA,GAAc,QAAQ,MAAA,CAAO,CAAC,KAAK,CAAA,KAAM,GAAA,GAAM,CAAA,CAAE,MAAA,EAAQ,CAAC,CAAA;AAChE,IAAA,MAAM,YAAA,GAAe,IAAA,CAAK,MAAA,EAAO,GAAI,WAAA;AAGrC,IAAA,IAAI,MAAA,GAAS,QAAQ,CAAC,CAAA;AACtB,IAAA,IAAI,aAAA,GAAgB,CAAA;AAEpB,IAAA,KAAA,MAAW,UAAU,OAAA,EAAS;AAC5B,MAAA,aAAA,IAAiB,MAAA,CAAO,MAAA;AACxB,MAAA,IAAI,gBAAgB,aAAA,EAAe;AACjC,QAAA,MAAA,GAAS,MAAA;AACT,QAAA;AAAA,MACF;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF
|
|
1
|
+
{"version":3,"file":"SrvResolvers.cjs.js","sources":["../../../src/entrypoints/discovery/SrvResolvers.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ForwardedError, InputError, NotFoundError } from '@backstage/errors';\nimport { resolveSrv, SrvRecord } from 'node:dns';\n\nconst PROTOCOL_SUFFIX = '+srv:';\n\n/**\n * Helps with resolution and caching of SRV lookups.\n *\n * Supports URLs on the form `http+srv://myplugin.services.region.example.net/api/myplugin`\n */\nexport class SrvResolvers {\n readonly #cache: Map<string, Promise<SrvRecord[]>>;\n readonly #cacheTtlMillis: number;\n readonly #resolveSrv: (host: string) => Promise<SrvRecord[]>;\n\n constructor(options?: {\n resolveSrv?: (host: string) => Promise<SrvRecord[]>;\n cacheTtlMillis?: number;\n }) {\n this.#cache = new Map();\n this.#cacheTtlMillis = options?.cacheTtlMillis ?? 1000;\n this.#resolveSrv =\n options?.resolveSrv ??\n (host =>\n new Promise((resolve, reject) => {\n resolveSrv(host, (err, result) => {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n }));\n }\n\n isSrvUrl(url: string): boolean {\n try {\n this.#parseSrvUrl(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get a resolver function for a given SRV form URL.\n *\n * @param url An SRV form URL, e.g. `http+srv://myplugin.services.region.example.net/api/myplugin`\n * @returns A function that returns resolved URLs, e.g. `http://1234abcd.region.example.net:8080/api/myplugin`\n */\n getResolver(url: string): () => Promise<string> {\n const { protocol, host, path } = this.#parseSrvUrl(url);\n return () =>\n this.#resolveHost(host).then(\n resolved => `${protocol}://${resolved}${path}`,\n );\n }\n\n /**\n * Attempts to parse out the relevant parts of an SRV URL.\n */\n #parseSrvUrl(url: string): { protocol: string; host: string; path: string } {\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch {\n throw new InputError(\n `SRV resolver expected a valid URL starting with http(s)+srv:// but got '${url}'`,\n );\n }\n if (!parsedUrl.protocol?.endsWith(PROTOCOL_SUFFIX) || !parsedUrl.hostname) {\n throw new InputError(\n `SRV resolver expected a URL with protocol http(s)+srv:// but got '${url}'`,\n );\n }\n if (parsedUrl.port) {\n throw new InputError(\n `SRV resolver URLs cannot contain a port but got '${url}'`,\n );\n }\n if (parsedUrl.username || parsedUrl.password) {\n throw new InputError(\n `SRV resolver URLs cannot contain username or password but got '${url}'`,\n );\n }\n if (parsedUrl.search || parsedUrl.hash) {\n throw new InputError(\n `SRV resolver URLs cannot contain search params or a hash but got '${url}'`,\n );\n }\n\n const protocol = parsedUrl.protocol.substring(\n 0,\n parsedUrl.protocol.length - PROTOCOL_SUFFIX.length,\n );\n const host = parsedUrl.hostname;\n const path = parsedUrl.pathname.replace(/\\/+$/, '');\n\n if (!['http', 'https'].includes(protocol)) {\n throw new InputError(\n `SRV URLs must be based on http or https but got '${url}'`,\n );\n }\n\n return { protocol, host, path };\n }\n\n /**\n * Resolves a single SRV record name to a host:port string.\n */\n #resolveHost(host: string): Promise<string> {\n let records = this.#cache.get(host);\n if (!records) {\n records = this.#resolveSrv(host).then(\n result => {\n if (!result.length) {\n throw new NotFoundError(`No SRV records found for ${host}`);\n }\n return result;\n },\n err => {\n throw new ForwardedError(`Failed SRV resolution for ${host}`, err);\n },\n );\n this.#cache.set(host, records);\n setTimeout(() => {\n this.#cache.delete(host);\n }, this.#cacheTtlMillis);\n }\n\n return records.then(rs => {\n const r = this.#pickRandomRecord(rs);\n return `${r.name}:${r.port}`;\n });\n }\n\n /**\n * Among a set of records, pick one at random.\n *\n * This assumes that the set is not empty.\n *\n * Since this contract only ever returns a single record, the best it can do\n * is to pick weighted-randomly among the highest-priority records. In order\n * to be smarter than that, the caller would have to be able to make decisions\n * on the whole set of records.\n */\n #pickRandomRecord(allRecords: SrvRecord[]): SrvRecord {\n // Lowest priority number means highest priority\n const lowestPriority = allRecords.reduce(\n (acc, r) => Math.min(acc, r.priority),\n Number.MAX_SAFE_INTEGER,\n );\n const records = allRecords.filter(r => r.priority === lowestPriority);\n\n const totalWeight = records.reduce((acc, r) => acc + r.weight, 0);\n const targetWeight = Math.random() * totalWeight;\n\n // Just as a fallback, we expect the loop below to always find a result\n let result = records[0];\n let currentWeight = 0;\n\n for (const record of records) {\n currentWeight += record.weight;\n if (targetWeight <= currentWeight) {\n result = record;\n break;\n }\n }\n\n return result;\n }\n}\n"],"names":["resolveSrv","InputError","NotFoundError","ForwardedError"],"mappings":";;;;;AAmBA,MAAM,eAAA,GAAkB,OAAA;AAOjB,MAAM,YAAA,CAAa;AAAA,EACf,MAAA;AAAA,EACA,eAAA;AAAA,EACA,WAAA;AAAA,EAET,YAAY,OAAA,EAGT;AACD,IAAA,IAAA,CAAK,MAAA,uBAAa,GAAA,EAAI;AACtB,IAAA,IAAA,CAAK,eAAA,GAAkB,SAAS,cAAA,IAAkB,GAAA;AAClD,IAAA,IAAA,CAAK,WAAA,GACH,SAAS,UAAA,KACR,CAAA,IAAA,KACC,IAAI,OAAA,CAAQ,CAAC,SAAS,MAAA,KAAW;AAC/B,MAAAA,mBAAA,CAAW,IAAA,EAAM,CAAC,GAAA,EAAK,MAAA,KAAW;AAChC,QAAA,IAAI,GAAA,EAAK;AACP,UAAA,MAAA,CAAO,GAAG,CAAA;AAAA,QACZ,CAAA,MAAO;AACL,UAAA,OAAA,CAAQ,MAAM,CAAA;AAAA,QAChB;AAAA,MACF,CAAC,CAAA;AAAA,IACH,CAAC,CAAA,CAAA;AAAA,EACP;AAAA,EAEA,SAAS,GAAA,EAAsB;AAC7B,IAAA,IAAI;AACF,MAAA,IAAA,CAAK,aAAa,GAAG,CAAA;AACrB,MAAA,OAAO,IAAA;AAAA,IACT,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,YAAY,GAAA,EAAoC;AAC9C,IAAA,MAAM,EAAE,QAAA,EAAU,IAAA,EAAM,MAAK,GAAI,IAAA,CAAK,aAAa,GAAG,CAAA;AACtD,IAAA,OAAO,MACL,IAAA,CAAK,YAAA,CAAa,IAAI,CAAA,CAAE,IAAA;AAAA,MACtB,cAAY,CAAA,EAAG,Q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AAA,CAAA,EAAI,EAAE,IAAI,CAAA,CAAA;AAAA,IAC5B,CAAC,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,kBAAkB,UAAA,EAAoC;AAEpD,IAAA,MAAM,iBAAiB,UAAA,CAAW,MAAA;AAAA,MAChC,CAAC,GAAA,EAAK,CAAA,KAAM,KAAK,GAAA,CAAI,GAAA,EAAK,EAAE,QAAQ,CAAA;AAAA,MACpC,MAAA,CAAO;AAAA,KACT;AACA,IAAA,MAAM,UAAU,UAAA,CAAW,MAAA,CAAO,CAAA,CAAA,KAAK,CAAA,CAAE,aAAa,cAAc,CAAA;AAEpE,IAAA,MAAM,WAAA,GAAc,QAAQ,MAAA,CAAO,CAAC,KAAK,CAAA,KAAM,GAAA,GAAM,CAAA,CAAE,MAAA,EAAQ,CAAC,CAAA;AAChE,IAAA,MAAM,YAAA,GAAe,IAAA,CAAK,MAAA,EAAO,GAAI,WAAA;AAGrC,IAAA,IAAI,MAAA,GAAS,QAAQ,CAAC,CAAA;AACtB,IAAA,IAAI,aAAA,GAAgB,CAAA;AAEpB,IAAA,KAAA,MAAW,UAAU,OAAA,EAAS;AAC5B,MAAA,aAAA,IAAiB,MAAA,CAAO,MAAA;AACxB,MAAA,IAAI,gBAAgB,aAAA,EAAe;AACjC,QAAA,MAAA,GAAS,MAAA;AACT,QAAA;AAAA,MACF;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discoveryServiceFactory.cjs.js","sources":["../../../src/entrypoints/discovery/discoveryServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { HostDiscovery } from './HostDiscovery';\n\n/**\n * Service discovery for inter-plugin communication.\n *\n * See {@link @backstage/code-plugin-api#DiscoveryService}\n * and {@link https://backstage.io/docs/backend-system/core-services/discovery | the service docs}\n * for more information.\n *\n * @public\n */\nexport const discoveryServiceFactory = createServiceFactory({\n service: coreServices.discovery,\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.logger,\n },\n async factory({ config, logger }) {\n return HostDiscovery.fromConfig(config, {\n logger,\n defaultEndpoints: [],\n });\n },\n});\n"],"names":["createServiceFactory","coreServices","HostDiscovery"],"mappings":";;;;;AA+BO,MAAM,0BAA0BA,qCAAA,CAAqB;AAAA,EAC1D,SAASC,6BAAA,CAAa,SAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,QAAQA,6BAAA,CAAa,UAAA;AAAA,IACrB,QAAQA,6BAAA,CAAa;AAAA,GACvB;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,MAAA,EAAQ,QAAO,EAAG;AAChC,IAAA,OAAOC,2BAAA,CAAc,WAAW,MAAA,EAAQ;AAAA,MACtC,MAAA;AAAA,MACA,kBAAkB;AAAC,KACpB,CAAA;AAAA,EACH;AACF,CAAC
|
|
1
|
+
{"version":3,"file":"discoveryServiceFactory.cjs.js","sources":["../../../src/entrypoints/discovery/discoveryServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { HostDiscovery } from './HostDiscovery';\n\n/**\n * Service discovery for inter-plugin communication.\n *\n * See {@link @backstage/code-plugin-api#DiscoveryService}\n * and {@link https://backstage.io/docs/backend-system/core-services/discovery | the service docs}\n * for more information.\n *\n * @public\n */\nexport const discoveryServiceFactory = createServiceFactory({\n service: coreServices.discovery,\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.logger,\n },\n async factory({ config, logger }) {\n return HostDiscovery.fromConfig(config, {\n logger,\n defaultEndpoints: [],\n });\n },\n});\n"],"names":["createServiceFactory","coreServices","HostDiscovery"],"mappings":";;;;;AA+BO,MAAM,0BAA0BA,qCAAA,CAAqB;AAAA,EAC1D,SAASC,6BAAA,CAAa,SAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,QAAQA,6BAAA,CAAa,UAAA;AAAA,IACrB,QAAQA,6BAAA,CAAa;AAAA,GACvB;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,MAAA,EAAQ,QAAO,EAAG;AAChC,IAAA,OAAOC,2BAAA,CAAc,WAAW,MAAA,EAAQ;AAAA,MACtC,MAAA;AAAA,MACA,kBAAkB;AAAC,KACpB,CAAA;AAAA,EACH;AACF,CAAC;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parsing.cjs.js","sources":["../../../src/entrypoints/discovery/parsing.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport type { HostDiscoveryEndpoint } from './HostDiscovery';\n\nexport function getEndpoints(config: Config): HostDiscoveryEndpoint[] {\n const endpoints: HostDiscoveryEndpoint[] = [];\n // Allow config to override the default endpoints\n const endpointConfigs = config.getOptionalConfigArray('discovery.endpoints');\n for (const endpointConfig of endpointConfigs ?? []) {\n if (typeof endpointConfig.get('target') === 'string') {\n endpoints.push({\n target: endpointConfig.getString('target'),\n plugins: endpointConfig.getStringArray('plugins'),\n });\n } else {\n endpoints.push({\n target: {\n internal: endpointConfig.getOptionalString('target.internal'),\n external: endpointConfig.getOptionalString('target.external'),\n },\n plugins: endpointConfig.getStringArray('plugins'),\n });\n }\n }\n return endpoints;\n}\n"],"names":[],"mappings":";;AAmBO,SAAS,aAAa,MAAA,EAAyC;AACpE,EAAA,MAAM,YAAqC,EAAC;AAE5C,EAAA,MAAM,eAAA,GAAkB,MAAA,CAAO,sBAAA,CAAuB,qBAAqB,CAAA;AAC3E,EAAA,KAAA,MAAW,cAAA,IAAkB,eAAA,IAAmB,EAAC,EAAG;AAClD,IAAA,IAAI,OAAO,cAAA,CAAe,GAAA,CAAI,QAAQ,MAAM,QAAA,EAAU;AACpD,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,MAAA,EAAQ,cAAA,CAAe,SAAA,CAAU,QAAQ,CAAA;AAAA,QACzC,OAAA,EAAS,cAAA,CAAe,cAAA,CAAe,SAAS;AAAA,OACjD,CAAA;AAAA,IACH,CAAA,MAAO;AACL,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,MAAA,EAAQ;AAAA,UACN,QAAA,EAAU,cAAA,CAAe,iBAAA,CAAkB,iBAAiB,CAAA;AAAA,UAC5D,QAAA,EAAU,cAAA,CAAe,iBAAA,CAAkB,iBAAiB;AAAA,SAC9D;AAAA,QACA,OAAA,EAAS,cAAA,CAAe,cAAA,CAAe,SAAS;AAAA,OACjD,CAAA;AAAA,IACH;AAAA,EACF;AACA,EAAA,OAAO,SAAA;AACT
|
|
1
|
+
{"version":3,"file":"parsing.cjs.js","sources":["../../../src/entrypoints/discovery/parsing.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport type { HostDiscoveryEndpoint } from './HostDiscovery';\n\nexport function getEndpoints(config: Config): HostDiscoveryEndpoint[] {\n const endpoints: HostDiscoveryEndpoint[] = [];\n // Allow config to override the default endpoints\n const endpointConfigs = config.getOptionalConfigArray('discovery.endpoints');\n for (const endpointConfig of endpointConfigs ?? []) {\n if (typeof endpointConfig.get('target') === 'string') {\n endpoints.push({\n target: endpointConfig.getString('target'),\n plugins: endpointConfig.getStringArray('plugins'),\n });\n } else {\n endpoints.push({\n target: {\n internal: endpointConfig.getOptionalString('target.internal'),\n external: endpointConfig.getOptionalString('target.external'),\n },\n plugins: endpointConfig.getStringArray('plugins'),\n });\n }\n }\n return endpoints;\n}\n"],"names":[],"mappings":";;AAmBO,SAAS,aAAa,MAAA,EAAyC;AACpE,EAAA,MAAM,YAAqC,EAAC;AAE5C,EAAA,MAAM,eAAA,GAAkB,MAAA,CAAO,sBAAA,CAAuB,qBAAqB,CAAA;AAC3E,EAAA,KAAA,MAAW,cAAA,IAAkB,eAAA,IAAmB,EAAC,EAAG;AAClD,IAAA,IAAI,OAAO,cAAA,CAAe,GAAA,CAAI,QAAQ,MAAM,QAAA,EAAU;AACpD,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,MAAA,EAAQ,cAAA,CAAe,SAAA,CAAU,QAAQ,CAAA;AAAA,QACzC,OAAA,EAAS,cAAA,CAAe,cAAA,CAAe,SAAS;AAAA,OACjD,CAAA;AAAA,IACH,CAAA,MAAO;AACL,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,MAAA,EAAQ;AAAA,UACN,QAAA,EAAU,cAAA,CAAe,iBAAA,CAAkB,iBAAiB,CAAA;AAAA,UAC5D,QAAA,EAAU,cAAA,CAAe,iBAAA,CAAkB,iBAAiB;AAAA,SAC9D;AAAA,QACA,OAAA,EAAS,cAAA,CAAe,cAAA,CAAe,SAAS;AAAA,OACjD,CAAA;AAAA,IACH;AAAA,EACF;AACA,EAAA,OAAO,SAAA;AACT;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpAuthServiceFactory.cjs.js","sources":["../../../src/entrypoints/httpAuth/httpAuthServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthService,\n BackstageCredentials,\n BackstagePrincipalTypes,\n BackstageUserPrincipal,\n DiscoveryService,\n HttpAuthService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { AuthenticationError, NotAllowedError } from '@backstage/errors';\nimport { parse as parseCookie } from 'cookie';\nimport { Request, Response } from 'express';\n\nconst FIVE_MINUTES_MS = 5 * 60 * 1000;\n\nconst BACKSTAGE_AUTH_COOKIE = 'backstage-auth';\n\nfunction getTokenFromRequest(req: Request) {\n let token: string | undefined;\n const authHeader = req.headers.authorization;\n if (typeof authHeader === 'string') {\n const matches = authHeader.match(/^Bearer[ ]+(\\S+)$/i);\n token = matches?.[1];\n }\n\n return { token };\n}\n\nfunction getCookieFromRequest(req: Request) {\n const cookieHeader = req.headers.cookie;\n if (cookieHeader) {\n const cookies = parseCookie(cookieHeader);\n const token = cookies[BACKSTAGE_AUTH_COOKIE];\n if (token) {\n return token;\n }\n }\n\n return undefined;\n}\n\nfunction willExpireSoon(expiresAt: Date) {\n return Date.now() + FIVE_MINUTES_MS > expiresAt.getTime();\n}\n\n/**\n * @public\n * Options for creating a DefaultHttpAuthService.\n */\nexport interface DefaultHttpAuthServiceOptions {\n auth: AuthService;\n discovery: DiscoveryService;\n pluginId: string;\n /**\n * Optionally override logic for extracting the token from the request.\n */\n getTokenFromRequest?: (req: Request) => { token?: string };\n}\n\n/**\n * @public\n * DefaultHttpAuthService is the default implementation of the HttpAuthService\n */\nexport class DefaultHttpAuthService implements HttpAuthService {\n readonly #credentialsCache = new WeakMap<\n Request,\n Promise<BackstageCredentials>\n >();\n readonly #limitedCredentialsCache = new WeakMap<\n Request,\n Promise<BackstageCredentials>\n >();\n readonly #auth: AuthService;\n readonly #discovery: DiscoveryService;\n readonly #pluginId: string;\n readonly #getToken: (req: Request) => { token?: string };\n\n private constructor(\n auth: AuthService,\n discovery: DiscoveryService,\n pluginId: string,\n getToken?: (req: Request) => { token?: string },\n ) {\n this.#auth = auth;\n this.#discovery = discovery;\n this.#pluginId = pluginId;\n this.#getToken = getToken ?? getTokenFromRequest;\n }\n\n static create(\n options: DefaultHttpAuthServiceOptions,\n ): DefaultHttpAuthService {\n return new DefaultHttpAuthService(\n options.auth,\n options.discovery,\n options.pluginId,\n options.getTokenFromRequest,\n );\n }\n\n async #extractCredentialsFromRequest(req: Request) {\n const { token } = this.#getToken(req);\n if (!token) {\n return await this.#auth.getNoneCredentials();\n }\n\n return await this.#auth.authenticate(token);\n }\n\n async #extractLimitedCredentialsFromRequest(req: Request) {\n const { token } = this.#getToken(req);\n if (token) {\n return await this.#auth.authenticate(token, {\n allowLimitedAccess: true,\n });\n }\n\n const cookie = getCookieFromRequest(req);\n if (cookie) {\n return await this.#auth.authenticate(cookie, {\n allowLimitedAccess: true,\n });\n }\n\n return await this.#auth.getNoneCredentials();\n }\n\n async #getCredentials(req: Request) {\n let credentials = this.#credentialsCache.get(req);\n if (!credentials) {\n credentials = this.#extractCredentialsFromRequest(req);\n this.#credentialsCache.set(req, credentials);\n }\n return credentials;\n }\n\n async #getLimitedCredentials(req: Request) {\n let credentials = this.#limitedCredentialsCache.get(req);\n if (!credentials) {\n credentials = this.#extractLimitedCredentialsFromRequest(req);\n this.#limitedCredentialsCache.set(req, credentials);\n }\n return credentials;\n }\n\n async credentials<TAllowed extends keyof BackstagePrincipalTypes = 'unknown'>(\n req: Request,\n options?: {\n allow?: Array<TAllowed>;\n allowLimitedAccess?: boolean;\n },\n ): Promise<BackstageCredentials<BackstagePrincipalTypes[TAllowed]>> {\n // Limited and full credentials are treated as two separate cases, this lets\n // us avoid internal dependencies between the AuthService and\n // HttpAuthService implementations\n const credentials = options?.allowLimitedAccess\n ? await this.#getLimitedCredentials(req)\n : await this.#getCredentials(req);\n\n const allowed = options?.allow;\n if (!allowed) {\n return credentials as any;\n }\n\n if (this.#auth.isPrincipal(credentials, 'none')) {\n if (allowed.includes('none' as TAllowed)) {\n return credentials as any;\n }\n\n throw new AuthenticationError('Missing credentials');\n } else if (this.#auth.isPrincipal(credentials, 'user')) {\n if (allowed.includes('user' as TAllowed)) {\n return credentials as any;\n }\n\n throw new NotAllowedError(\n `This endpoint does not allow 'user' credentials`,\n );\n } else if (this.#auth.isPrincipal(credentials, 'service')) {\n if (allowed.includes('service' as TAllowed)) {\n return credentials as any;\n }\n\n throw new NotAllowedError(\n `This endpoint does not allow 'service' credentials`,\n );\n }\n\n throw new NotAllowedError(\n 'Unknown principal type, this should never happen',\n );\n }\n\n async issueUserCookie(\n res: Response,\n options?: { credentials?: BackstageCredentials },\n ): Promise<{ expiresAt: Date }> {\n if (res.headersSent) {\n throw new Error('Failed to issue user cookie, headers were already sent');\n }\n\n let credentials: BackstageCredentials<BackstageUserPrincipal>;\n if (options?.credentials) {\n if (this.#auth.isPrincipal(options.credentials, 'none')) {\n res.clearCookie(\n BACKSTAGE_AUTH_COOKIE,\n await this.#getCookieOptions(res.req),\n );\n return { expiresAt: new Date() };\n }\n if (!this.#auth.isPrincipal(options.credentials, 'user')) {\n throw new AuthenticationError(\n 'Refused to issue cookie for non-user principal',\n );\n }\n credentials = options.credentials;\n } else {\n credentials = await this.credentials(res.req, { allow: ['user'] });\n }\n\n const existingExpiresAt = await this.#existingCookieExpiration(res.req);\n if (existingExpiresAt && !willExpireSoon(existingExpiresAt)) {\n return { expiresAt: existingExpiresAt };\n }\n\n const { token, expiresAt } = await this.#auth.getLimitedUserToken(\n credentials,\n );\n if (!token) {\n throw new Error('User credentials is unexpectedly missing token');\n }\n\n res.cookie(BACKSTAGE_AUTH_COOKIE, token, {\n ...(await this.#getCookieOptions(res.req)),\n expires: expiresAt,\n });\n\n return { expiresAt };\n }\n\n async #getCookieOptions(_req: Request): Promise<{\n domain: string;\n httpOnly: true;\n secure: boolean;\n priority: 'high';\n sameSite: 'none' | 'lax';\n }> {\n // TODO: eventually we should read from `${req.protocol}://${req.hostname}`\n // once https://github.com/backstage/backstage/issues/24169 has landed\n const externalBaseUrlStr = await this.#discovery.getExternalBaseUrl(\n this.#pluginId,\n );\n const externalBaseUrl = new URL(externalBaseUrlStr);\n\n const secure =\n externalBaseUrl.protocol === 'https:' ||\n externalBaseUrl.hostname === 'localhost';\n\n return {\n domain: externalBaseUrl.hostname,\n httpOnly: true,\n secure,\n priority: 'high',\n sameSite: secure ? 'none' : 'lax',\n };\n }\n\n async #existingCookieExpiration(req: Request): Promise<Date | undefined> {\n const existingCookie = getCookieFromRequest(req);\n if (!existingCookie) {\n return undefined;\n }\n\n try {\n const existingCredentials = await this.#auth.authenticate(\n existingCookie,\n {\n allowLimitedAccess: true,\n },\n );\n if (!this.#auth.isPrincipal(existingCredentials, 'user')) {\n return undefined;\n }\n\n return existingCredentials.expiresAt;\n } catch (error) {\n if (error.name === 'AuthenticationError') {\n return undefined;\n }\n throw error;\n }\n }\n}\n\n/**\n * Authentication of HTTP requests.\n *\n * See {@link @backstage/code-plugin-api#HttpAuthService}\n * and {@link https://backstage.io/docs/backend-system/core-services/http-auth | the service docs}\n * for more information.\n *\n * @public\n */\nexport const httpAuthServiceFactory = createServiceFactory({\n service: coreServices.httpAuth,\n deps: {\n auth: coreServices.auth,\n discovery: coreServices.discovery,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ auth, discovery, plugin }) {\n return DefaultHttpAuthService.create({\n auth,\n discovery,\n pluginId: plugin.getId(),\n });\n },\n});\n"],"names":["parseCookie","AuthenticationError","NotAllowedError","createServiceFactory","coreServices"],"mappings":";;;;;;AA8BA,MAAM,eAAA,GAAkB,IAAI,EAAA,GAAK,GAAA;AAEjC,MAAM,qBAAA,GAAwB,gBAAA;AAE9B,SAAS,oBAAoB,GAAA,EAAc;AACzC,EAAA,IAAI,KAAA;AACJ,EAAA,MAAM,UAAA,GAAa,IAAI,OAAA,CAAQ,aAAA;AAC/B,EAAA,IAAI,OAAO,eAAe,QAAA,EAAU;AAClC,IAAA,MAAM,OAAA,GAAU,UAAA,CAAW,KAAA,CAAM,oBAAoB,CAAA;AACrD,IAAA,KAAA,GAAQ,UAAU,CAAC,CAAA;AAAA,EACrB;AAEA,EAAA,OAAO,EAAE,KAAA,EAAM;AACjB;AAEA,SAAS,qBAAqB,GAAA,EAAc;AAC1C,EAAA,MAAM,YAAA,GAAe,IAAI,OAAA,CAAQ,MAAA;AACjC,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,MAAM,OAAA,GAAUA,aAAY,YAAY,CAAA;AACxC,IAAA,MAAM,KAAA,GAAQ,QAAQ,qBAAqB,CAAA;AAC3C,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,S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Aa,IAAA;AAAA,IACnB,WAAWA,6BAAA,CAAa,SAAA;AAAA,IACxB,QAAQA,6BAAA,CAAa;AAAA,GACvB;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,IAAA,EAAM,SAAA,EAAW,QAAO,EAAG;AACzC,IAAA,OAAO,uBAAuB,MAAA,CAAO;AAAA,MACnC,IAAA;AAAA,MACA,SAAA;AAAA,MACA,QAAA,EAAU,OAAO,KAAA;AAAM,KACxB,CAAA;AAAA,EACH;AACF,CAAC;;;;;"}
|
|
1
|
+
{"version":3,"file":"httpAuthServiceFactory.cjs.js","sources":["../../../src/entrypoints/httpAuth/httpAuthServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthService,\n BackstageCredentials,\n BackstagePrincipalTypes,\n BackstageUserPrincipal,\n DiscoveryService,\n HttpAuthService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { AuthenticationError, NotAllowedError } from '@backstage/errors';\nimport { parse as parseCookie } from 'cookie';\nimport { Request, Response } from 'express';\n\nconst FIVE_MINUTES_MS = 5 * 60 * 1000;\n\nconst BACKSTAGE_AUTH_COOKIE = 'backstage-auth';\n\nfunction getTokenFromRequest(req: Request) {\n let token: string | undefined;\n const authHeader = req.headers.authorization;\n if (typeof authHeader === 'string') {\n const matches = authHeader.match(/^Bearer[ ]+(\\S+)$/i);\n token = matches?.[1];\n }\n\n return { token };\n}\n\nfunction getCookieFromRequest(req: Request) {\n const cookieHeader = req.headers.cookie;\n if (cookieHeader) {\n const cookies = parseCookie(cookieHeader);\n const token = cookies[BACKSTAGE_AUTH_COOKIE];\n if (token) {\n return token;\n }\n }\n\n return undefined;\n}\n\nfunction willExpireSoon(expiresAt: Date) {\n return Date.now() + FIVE_MINUTES_MS > expiresAt.getTime();\n}\n\n/**\n * @public\n * Options for creating a DefaultHttpAuthService.\n */\nexport interface DefaultHttpAuthServiceOptions {\n auth: AuthService;\n discovery: DiscoveryService;\n pluginId: string;\n /**\n * Optionally override logic for extracting the token from the request.\n */\n getTokenFromRequest?: (req: Request) => { token?: string };\n}\n\n/**\n * @public\n * DefaultHttpAuthService is the default implementation of the HttpAuthService\n */\nexport class DefaultHttpAuthService implements HttpAuthService {\n readonly #credentialsCache = new WeakMap<\n Request,\n Promise<BackstageCredentials>\n >();\n readonly #limitedCredentialsCache = new WeakMap<\n Request,\n Promise<BackstageCredentials>\n >();\n readonly #auth: AuthService;\n readonly #discovery: DiscoveryService;\n readonly #pluginId: string;\n readonly #getToken: (req: Request) => { token?: string };\n\n private constructor(\n auth: AuthService,\n discovery: DiscoveryService,\n pluginId: string,\n getToken?: (req: Request) => { token?: string },\n ) {\n this.#auth = auth;\n this.#discovery = discovery;\n this.#pluginId = pluginId;\n this.#getToken = getToken ?? getTokenFromRequest;\n }\n\n static create(\n options: DefaultHttpAuthServiceOptions,\n ): DefaultHttpAuthService {\n return new DefaultHttpAuthService(\n options.auth,\n options.discovery,\n options.pluginId,\n options.getTokenFromRequest,\n );\n }\n\n async #extractCredentialsFromRequest(req: Request) {\n const { token } = this.#getToken(req);\n if (!token) {\n return await this.#auth.getNoneCredentials();\n }\n\n return await this.#auth.authenticate(token);\n }\n\n async #extractLimitedCredentialsFromRequest(req: Request) {\n const { token } = this.#getToken(req);\n if (token) {\n return await this.#auth.authenticate(token, {\n allowLimitedAccess: true,\n });\n }\n\n const cookie = getCookieFromRequest(req);\n if (cookie) {\n return await this.#auth.authenticate(cookie, {\n allowLimitedAccess: true,\n });\n }\n\n return await this.#auth.getNoneCredentials();\n }\n\n async #getCredentials(req: Request) {\n let credentials = this.#credentialsCache.get(req);\n if (!credentials) {\n credentials = this.#extractCredentialsFromRequest(req);\n this.#credentialsCache.set(req, credentials);\n }\n return credentials;\n }\n\n async #getLimitedCredentials(req: Request) {\n let credentials = this.#limitedCredentialsCache.get(req);\n if (!credentials) {\n credentials = this.#extractLimitedCredentialsFromRequest(req);\n this.#limitedCredentialsCache.set(req, credentials);\n }\n return credentials;\n }\n\n async credentials<TAllowed extends keyof BackstagePrincipalTypes = 'unknown'>(\n req: Request,\n options?: {\n allow?: Array<TAllowed>;\n allowLimitedAccess?: boolean;\n },\n ): Promise<BackstageCredentials<BackstagePrincipalTypes[TAllowed]>> {\n // Limited and full credentials are treated as two separate cases, this lets\n // us avoid internal dependencies between the AuthService and\n // HttpAuthService implementations\n const credentials = options?.allowLimitedAccess\n ? await this.#getLimitedCredentials(req)\n : await this.#getCredentials(req);\n\n const allowed = options?.allow;\n if (!allowed) {\n return credentials as any;\n }\n\n if (this.#auth.isPrincipal(credentials, 'none')) {\n if (allowed.includes('none' as TAllowed)) {\n return credentials as any;\n }\n\n throw new AuthenticationError('Missing credentials');\n } else if (this.#auth.isPrincipal(credentials, 'user')) {\n if (allowed.includes('user' as TAllowed)) {\n return credentials as any;\n }\n\n throw new NotAllowedError(\n `This endpoint does not allow 'user' credentials`,\n );\n } else if (this.#auth.isPrincipal(credentials, 'service')) {\n if (allowed.includes('service' as TAllowed)) {\n return credentials as any;\n }\n\n throw new NotAllowedError(\n `This endpoint does not allow 'service' credentials`,\n );\n }\n\n throw new NotAllowedError(\n 'Unknown principal type, this should never happen',\n );\n }\n\n async issueUserCookie(\n res: Response,\n options?: { credentials?: BackstageCredentials },\n ): Promise<{ expiresAt: Date }> {\n if (res.headersSent) {\n throw new Error('Failed to issue user cookie, headers were already sent');\n }\n\n let credentials: BackstageCredentials<BackstageUserPrincipal>;\n if (options?.credentials) {\n if (this.#auth.isPrincipal(options.credentials, 'none')) {\n res.clearCookie(\n BACKSTAGE_AUTH_COOKIE,\n await this.#getCookieOptions(res.req),\n );\n return { expiresAt: new Date() };\n }\n if (!this.#auth.isPrincipal(options.credentials, 'user')) {\n throw new AuthenticationError(\n 'Refused to issue cookie for non-user principal',\n );\n }\n credentials = options.credentials;\n } else {\n credentials = await this.credentials(res.req, { allow: ['user'] });\n }\n\n const existingExpiresAt = await this.#existingCookieExpiration(res.req);\n if (existingExpiresAt && !willExpireSoon(existingExpiresAt)) {\n return { expiresAt: existingExpiresAt };\n }\n\n const { token, expiresAt } = await this.#auth.getLimitedUserToken(\n credentials,\n );\n if (!token) {\n throw new Error('User credentials is unexpectedly missing token');\n }\n\n res.cookie(BACKSTAGE_AUTH_COOKIE, token, {\n ...(await this.#getCookieOptions(res.req)),\n expires: expiresAt,\n });\n\n return { expiresAt };\n }\n\n async #getCookieOptions(_req: Request): Promise<{\n domain: string;\n httpOnly: true;\n secure: boolean;\n priority: 'high';\n sameSite: 'none' | 'lax';\n }> {\n // TODO: eventually we should read from `${req.protocol}://${req.hostname}`\n // once https://github.com/backstage/backstage/issues/24169 has landed\n const externalBaseUrlStr = await this.#discovery.getExternalBaseUrl(\n this.#pluginId,\n );\n const externalBaseUrl = new URL(externalBaseUrlStr);\n\n const secure =\n externalBaseUrl.protocol === 'https:' ||\n externalBaseUrl.hostname === 'localhost';\n\n return {\n domain: externalBaseUrl.hostname,\n httpOnly: true,\n secure,\n priority: 'high',\n sameSite: secure ? 'none' : 'lax',\n };\n }\n\n async #existingCookieExpiration(req: Request): Promise<Date | undefined> {\n const existingCookie = getCookieFromRequest(req);\n if (!existingCookie) {\n return undefined;\n }\n\n try {\n const existingCredentials = await this.#auth.authenticate(\n existingCookie,\n {\n allowLimitedAccess: true,\n },\n );\n if (!this.#auth.isPrincipal(existingCredentials, 'user')) {\n return undefined;\n }\n\n return existingCredentials.expiresAt;\n } catch (error) {\n if (error.name === 'AuthenticationError') {\n return undefined;\n }\n throw error;\n }\n }\n}\n\n/**\n * Authentication of HTTP requests.\n *\n * See {@link @backstage/code-plugin-api#HttpAuthService}\n * and {@link https://backstage.io/docs/backend-system/core-services/http-auth | the service docs}\n * for more information.\n *\n * @public\n */\nexport const httpAuthServiceFactory = createServiceFactory({\n service: coreServices.httpAuth,\n deps: {\n auth: coreServices.auth,\n discovery: coreServices.discovery,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ auth, discovery, plugin }) {\n return DefaultHttpAuthService.create({\n auth,\n discovery,\n pluginId: plugin.getId(),\n });\n },\n});\n"],"names":["parseCookie","AuthenticationError","NotAllowedError","createServiceFactory","coreServices"],"mappings":";;;;;;AA8BA,MAAM,eAAA,GAAkB,IAAI,EAAA,GAAK,GAAA;AAEjC,MAAM,qBAAA,GAAwB,gBAAA;AAE9B,SAAS,oBAAoB,GAAA,EAAc;AACzC,EAAA,IAAI,KAAA;AACJ,EAAA,MAAM,UAAA,GAAa,IAAI,OAAA,CAAQ,aAAA;AAC/B,EAAA,IAAI,OAAO,eAAe,QAAA,EAAU;AAClC,IAAA,MAAM,OAAA,GAAU,UAAA,CAAW,KAAA,CAAM,oBAAoB,CAAA;AACrD,IAAA,KAAA,GAAQ,UAAU,CAAC,CAAA;AAAA,EACrB;AAEA,EAAA,OAAO,EAAE,KAAA,EAAM;AACjB;AAEA,SAAS,qBAAqB,GAAA,EAAc;AAC1C,EAAA,MAAM,YAAA,GAAe,IAAI,OAAA,CAAQ,MAAA;AACjC,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,MAAM,OAAA,GAAUA,aAAY,YAAY,CAAA;AACxC,IAAA,MAAM,KAAA,GAAQ,QAAQ,qBAAqB,CAAA;AAC3C,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,eAAe,SAAA,EAAiB;AACvC,EAAA,OAAO,IAAA,CAAK,GAAA,EAAI,GAAI,eAAA,GAAkB,UAAU,OAAA,EAAQ;AAC1D;AAoBO,MAA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EAAE,IAAA,EAAM,SAAA,EAAW,QAAO,EAAG;AACzC,IAAA,OAAO,uBAAuB,MAAA,CAAO;AAAA,MACnC,IAAA;AAAA,MACA,SAAA;AAAA,MACA,QAAA,EAAU,OAAO,KAAA;AAAM,KACxB,CAAA;AAAA,EACH;AACF,CAAC;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAuthIntegrationRouter.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createAuthIntegrationRouter.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport express from 'express';\nimport Router from 'express-promise-router';\n\n/**\n * @public\n */\nexport function createAuthIntegrationRouter(options: {\n auth: AuthService;\n}): express.Router {\n const router = Router();\n\n router.get('/.backstage/auth/v1/jwks.json', async (_req, res) => {\n const { keys } = await options.auth.listPublicServiceKeys();\n\n res.json({ keys });\n });\n\n return router;\n}\n"],"names":["Router"],"mappings":";;;;;;;;AAuBO,SAAS,4BAA4B,OAAA,EAEzB;AACjB,EAAA,MAAM,SAASA,uBAAA,EAAO;AAEtB,EAAA,MAAA,CAAO,GAAA,CAAI,+BAAA,EAAiC,OAAO,IAAA,EAAM,GAAA,KAAQ;AAC/D,IAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,OAAA,CAAQ,KAAK,qBAAA,EAAsB;AAE1D,IAAA,GAAA,CAAI,IAAA,CAAK,EAAE,IAAA,EAAM,CAAA;AAAA,EACnB,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT
|
|
1
|
+
{"version":3,"file":"createAuthIntegrationRouter.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createAuthIntegrationRouter.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport express from 'express';\nimport Router from 'express-promise-router';\n\n/**\n * @public\n */\nexport function createAuthIntegrationRouter(options: {\n auth: AuthService;\n}): express.Router {\n const router = Router();\n\n router.get('/.backstage/auth/v1/jwks.json', async (_req, res) => {\n const { keys } = await options.auth.listPublicServiceKeys();\n\n res.json({ keys });\n });\n\n return router;\n}\n"],"names":["Router"],"mappings":";;;;;;;;AAuBO,SAAS,4BAA4B,OAAA,EAEzB;AACjB,EAAA,MAAM,SAASA,uBAAA,EAAO;AAEtB,EAAA,MAAA,CAAO,GAAA,CAAI,+BAAA,EAAiC,OAAO,IAAA,EAAM,GAAA,KAAQ;AAC/D,IAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,OAAA,CAAQ,KAAK,qBAAA,EAAsB;AAE1D,IAAA,GAAA,CAAI,IAAA,CAAK,EAAE,IAAA,EAAM,CAAA;AAAA,EACnB,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCookieAuthRefreshMiddleware.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createCookieAuthRefreshMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthService, HttpAuthService } from '@backstage/backend-plugin-api';\nimport Router from 'express-promise-router';\n\nconst WELL_KNOWN_COOKIE_PATH_V1 = '/.backstage/auth/v1/cookie';\n\n/**\n * @public\n * Creates a middleware that can be used to refresh the cookie for the user.\n */\nexport function createCookieAuthRefreshMiddleware(options: {\n auth: AuthService;\n httpAuth: HttpAuthService;\n}) {\n const { auth, httpAuth } = options;\n const router = Router();\n\n // Endpoint that sets the cookie for the user\n router.get(WELL_KNOWN_COOKIE_PATH_V1, async (_, res) => {\n const { expiresAt } = await httpAuth.issueUserCookie(res);\n res.json({ expiresAt: expiresAt.toISOString() });\n });\n\n // Endpoint that removes the cookie for the user\n router.delete(WELL_KNOWN_COOKIE_PATH_V1, async (_, res) => {\n const credentials = await auth.getNoneCredentials();\n await httpAuth.issueUserCookie(res, { credentials });\n res.status(204).end();\n });\n\n return router;\n}\n"],"names":["Router"],"mappings":";;;;;;;;AAmBA,MAAM,yBAAA,GAA4B,4BAAA;AAM3B,SAAS,kCAAkC,OAAA,EAG/C;AACD,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAS,GAAI,OAAA;AAC3B,EAAA,MAAM,SAASA,uBAAA,EAAO;AAGtB,EAAA,MAAA,CAAO,GAAA,CAAI,yBAAA,EAA2B,OAAO,CAAA,EAAG,GAAA,KAAQ;AACtD,IAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAM,QAAA,CAAS,gBAAgB,GAAG,CAAA;AACxD,IAAA,GAAA,CAAI,KAAK,EAAE,SAAA,EAAW,SAAA,CAAU,WAAA,IAAe,CAAA;AAAA,EACjD,CAAC,CAAA;AAGD,EAAA,MAAA,CAAO,MAAA,CAAO,yBAAA,EAA2B,OAAO,CAAA,EAAG,GAAA,KAAQ;AACzD,IAAA,MAAM,WAAA,GAAc,MAAM,IAAA,CAAK,kBAAA,EAAmB;AAClD,IAAA,MAAM,QAAA,CAAS,eAAA,CAAgB,GAAA,EAAK,EAAE,aAAa,CAAA;AACnD,IAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,GAAA,EAAI;AAAA,EACtB,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT
|
|
1
|
+
{"version":3,"file":"createCookieAuthRefreshMiddleware.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createCookieAuthRefreshMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthService, HttpAuthService } from '@backstage/backend-plugin-api';\nimport Router from 'express-promise-router';\n\nconst WELL_KNOWN_COOKIE_PATH_V1 = '/.backstage/auth/v1/cookie';\n\n/**\n * @public\n * Creates a middleware that can be used to refresh the cookie for the user.\n */\nexport function createCookieAuthRefreshMiddleware(options: {\n auth: AuthService;\n httpAuth: HttpAuthService;\n}) {\n const { auth, httpAuth } = options;\n const router = Router();\n\n // Endpoint that sets the cookie for the user\n router.get(WELL_KNOWN_COOKIE_PATH_V1, async (_, res) => {\n const { expiresAt } = await httpAuth.issueUserCookie(res);\n res.json({ expiresAt: expiresAt.toISOString() });\n });\n\n // Endpoint that removes the cookie for the user\n router.delete(WELL_KNOWN_COOKIE_PATH_V1, async (_, res) => {\n const credentials = await auth.getNoneCredentials();\n await httpAuth.issueUserCookie(res, { credentials });\n res.status(204).end();\n });\n\n return router;\n}\n"],"names":["Router"],"mappings":";;;;;;;;AAmBA,MAAM,yBAAA,GAA4B,4BAAA;AAM3B,SAAS,kCAAkC,OAAA,EAG/C;AACD,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAS,GAAI,OAAA;AAC3B,EAAA,MAAM,SAASA,uBAAA,EAAO;AAGtB,EAAA,MAAA,CAAO,GAAA,CAAI,yBAAA,EAA2B,OAAO,CAAA,EAAG,GAAA,KAAQ;AACtD,IAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAM,QAAA,CAAS,gBAAgB,GAAG,CAAA;AACxD,IAAA,GAAA,CAAI,KAAK,EAAE,SAAA,EAAW,SAAA,CAAU,WAAA,IAAe,CAAA;AAAA,EACjD,CAAC,CAAA;AAGD,EAAA,MAAA,CAAO,MAAA,CAAO,yBAAA,EAA2B,OAAO,CAAA,EAAG,GAAA,KAAQ;AACzD,IAAA,MAAM,WAAA,GAAc,MAAM,IAAA,CAAK,kBAAA,EAAmB;AAClD,IAAA,MAAM,QAAA,CAAS,eAAA,CAAgB,GAAA,EAAK,EAAE,aAAa,CAAA;AACnD,IAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,GAAA,EAAI;AAAA,EACtB,CAAC,CAAA;AAED,EAAA,OAAO,MAAA;AACT;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCredentialsBarrier.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createCredentialsBarrier.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n HttpAuthService,\n HttpRouterServiceAuthPolicy,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { RequestHandler } from 'express';\nimport { pathToRegexp } from 'path-to-regexp';\n\nexport function createPathPolicyPredicate(policyPath: string) {\n if (policyPath === '/' || policyPath === '*') {\n return () => true;\n }\n\n const { regexp: pathRegex } = pathToRegexp(policyPath, {\n end: false,\n });\n\n return (path: string): boolean => {\n return pathRegex.test(path);\n };\n}\n\n/**\n * @public\n */\nexport function createCredentialsBarrier(options: {\n httpAuth: HttpAuthService;\n config: RootConfigService;\n}): {\n middleware: RequestHandler;\n addAuthPolicy: (policy: HttpRouterServiceAuthPolicy) => void;\n} {\n const { httpAuth, config } = options;\n\n const disableDefaultAuthPolicy = config.getOptionalBoolean(\n 'backend.auth.dangerouslyDisableDefaultAuthPolicy',\n );\n\n if (disableDefaultAuthPolicy) {\n return {\n middleware: (_req, _res, next) => next(),\n addAuthPolicy: () => {},\n };\n }\n\n const unauthenticatedPredicates = new Array<(path: string) => boolean>();\n const cookiePredicates = new Array<(path: string) => boolean>();\n\n const middleware: RequestHandler = (req, _, next) => {\n const allowsUnauthenticated = unauthenticatedPredicates.some(predicate =>\n predicate(req.path),\n );\n\n if (allowsUnauthenticated) {\n next();\n return;\n }\n\n const allowsCookie = cookiePredicates.some(predicate =>\n predicate(req.path),\n );\n\n httpAuth\n .credentials(req, {\n allow: ['user', 'service'],\n allowLimitedAccess: allowsCookie,\n })\n .then(\n () => next(),\n err => next(err),\n );\n };\n\n const addAuthPolicy = (policy: HttpRouterServiceAuthPolicy) => {\n if (policy.allow === 'unauthenticated') {\n unauthenticatedPredicates.push(createPathPolicyPredicate(policy.path));\n } else if (policy.allow === 'user-cookie') {\n cookiePredicates.push(createPathPolicyPredicate(policy.path));\n } else {\n throw new Error('Invalid auth policy');\n }\n };\n\n return { middleware, addAuthPolicy };\n}\n"],"names":["pathToRegexp"],"mappings":";;;;AAwBO,SAA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AAK;AAAA,MAChB,KAAA,EAAO,CAAC,MAAA,EAAQ,SAAS,CAAA;AAAA,MACzB,kBAAA,EAAoB;AAAA,KACrB,CAAA,CACA,IAAA;AAAA,MACC,MAAM,IAAA,EAAK;AAAA,MACX,CAAA,GAAA,KAAO,KAAK,GAAG;AAAA,KACjB;AAAA,EACJ,CAAA;AAEA,EAAA,MAAM,aAAA,GAAgB,CAAC,MAAA,KAAwC;AAC7D,IAAA,IAAI,MAAA,CAAO,UAAU,iBAAA,EAAmB;AACtC,MAAA,yBAAA,CAA0B,IAAA,CAAK,yBAAA,CAA0B,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,IACvE,CAAA,MAAA,IAAW,MAAA,CAAO,KAAA,KAAU,aAAA,EAAe;AACzC,MAAA,gBAAA,CAAiB,IAAA,CAAK,yBAAA,CAA0B,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,IAC9D,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,MAAM,qBAAqB,CAAA;AAAA,IACvC;AAAA,EACF,CAAA;AAEA,EAAA,OAAO,EAAE,YAAY,aAAA,EAAc;AACrC
|
|
1
|
+
{"version":3,"file":"createCredentialsBarrier.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createCredentialsBarrier.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n HttpAuthService,\n HttpRouterServiceAuthPolicy,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { RequestHandler } from 'express';\nimport { pathToRegexp } from 'path-to-regexp';\n\nexport function createPathPolicyPredicate(policyPath: string) {\n if (policyPath === '/' || policyPath === '*') {\n return () => true;\n }\n\n const { regexp: pathRegex } = pathToRegexp(policyPath, {\n end: false,\n });\n\n return (path: string): boolean => {\n return pathRegex.test(path);\n };\n}\n\n/**\n * @public\n */\nexport function createCredentialsBarrier(options: {\n httpAuth: HttpAuthService;\n config: RootConfigService;\n}): {\n middleware: RequestHandler;\n addAuthPolicy: (policy: HttpRouterServiceAuthPolicy) => void;\n} {\n const { httpAuth, config } = options;\n\n const disableDefaultAuthPolicy = config.getOptionalBoolean(\n 'backend.auth.dangerouslyDisableDefaultAuthPolicy',\n );\n\n if (disableDefaultAuthPolicy) {\n return {\n middleware: (_req, _res, next) => next(),\n addAuthPolicy: () => {},\n };\n }\n\n const unauthenticatedPredicates = new Array<(path: string) => boolean>();\n const cookiePredicates = new Array<(path: string) => boolean>();\n\n const middleware: RequestHandler = (req, _, next) => {\n const allowsUnauthenticated = unauthenticatedPredicates.some(predicate =>\n predicate(req.path),\n );\n\n if (allowsUnauthenticated) {\n next();\n return;\n }\n\n const allowsCookie = cookiePredicates.some(predicate =>\n predicate(req.path),\n );\n\n httpAuth\n .credentials(req, {\n allow: ['user', 'service'],\n allowLimitedAccess: allowsCookie,\n })\n .then(\n () => next(),\n err => next(err),\n );\n };\n\n const addAuthPolicy = (policy: HttpRouterServiceAuthPolicy) => {\n if (policy.allow === 'unauthenticated') {\n unauthenticatedPredicates.push(createPathPolicyPredicate(policy.path));\n } else if (policy.allow === 'user-cookie') {\n cookiePredicates.push(createPathPolicyPredicate(policy.path));\n } else {\n throw new Error('Invalid auth policy');\n }\n };\n\n return { middleware, addAuthPolicy };\n}\n"],"names":["pathToRegexp"],"mappings":";;;;AAwBO,SAAS,0BAA0B,UAAA,EAAoB;AAC5D,EAAA,IAAI,UAAA,KAAe,GAAA,IAAO,UAAA,KAAe,GAAA,EAAK;AAC5C,IAAA,OAAO,MAAM,IAAA;AAAA,EACf;AAEA,EAAA,MAAM,EAAE,MAAA,EAAQ,SAA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AAK,GAAG;AAAA,KACjB;AAAA,EACJ,CAAA;AAEA,EAAA,MAAM,aAAA,GAAgB,CAAC,MAAA,KAAwC;AAC7D,IAAA,IAAI,MAAA,CAAO,UAAU,iBAAA,EAAmB;AACtC,MAAA,yBAAA,CAA0B,IAAA,CAAK,yBAAA,CAA0B,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,IACvE,CAAA,MAAA,IAAW,MAAA,CAAO,KAAA,KAAU,aAAA,EAAe;AACzC,MAAA,gBAAA,CAAiB,IAAA,CAAK,yBAAA,CAA0B,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,IAC9D,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,MAAM,qBAAqB,CAAA;AAAA,IACvC;AAAA,EACF,CAAA;AAEA,EAAA,OAAO,EAAE,YAAY,aAAA,EAAc;AACrC;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createLifecycleMiddleware.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createLifecycleMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RootConfigService,\n LifecycleService,\n} from '@backstage/backend-plugin-api';\nimport { readDurationFromConfig } from '@backstage/config';\nimport { ServiceUnavailableError } from '@backstage/errors';\nimport { HumanDuration, durationToMilliseconds } from '@backstage/types';\nimport { RequestHandler } from 'express';\n\nexport const DEFAULT_TIMEOUT = { seconds: 5 };\n\n/**\n * Options for {@link createLifecycleMiddleware}.\n * @public\n */\nexport interface LifecycleMiddlewareOptions {\n config: RootConfigService;\n lifecycle: LifecycleService;\n}\n\n/**\n * Creates a middleware that pauses requests until the service has started.\n *\n * @remarks\n *\n * Requests that arrive before the service has started will be paused until startup is complete.\n * If the service does not start within the provided timeout, the request will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * If the service is shutting down, all requests will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * @public\n */\nexport function createLifecycleMiddleware(\n options: LifecycleMiddlewareOptions,\n): RequestHandler {\n const { config, lifecycle } = options;\n\n let state: 'init' | 'up' | 'down' = 'init';\n const waiting = new Set<{\n next: (err?: Error) => void;\n timeout: NodeJS.Timeout;\n }>();\n\n lifecycle.addStartupHook(async () => {\n if (state === 'init') {\n state = 'up';\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next();\n }\n waiting.clear();\n }\n });\n\n lifecycle.addShutdownHook(async () => {\n state = 'down';\n\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next(new ServiceUnavailableError('Service is shutting down'));\n }\n waiting.clear();\n });\n\n let startupRequestPauseTimeout: HumanDuration = DEFAULT_TIMEOUT;\n\n if (config.has('backend.lifecycle.startupRequestPauseTimeout')) {\n startupRequestPauseTimeout = readDurationFromConfig(config, {\n key: 'backend.lifecycle.startupRequestPauseTimeout',\n });\n }\n\n const timeoutMs = durationToMilliseconds(startupRequestPauseTimeout);\n\n return (_req, _res, next) => {\n if (state === 'up') {\n next();\n return;\n } else if (state === 'down') {\n next(new ServiceUnavailableError('Service is shutting down'));\n return;\n }\n\n const item = {\n next,\n timeout: setTimeout(() => {\n if (waiting.delete(item)) {\n next(new ServiceUnavailableError('Service has not started up yet'));\n }\n }, timeoutMs),\n };\n\n waiting.add(item);\n };\n}\n"],"names":["config","ServiceUnavailableError","readDurationFromConfig","durationToMilliseconds"],"mappings":";;;;;;AAyBO,MAAM,eAAA,GAAkB,EAAE,OAAA,EAAS,CAAA;AAyBnC,SAAS,0BACd,OAAA,EACgB;AAChB,EAAA,MAAM,UAAEA,QAAA,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AAA;AAC5D,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,IAAA,GAAO;AAAA,MACX,IAAA;AAAA,MACA,OAAA,EAAS,WAAW,MAAM;AACxB,QAAA,IAAI,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAA,EAAG;AACxB,UAAA,IAAA,CAAK,IAAIA,8BAAA,CAAwB,gCAAgC,CAAC,CAAA;AAAA,QACpE;AAAA,MACF,GAAG,SAAS;AAAA,KACd;AAEA,IAAA,OAAA,CAAQ,IAAI,IAAI,CAAA;AAAA,EAClB,CAAA;AACF
|
|
1
|
+
{"version":3,"file":"createLifecycleMiddleware.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createLifecycleMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RootConfigService,\n LifecycleService,\n} from '@backstage/backend-plugin-api';\nimport { readDurationFromConfig } from '@backstage/config';\nimport { ServiceUnavailableError } from '@backstage/errors';\nimport { HumanDuration, durationToMilliseconds } from '@backstage/types';\nimport { RequestHandler } from 'express';\n\nexport const DEFAULT_TIMEOUT = { seconds: 5 };\n\n/**\n * Options for {@link createLifecycleMiddleware}.\n * @public\n */\nexport interface LifecycleMiddlewareOptions {\n config: RootConfigService;\n lifecycle: LifecycleService;\n}\n\n/**\n * Creates a middleware that pauses requests until the service has started.\n *\n * @remarks\n *\n * Requests that arrive before the service has started will be paused until startup is complete.\n * If the service does not start within the provided timeout, the request will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * If the service is shutting down, all requests will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * @public\n */\nexport function createLifecycleMiddleware(\n options: LifecycleMiddlewareOptions,\n): RequestHandler {\n const { config, lifecycle } = options;\n\n let state: 'init' | 'up' | 'down' = 'init';\n const waiting = new Set<{\n next: (err?: Error) => void;\n timeout: NodeJS.Timeout;\n }>();\n\n lifecycle.addStartupHook(async () => {\n if (state === 'init') {\n state = 'up';\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next();\n }\n waiting.clear();\n }\n });\n\n lifecycle.addShutdownHook(async () => {\n state = 'down';\n\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next(new ServiceUnavailableError('Service is shutting down'));\n }\n waiting.clear();\n });\n\n let startupRequestPauseTimeout: HumanDuration = DEFAULT_TIMEOUT;\n\n if (config.has('backend.lifecycle.startupRequestPauseTimeout')) {\n startupRequestPauseTimeout = readDurationFromConfig(config, {\n key: 'backend.lifecycle.startupRequestPauseTimeout',\n });\n }\n\n const timeoutMs = durationToMilliseconds(startupRequestPauseTimeout);\n\n return (_req, _res, next) => {\n if (state === 'up') {\n next();\n return;\n } else if (state === 'down') {\n next(new ServiceUnavailableError('Service is shutting down'));\n return;\n }\n\n const item = {\n next,\n timeout: setTimeout(() => {\n if (waiting.delete(item)) {\n next(new ServiceUnavailableError('Service has not started up yet'));\n }\n }, timeoutMs),\n };\n\n waiting.add(item);\n };\n}\n"],"names":["config","ServiceUnavailableError","readDurationFromConfig","durationToMilliseconds"],"mappings":";;;;;;AAyBO,MAAM,eAAA,GAAkB,EAAE,OAAA,EAAS,CAAA;AAyBnC,SAAS,0BACd,OAAA,EACgB;AAChB,EAAA,MAAM,UAAEA,QAAA,EAAQ,SAAA,EAAU,GAAI,OAAA;AAE9B,EAAA,IAAI,KAAA,GAAgC,MAAA;AACpC,EAAA,MAAM,OAAA,uBAAc,GAAA,EAGjB;AAEH,EAAA,SAAA,CAAU,eAAe,YAAY;AACnC,IAAA,IAAI,UAAU,MAAA,EAAQ;AACpB,MAAA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AIA,8BAAA,CAAwB,gCAAgC,CAAC,CAAA;AAAA,QACpE;AAAA,MACF,GAAG,SAAS;AAAA,KACd;AAEA,IAAA,OAAA,CAAQ,IAAI,IAAI,CAAA;AAAA,EAClB,CAAA;AACF;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRateLimitMiddleware.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createRateLimitMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NextFunction, Request, Response, RequestHandler } from 'express';\nimport { RateLimitStoreFactory } from '../../../lib/RateLimitStoreFactory.ts';\nimport { RootConfigService } from '@backstage/backend-plugin-api';\n\nimport { rateLimitMiddleware } from '../../../lib/rateLimitMiddleware.ts';\n\n/**\n * @public\n * Creates a middleware that applies rate limiting to requests based on the provided configuration.\n */\nexport const createRateLimitMiddleware = (options: {\n pluginId: string;\n config: RootConfigService;\n}): RequestHandler => {\n const { pluginId, config } = options;\n const configKey = `backend.rateLimit.plugin.${pluginId}`;\n const enabled = config.has(configKey);\n if (!enabled) {\n return (_req: Request, _res: Response, next: NextFunction) => {\n next();\n };\n }\n\n const rateLimitOptions = config.getConfig(configKey);\n\n return rateLimitMiddleware({\n store: RateLimitStoreFactory.create({ config, prefix: pluginId }),\n config: rateLimitOptions,\n });\n};\n"],"names":["rateLimitMiddleware","RateLimitStoreFactory"],"mappings":";;;;;AAyBO,MAAM,yBAAA,GAA4B,CAAC,OAAA,KAGpB;AACpB,EAAA,MAAM,EAAE,QAAA,EAAU,MAAA,EAAO,GAAI,OAAA;AAC7B,EAAA,MAAM,SAAA,GAAY,4BAA4B,QAAQ,CAAA,CAAA;AACtD,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,GAAA,CAAI,SAAS,CAAA;AACpC,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,OAAO,CAAC,IAAA,EAAe,IAAA,EAAgB,IAAA,KAAuB;AAC5D,MAAA,IAAA,EAAK;AAAA,IACP,CAAA;AAAA,EACF;AAEA,EAAA,MAAM,gBAAA,GAAmB,MAAA,CAAO,SAAA,CAAU,SAAS,CAAA;AAEnD,EAAA,OAAOA,uCAAA,CAAoB;AAAA,IACzB,OAAOC,2CAAA,CAAsB,MAAA,CAAO,EAAE,MAAA,EAAQ,MAAA,EAAQ,UAAU,CAAA;AAAA,IAChE,MAAA,EAAQ;AAAA,GACT,CAAA;AACH
|
|
1
|
+
{"version":3,"file":"createRateLimitMiddleware.cjs.js","sources":["../../../../src/entrypoints/httpRouter/http/createRateLimitMiddleware.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NextFunction, Request, Response, RequestHandler } from 'express';\nimport { RateLimitStoreFactory } from '../../../lib/RateLimitStoreFactory.ts';\nimport { RootConfigService } from '@backstage/backend-plugin-api';\n\nimport { rateLimitMiddleware } from '../../../lib/rateLimitMiddleware.ts';\n\n/**\n * @public\n * Creates a middleware that applies rate limiting to requests based on the provided configuration.\n */\nexport const createRateLimitMiddleware = (options: {\n pluginId: string;\n config: RootConfigService;\n}): RequestHandler => {\n const { pluginId, config } = options;\n const configKey = `backend.rateLimit.plugin.${pluginId}`;\n const enabled = config.has(configKey);\n if (!enabled) {\n return (_req: Request, _res: Response, next: NextFunction) => {\n next();\n };\n }\n\n const rateLimitOptions = config.getConfig(configKey);\n\n return rateLimitMiddleware({\n store: RateLimitStoreFactory.create({ config, prefix: pluginId }),\n config: rateLimitOptions,\n });\n};\n"],"names":["rateLimitMiddleware","RateLimitStoreFactory"],"mappings":";;;;;AAyBO,MAAM,yBAAA,GAA4B,CAAC,OAAA,KAGpB;AACpB,EAAA,MAAM,EAAE,QAAA,EAAU,MAAA,EAAO,GAAI,OAAA;AAC7B,EAAA,MAAM,SAAA,GAAY,4BAA4B,QAAQ,CAAA,CAAA;AACtD,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,GAAA,CAAI,SAAS,CAAA;AACpC,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,OAAO,CAAC,IAAA,EAAe,IAAA,EAAgB,IAAA,KAAuB;AAC5D,MAAA,IAAA,EAAK;AAAA,IACP,CAAA;AAAA,EACF;AAEA,EAAA,MAAM,gBAAA,GAAmB,MAAA,CAAO,SAAA,CAAU,SAAS,CAAA;AAEnD,EAAA,OAAOA,uCAAA,CAAoB;AAAA,IACzB,OAAOC,2CAAA,CAAsB,MAAA,CAAO,EAAE,MAAA,EAAQ,MAAA,EAAQ,UAAU,CAAA;AAAA,IAChE,MAAA,EAAQ;AAAA,GACT,CAAA;AACH;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpRouterServiceFactory.cjs.js","sources":["../../../src/entrypoints/httpRouter/httpRouterServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Handler } from 'express';\nimport PromiseRouter from 'express-promise-router';\nimport {\n coreServices,\n createServiceFactory,\n HttpRouterServiceAuthPolicy,\n} from '@backstage/backend-plugin-api';\nimport {\n createAuthIntegrationRouter,\n createCookieAuthRefreshMiddleware,\n createCredentialsBarrier,\n createLifecycleMiddleware,\n} from './http';\nimport { MiddlewareFactory } from '../rootHttpRouter';\nimport { createRateLimitMiddleware } from './http/createRateLimitMiddleware.ts';\n\n/**\n * HTTP route registration for plugins.\n *\n * See {@link @backstage/code-plugin-api#HttpRouterService}\n * and {@link https://backstage.io/docs/backend-system/core-services/http-router | the service docs}\n * for more information.\n *\n * @public\n */\nexport const httpRouterServiceFactory = createServiceFactory({\n service: coreServices.httpRouter,\n initialization: 'always',\n deps: {\n plugin: coreServices.pluginMetadata,\n config: coreServices.rootConfig,\n lifecycle: coreServices.lifecycle,\n rootHttpRouter: coreServices.rootHttpRouter,\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n logger: coreServices.logger,\n },\n async factory({\n auth,\n httpAuth,\n config,\n plugin,\n rootHttpRouter,\n lifecycle,\n logger,\n }) {\n const router = PromiseRouter();\n\n router.use(createRateLimitMiddleware({ pluginId: plugin.getId(), config }));\n\n rootHttpRouter.use(`/api/${plugin.getId()}`, router);\n\n const credentialsBarrier = createCredentialsBarrier({\n httpAuth,\n config,\n });\n\n router.use(createAuthIntegrationRouter({ auth }));\n router.use(createLifecycleMiddleware({ config, lifecycle }));\n router.use(credentialsBarrier.middleware);\n router.use(createCookieAuthRefreshMiddleware({ auth, httpAuth }));\n\n const pluginRoutes = PromiseRouter();\n router.use(pluginRoutes);\n\n const middleware = MiddlewareFactory.create({ config, logger });\n router.use(middleware.error());\n\n return {\n use(handler: Handler): void {\n pluginRoutes.use(handler);\n },\n addAuthPolicy(policy: HttpRouterServiceAuthPolicy): void {\n credentialsBarrier.addAuthPolicy(policy);\n },\n };\n },\n});\n"],"names":["createServiceFactory","coreServices","PromiseRouter","createRateLimitMiddleware","createCredentialsBarrier","createAuthIntegrationRouter","createLifecycleMiddleware","createCookieAuthRefreshMiddleware","MiddlewareFactory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,MAAM,2BAA2BA,qCAAA,CAAqB;AAAA,EAC3D,SAASC,6BAAA,CAAa,UAAA;AAAA,EACtB,cAAA,EAAgB,QAAA;AAAA,EAChB,IAAA,EAAM;AAAA,IACJ,QAAQA,6BAAA,CAAa,cAAA;AAAA,IACrB,QAAQA,6BAAA,CAAa,UAAA;AAAA,IACrB,WAAWA,6BAAA,CAAa,SAAA;AAAA,IACxB,gBAAgBA,6BAAA,CAAa,cAAA;AAAA,IAC7B,MAAMA,6BAAA,CAAa,IAAA;AAAA,IACnB,UAAUA,6BAAA,CAAa,QAAA;AAAA,IACvB,QAAQA,6BAAA,CAAa;AAAA,GACvB;AAAA,EACA,MAAM,OAAA,CAAQ;AAAA,IACZ,IAAA;AAAA,IACA,QAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,cAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF,EAAG;AACD,IAAA,MAAM,SAASC,uBAAA,EAAc;AAE7B,IAAA,MAAA,CAAO,GAAA,CAAIC,oDAA0B,EAAE,QAAA,EAAU,OAAO,KAAA,EAAM,EAAG,MAAA,EAAQ,CAAC,CAAA;AAE1E,IAAA,cAAA,CAAe,IAAI,CAAA,KAAA,EAAQ,MAAA,CAAO,KAAA,EAAO,IAAI,MAAM,CAAA;AAEnD,IAAA,MAAM,qBAAqBC,iDAAA,CAAyB;AAAA,MAClD,QAAA;AAAA,MACA;AAAA,KACD,CAAA;AAED,IAAA,MAAA,CAAO,GAAA,CAAIC,uDAAA,CAA4B,EAAE,IAAA,EAAM,CAAC,CAAA;AAChD,IAAA,MAAA,CAAO,IAAIC,mDAAA,CAA0B,EAAE,MAAA,EAAQ,SAAA,EAAW,CAAC,CAAA;AAC3D,IAAA,MAAA,CAAO,GAAA,CAAI,mBAAmB,UAAU,CAAA;AACxC,IAAA,MAAA,CAAO,IAAIC,mEAAA,CAAkC,EAAE,IAAA,EAAM,QAAA,EAAU,CAAC,CAAA;AAEhE,IAAA,MAAM,eAAeL,uBAAA,EAAc;AACnC,IAAA,MAAA,CAAO,IAAI,YAAY,CAAA;AAEvB,IAAA,MAAM,aAAaM,mCAAA,CAAkB,MAAA,CAAO,EAAE,MAAA,EAAQ,QAAQ,CAAA;AAC9D,IAAA,MAAA,CAAO,GAAA,CAAI,UAAA,CAAW,KAAA,EAAO,CAAA;AAE7B,IAAA,OAAO;AAAA,MACL,IAAI,OAAA,EAAwB;AAC1B,QAAA,YAAA,CAAa,IAAI,OAAO,CAAA;AAAA,MAC1B,CAAA;AAAA,MACA,cAAc,MAAA,EAA2C;AACvD,QAAA,kBAAA,CAAmB,cAAc,MAAM,CAAA;AAAA,MACzC;AAAA,KACF;AAAA,EACF;AACF,CAAC
|
|
1
|
+
{"version":3,"file":"httpRouterServiceFactory.cjs.js","sources":["../../../src/entrypoints/httpRouter/httpRouterServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Handler } from 'express';\nimport PromiseRouter from 'express-promise-router';\nimport {\n coreServices,\n createServiceFactory,\n HttpRouterServiceAuthPolicy,\n} from '@backstage/backend-plugin-api';\nimport {\n createAuthIntegrationRouter,\n createCookieAuthRefreshMiddleware,\n createCredentialsBarrier,\n createLifecycleMiddleware,\n} from './http';\nimport { MiddlewareFactory } from '../rootHttpRouter';\nimport { createRateLimitMiddleware } from './http/createRateLimitMiddleware.ts';\n\n/**\n * HTTP route registration for plugins.\n *\n * See {@link @backstage/code-plugin-api#HttpRouterService}\n * and {@link https://backstage.io/docs/backend-system/core-services/http-router | the service docs}\n * for more information.\n *\n * @public\n */\nexport const httpRouterServiceFactory = createServiceFactory({\n service: coreServices.httpRouter,\n initialization: 'always',\n deps: {\n plugin: coreServices.pluginMetadata,\n config: coreServices.rootConfig,\n lifecycle: coreServices.lifecycle,\n rootHttpRouter: coreServices.rootHttpRouter,\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n logger: coreServices.logger,\n },\n async factory({\n auth,\n httpAuth,\n config,\n plugin,\n rootHttpRouter,\n lifecycle,\n logger,\n }) {\n const router = PromiseRouter();\n\n router.use(createRateLimitMiddleware({ pluginId: plugin.getId(), config }));\n\n rootHttpRouter.use(`/api/${plugin.getId()}`, router);\n\n const credentialsBarrier = createCredentialsBarrier({\n httpAuth,\n config,\n });\n\n router.use(createAuthIntegrationRouter({ auth }));\n router.use(createLifecycleMiddleware({ config, lifecycle }));\n router.use(credentialsBarrier.middleware);\n router.use(createCookieAuthRefreshMiddleware({ auth, httpAuth }));\n\n const pluginRoutes = PromiseRouter();\n router.use(pluginRoutes);\n\n const middleware = MiddlewareFactory.create({ config, logger });\n router.use(middleware.error());\n\n return {\n use(handler: Handler): void {\n pluginRoutes.use(handler);\n },\n addAuthPolicy(policy: HttpRouterServiceAuthPolicy): void {\n credentialsBarrier.addAuthPolicy(policy);\n },\n };\n },\n});\n"],"names":["createServiceFactory","coreServices","PromiseRouter","createRateLimitMiddleware","createCredentialsBarrier","createAuthIntegrationRouter","createLifecycleMiddleware","createCookieAuthRefreshMiddleware","MiddlewareFactory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,MAAM,2BAA2BA,qCAAA,CAAqB;AAAA,EAC3D,SAASC,6BAAA,CAAa,UAAA;AAAA,EACtB,cAAA,EAAgB,QA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AkB,MAAA,CAAO,EAAE,MAAA,EAAQ,QAAQ,CAAA;AAC9D,IAAA,MAAA,CAAO,GAAA,CAAI,UAAA,CAAW,KAAA,EAAO,CAAA;AAE7B,IAAA,OAAO;AAAA,MACL,IAAI,OAAA,EAAwB;AAC1B,QAAA,YAAA,CAAa,IAAI,OAAO,CAAA;AAAA,MAC1B,CAAA;AAAA,MACA,cAAc,MAAA,EAA2C;AACvD,QAAA,kBAAA,CAAmB,cAAc,MAAM,CAAA;AAAA,MACzC;AAAA,KACF;AAAA,EACF;AACF,CAAC;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycleServiceFactory.cjs.js","sources":["../../../src/entrypoints/lifecycle/lifecycleServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n LifecycleService,\n LifecycleServiceShutdownHook,\n LifecycleServiceShutdownOptions,\n LifecycleServiceStartupHook,\n LifecycleServiceStartupOptions,\n LoggerService,\n PluginMetadataService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class BackendPluginLifecycleImpl implements LifecycleService {\n private readonly logger: LoggerService;\n private readonly pluginMetadata: PluginMetadataService;\n\n constructor(logger: LoggerService, pluginMetadata: PluginMetadataService) {\n this.logger = logger;\n this.pluginMetadata = pluginMetadata;\n }\n\n #hasStarted = false;\n #hasShutdown = false;\n #startupTasks: Array<{\n hook: LifecycleServiceStartupHook;\n options?: LifecycleServiceStartupOptions;\n }> = [];\n #shutdownTasks: Array<{\n hook: LifecycleServiceShutdownHook;\n options?: LifecycleServiceShutdownOptions;\n }> = [];\n\n addStartupHook(\n hook: LifecycleServiceStartupHook,\n options?: LifecycleServiceStartupOptions,\n ): void {\n if (this.#hasStarted) {\n throw new Error('Attempted to add startup hook after startup');\n }\n this.#startupTasks.push({ hook, options });\n }\n\n async startup(): Promise<void> {\n if (this.#hasStarted) {\n return;\n }\n this.#hasStarted = true;\n\n this.logger.debug(\n `Running ${this.#startupTasks.length} plugin startup tasks...`,\n );\n await Promise.all(\n this.#startupTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Plugin startup hook succeeded`);\n } catch (error) {\n logger.error(`Plugin startup hook failed, ${error}`);\n }\n }),\n );\n }\n\n addShutdownHook(\n hook: LifecycleServiceShutdownHook,\n options?: LifecycleServiceShutdownOptions,\n ): void {\n if (this.#hasShutdown) {\n throw new Error('Attempted to add shutdown hook after shutdown');\n }\n const plugin = this.pluginMetadata.getId();\n const logger = options?.logger?.child({ plugin }) ?? this.logger;\n this.#shutdownTasks.push({\n hook,\n options: {\n ...options,\n logger,\n },\n });\n }\n\n async shutdown(): Promise<void> {\n if (this.#hasShutdown) {\n return;\n }\n this.#hasShutdown = true;\n\n this.logger.debug(\n `Running ${this.#shutdownTasks.length} plugin shutdown tasks...`,\n );\n\n await Promise.all(\n this.#shutdownTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Plugin shutdown hook succeeded`);\n } catch (error) {\n logger.error('Plugin shutdown hook failed', error);\n }\n }),\n );\n }\n}\n\n/**\n * Registration of plugin startup and shutdown lifecycle hooks.\n *\n * See {@link @backstage/code-plugin-api#LifecycleService}\n * and {@link https://backstage.io/docs/backend-system/core-services/lifecycle | the service docs}\n * for more information.\n *\n * @public\n */\nexport const lifecycleServiceFactory = createServiceFactory({\n service: coreServices.lifecycle,\n deps: {\n logger: coreServices.logger,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ logger, pluginMetadata }) {\n return new BackendPluginLifecycleImpl(logger, pluginMetadata);\n },\n});\n"],"names":["createServiceFactory","coreServices"],"mappings":";;;;AA6BO,MAAM,0BAAA,CAAuD;AAAA,EACjD,MAAA;AAAA,EACA,cAAA;AAAA,EAEjB,WAAA,CAAY,QAAuB,cAAA,EAAuC;AACxE,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,cAAA,GAAiB,cAAA;AAAA,EACxB;AAAA,EAEA,WAAA,GAAc,KAAA;AAAA,EACd,YAAA,GAAe,KAAA;AAAA,EACf,gBAGK,EAAC;AAAA,EACN,iBAGK,EAAC;AAAA,EAEN,cAAA,CACE,MACA,OAAA,EACM;AACN,IAAA,IAAI,KAAK,WAAA,EAAa;AACpB,MAAA,MAAM,IAAI,MAAM,6CAA6C,CAAA;AAAA,IAC/D;AACA,IAAA,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,EAAE,IAAA,EAAM,SAAS,CAAA;AAAA,EAC3C;AAAA,EAEA,MAAM,OAAA,GAAyB;AAC7B,IAAA,IAAI,KAAK,WAAA,EAAa;AACpB,MAAA;AAAA,IACF;AACA,IAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAEnB,IAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,MACV,CAAA,QAAA,EAAW,IAAA,CAAK,aAAA,CAAc,MAAM,CAAA,wBAAA;AAAA,KACtC;AACA,IAAA,MAAM,OAAA,CAAQ,GAAA;AAAA,MACZ,KAAK,aAAA,CAAc,GAAA,CAAI,OAAO,EAAE,IAAA,EAAM,SAAQ,KAAM;AAClD,QAAA,MAAM,MAAA,GAAS,OAAA,EAAS,MAAA,IAAU,IAAA,CAAK,MAAA;AACvC,QAAA,IAAI;AACF,UAAA,MAAM,IAAA,EAAK;AACX,UAAA,MAAA,CAAO,MAAM,CAAA,6BAAA,CAA+B,CAAA;AAAA,QAC9C,SAAS,KAAA,EAAO;AACd,UAAA,MAAA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AAA,KACH;AAAA,EACF;AACF;AAWO,MAAM,0BAA0BA,qCAAA,CAAqB;AAAA,EAC1D,SAASC,6BAAA,CAAa,SAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,QAAQA,6BAAA,CAAa,MAAA;AAAA,IACrB,gBAAgBA,6BAAA,CAAa;AAAA,GAC/B;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,MAAA,EAAQ,gBAAe,EAAG;AACxC,IAAA,OAAO,IAAI,0BAAA,CAA2B,MAAA,EAAQ,cAAc,CAAA;AAAA,EAC9D;AACF,CAAC
|
|
1
|
+
{"version":3,"file":"lifecycleServiceFactory.cjs.js","sources":["../../../src/entrypoints/lifecycle/lifecycleServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n LifecycleService,\n LifecycleServiceShutdownHook,\n LifecycleServiceShutdownOptions,\n LifecycleServiceStartupHook,\n LifecycleServiceStartupOptions,\n LoggerService,\n PluginMetadataService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class BackendPluginLifecycleImpl implements LifecycleService {\n private readonly logger: LoggerService;\n private readonly pluginMetadata: PluginMetadataService;\n\n constructor(logger: LoggerService, pluginMetadata: PluginMetadataService) {\n this.logger = logger;\n this.pluginMetadata = pluginMetadata;\n }\n\n #hasStarted = false;\n #hasShutdown = false;\n #startupTasks: Array<{\n hook: LifecycleServiceStartupHook;\n options?: LifecycleServiceStartupOptions;\n }> = [];\n #shutdownTasks: Array<{\n hook: LifecycleServiceShutdownHook;\n options?: LifecycleServiceShutdownOptions;\n }> = [];\n\n addStartupHook(\n hook: LifecycleServiceStartupHook,\n options?: LifecycleServiceStartupOptions,\n ): void {\n if (this.#hasStarted) {\n throw new Error('Attempted to add startup hook after startup');\n }\n this.#startupTasks.push({ hook, options });\n }\n\n async startup(): Promise<void> {\n if (this.#hasStarted) {\n return;\n }\n this.#hasStarted = true;\n\n this.logger.debug(\n `Running ${this.#startupTasks.length} plugin startup tasks...`,\n );\n await Promise.all(\n this.#startupTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Plugin startup hook succeeded`);\n } catch (error) {\n logger.error(`Plugin startup hook failed, ${error}`);\n }\n }),\n );\n }\n\n addShutdownHook(\n hook: LifecycleServiceShutdownHook,\n options?: LifecycleServiceShutdownOptions,\n ): void {\n if (this.#hasShutdown) {\n throw new Error('Attempted to add shutdown hook after shutdown');\n }\n const plugin = this.pluginMetadata.getId();\n const logger = options?.logger?.child({ plugin }) ?? this.logger;\n this.#shutdownTasks.push({\n hook,\n options: {\n ...options,\n logger,\n },\n });\n }\n\n async shutdown(): Promise<void> {\n if (this.#hasShutdown) {\n return;\n }\n this.#hasShutdown = true;\n\n this.logger.debug(\n `Running ${this.#shutdownTasks.length} plugin shutdown tasks...`,\n );\n\n await Promise.all(\n this.#shutdownTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Plugin shutdown hook succeeded`);\n } catch (error) {\n logger.error('Plugin shutdown hook failed', error);\n }\n }),\n );\n }\n}\n\n/**\n * Registration of plugin startup and shutdown lifecycle hooks.\n *\n * See {@link @backstage/code-plugin-api#LifecycleService}\n * and {@link https://backstage.io/docs/backend-system/core-services/lifecycle | the service docs}\n * for more information.\n *\n * @public\n */\nexport const lifecycleServiceFactory = createServiceFactory({\n service: coreServices.lifecycle,\n deps: {\n logger: coreServices.logger,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ logger, pluginMetadata }) {\n return new BackendPluginLifecycleImpl(logger, pluginMetadata);\n },\n});\n"],"names":["createServiceFactory","coreServices"],"mappings":";;;;AA6BO,MAAM,0BAAA,CAAuD;AAAA,EACjD,MAAA;AAAA,EACA,cAAA;AAAA,EAEjB,WAAA,CAAY,QAAuB,cAAA,EAAuC;AACxE,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,cAAA,GAAiB,cAAA;AAAA,EACxB;AAAA,EAEA,WAAA,GAAc,KAAA;AAAA,EACd,YAAA,GAAe,KAAA;AAAA,EACf,gBAGK,EAAC;AAAA,EACN,iBAGK,EAAC;AAAA,EAEN,cAAA,CACE,MACA,OAAA,EACM;AACN,IAAA,IAAI,KAAK,WAAA,EAAa;AACpB,MAAA,MAAM,IAAI,MAAM,6CAA6C,CAAA;AAAA,IAC/D;AACA,IAAA,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,EAAE,IAAA,EAAM,SAAS,CAAA;AAAA,EAC3C;AAAA,EAEA,MAAM,OAAA,GAAyB;AAC7B,IAAA,IAAI,KAAK,WAAA,EAAa;AACpB,MAAA;AAAA,IACF;AACA,IAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAEnB,IAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,MACV,CAAA,QAAA,EAAW,IAAA,CAAK,aAAA,CAAc,MAAM,CAAA,wBAAA;AAAA,KACtC;AACA,IAAA,MAAM,OAAA,CAAQ,GAAA;AAAA,MACZ,KAAK,aAAA,CAAc,GAAA,CAAI,OAAO,EAAE,IAAA,EAAM,SAAQ,KAAM;AAClD,QAAA,MAAM,MAAA,GAAS,OAAA,EAAS,MAAA,IAAU,IAAA,CAAK,MAAA;AACvC,QAAA,IAAI;AACF,UAAA,MAAM,IAAA,EAAK;AACX,UAAA,MAAA,CAAO,MAAM,CAAA,6BAAA,CAA+B,CAAA;AAAA,QAC9C,SAAS,KAAA,EAAO;AACd,UAAA,MAAA,CAAO,KAAA,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A,EACF;AACF;AAWO,MAAM,0BAA0BA,qCAAA,CAAqB;AAAA,EAC1D,SAASC,6BAAA,CAAa,SAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,QAAQA,6BAAA,CAAa,MAAA;AAAA,IACrB,gBAAgBA,6BAAA,CAAa;AAAA,GAC/B;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,MAAA,EAAQ,gBAAe,EAAG;AACxC,IAAA,OAAO,IAAI,0BAAA,CAA2B,MAAA,EAAQ,cAAc,CAAA;AAAA,EAC9D;AACF,CAAC;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loggerServiceFactory.cjs.js","sources":["../../../src/entrypoints/logger/loggerServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\n\n/**\n * Plugin-level logging.\n *\n * See {@link @backstage/code-plugin-api#LoggerService}\n * and {@link https://backstage.io/docs/backend-system/core-services/logger | the service docs}\n * for more information.\n *\n * @public\n */\nexport const loggerServiceFactory = createServiceFactory({\n service: coreServices.logger,\n deps: {\n rootLogger: coreServices.rootLogger,\n plugin: coreServices.pluginMetadata,\n },\n factory({ rootLogger, plugin }) {\n return rootLogger.child({ plugin: plugin.getId() });\n },\n});\n"],"names":["createServiceFactory","coreServices"],"mappings":";;;;AA8BO,MAAM,uBAAuBA,qCAAA,CAAqB;AAAA,EACvD,SAASC,6BAAA,CAAa,MAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,YAAYA,6BAAA,CAAa,UAAA;AAAA,IACzB,QAAQA,6BAAA,CAAa;AAAA,GACvB;AAAA,EACA,OAAA,CAAQ,EAAE,UAAA,EAAY,MAAA,EAAO,EAAG;AAC9B,IAAA,OAAO,WAAW,KAAA,CAAM,EAAE,QAAQ,MAAA,CAAO,KAAA,IAAS,CAAA;AAAA,EACpD;AACF,CAAC
|
|
1
|
+
{"version":3,"file":"loggerServiceFactory.cjs.js","sources":["../../../src/entrypoints/logger/loggerServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\n\n/**\n * Plugin-level logging.\n *\n * See {@link @backstage/code-plugin-api#LoggerService}\n * and {@link https://backstage.io/docs/backend-system/core-services/logger | the service docs}\n * for more information.\n *\n * @public\n */\nexport const loggerServiceFactory = createServiceFactory({\n service: coreServices.logger,\n deps: {\n rootLogger: coreServices.rootLogger,\n plugin: coreServices.pluginMetadata,\n },\n factory({ rootLogger, plugin }) {\n return rootLogger.child({ plugin: plugin.getId() });\n },\n});\n"],"names":["createServiceFactory","coreServices"],"mappings":";;;;AA8BO,MAAM,uBAAuBA,qCAAA,CAAqB;AAAA,EACvD,SAASC,6BAAA,CAAa,MAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,YAAYA,6BAAA,CAAa,UAAA;AAAA,IACzB,QAAQA,6BAAA,CAAa;AAAA,GACvB;AAAA,EACA,OAAA,CAAQ,EAAE,UAAA,EAAY,MAAA,EAAO,EAAG;AAC9B,IAAA,OAAO,WAAW,KAAA,CAAM,EAAE,QAAQ,MAAA,CAAO,KAAA,IAAS,CAAA;AAAA,EACpD;AACF,CAAC;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permissionsServiceFactory.cjs.js","sources":["../../../src/entrypoints/permissions/permissionsServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerPermissionClient } from '@backstage/plugin-permission-node';\n\n/**\n * Permission system integration for authorization of user actions.\n *\n * See {@link @backstage/code-plugin-api#PermissionsService}\n * and {@link https://backstage.io/docs/backend-system/core-services/permissions | the service docs}\n * for more information.\n *\n * @public\n */\nexport const permissionsServiceFactory = createServiceFactory({\n service: coreServices.permissions,\n deps: {\n auth: coreServices.auth,\n config: coreServices.rootConfig,\n discovery: coreServices.discovery,\n },\n async factory({ auth, config, discovery }) {\n return ServerPermissionClient.fromConfig(config, {\n auth,\n discovery,\n });\n },\n});\n"],"names":["createServiceFactory","coreServices","ServerPermissionClient"],"mappings":";;;;;AA+BO,MAAM,4BAA4BA,qCAAA,CAAqB;AAAA,EAC5D,SAASC,6BAAA,CAAa,WAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,MAAMA,6BAAA,CAAa,IAAA;AAAA,IACnB,QAAQA,6BAAA,CAAa,UAAA;AAAA,IACrB,WAAWA,6BAAA,CAAa;AAAA,GAC1B;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,IAAA,EAAM,MAAA,EAAQ,WAAU,EAAG;AACzC,IAAA,OAAOC,2CAAA,CAAuB,WAAW,MAAA,EAAQ;AAAA,MAC/C,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACF,CAAC
|
|
1
|
+
{"version":3,"file":"permissionsServiceFactory.cjs.js","sources":["../../../src/entrypoints/permissions/permissionsServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerPermissionClient } from '@backstage/plugin-permission-node';\n\n/**\n * Permission system integration for authorization of user actions.\n *\n * See {@link @backstage/code-plugin-api#PermissionsService}\n * and {@link https://backstage.io/docs/backend-system/core-services/permissions | the service docs}\n * for more information.\n *\n * @public\n */\nexport const permissionsServiceFactory = createServiceFactory({\n service: coreServices.permissions,\n deps: {\n auth: coreServices.auth,\n config: coreServices.rootConfig,\n discovery: coreServices.discovery,\n },\n async factory({ auth, config, discovery }) {\n return ServerPermissionClient.fromConfig(config, {\n auth,\n discovery,\n });\n },\n});\n"],"names":["createServiceFactory","coreServices","ServerPermissionClient"],"mappings":";;;;;AA+BO,MAAM,4BAA4BA,qCAAA,CAAqB;AAAA,EAC5D,SAASC,6BAAA,CAAa,WAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,MAAMA,6BAAA,CAAa,IAAA;AAAA,IACnB,QAAQA,6BAAA,CAAa,UAAA;AAAA,IACrB,WAAWA,6BAAA,CAAa;AAAA,GAC1B;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,IAAA,EAAM,MAAA,EAAQ,WAAU,EAAG;AACzC,IAAA,OAAOC,2CAAA,CAAuB,WAAW,MAAA,EAAQ;AAAA,MAC/C,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACF,CAAC;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permissionsRegistryServiceFactory.cjs.js","sources":["../../../src/entrypoints/permissionsRegistry/permissionsRegistryServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PermissionsRegistryService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n PermissionResourceRef,\n createPermissionIntegrationRouter,\n} from '@backstage/plugin-permission-node';\nimport { NotAllowedError } from '@backstage/errors';\nimport Router from 'express-promise-router';\n\nfunction assertRefPluginId(ref: PermissionResourceRef, pluginId: string) {\n if (ref.pluginId !== pluginId) {\n throw new Error(\n `Resource type '${ref.resourceType}' belongs to plugin '${ref.pluginId}', but was used with plugin '${pluginId}'`,\n );\n }\n}\n\n/**\n * Permission system integration for registering resources and permissions.\n *\n * See {@link @backstage/core-plugin-api#PermissionsRegistryService}\n * and {@link https://backstage.io/docs/backend-system/core-services/permission-integrations | the service docs}\n * for more information.\n *\n * @public\n */\nexport const permissionsRegistryServiceFactory = createServiceFactory({\n service: coreServices.permissionsRegistry,\n deps: {\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n lifecycle: coreServices.lifecycle,\n httpRouter: coreServices.httpRouter,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ auth, httpAuth, httpRouter, lifecycle, pluginMetadata }) {\n const router = createPermissionIntegrationRouter();\n\n const pluginId = pluginMetadata.getId();\n\n const applyConditionMiddleware = Router();\n applyConditionMiddleware.use(\n '/.well-known/backstage/permissions/apply-conditions',\n async (req, _res, next) => {\n const credentials = await httpAuth.credentials(req, {\n allow: ['user', 'service'],\n });\n if (\n auth.isPrincipal(credentials, 'user') &&\n !credentials.principal.actor\n ) {\n throw new NotAllowedError();\n }\n next();\n },\n );\n httpRouter.use(applyConditionMiddleware);\n httpRouter.use(router);\n\n let started = false;\n lifecycle.addStartupHook(() => {\n started = true;\n });\n\n return {\n addResourceType(resource) {\n if (started) {\n throw new Error(\n 'Cannot add permission resource types after the plugin has started',\n );\n }\n assertRefPluginId(resource.resourceRef, pluginId);\n router.addResourceType({\n ...resource,\n resourceType: resource.resourceRef.resourceType,\n });\n },\n addPermissions(permissions) {\n if (started) {\n throw new Error(\n 'Cannot add permissions after the plugin has started',\n );\n }\n router.addPermissions(permissions);\n },\n addPermissionRules(rules) {\n if (started) {\n throw new Error(\n 'Cannot add permission rules after the plugin has started',\n );\n }\n router.addPermissionRules(rules);\n },\n getPermissionRuleset(resourceRef) {\n assertRefPluginId(resourceRef, pluginId);\n return router.getPermissionRuleset(resourceRef);\n },\n } satisfies PermissionsRegistryService;\n },\n});\n"],"names":["createServiceFactory","coreServices","createPermissionIntegrationRouter","Router","NotAllowedError"],"mappings":";;;;;;;;;;;AA4BA,SAAS,iBAAA,CAAkB,KAA4B,QAAA,EAAkB;AACvE,EAAA,IAAI,GAAA,CAAI,aAAa,QAAA,EAAU;AAC7B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,kBAAkB,GAAA,CAAI,YAAY,wBAAwB,GAAA,CAAI,QAAQ,gCAAgC,QAAQ,CAAA,CAAA;AAAA,KAChH;AAAA,EACF;AACF;AAWO,MAAM,oCAAoCA,qCAAA,CAAqB;AAAA,EACpE,SAASC,6BAAA,CAAa,mBAAA;AAAA,EACtB,IAAA,EAAM;AA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,CAAS,aAAa,QAAQ,CAAA;AAChD,QAAA,MAAA,CAAO,eAAA,CAAgB;AAAA,UACrB,GAAG,QAAA;AAAA,UACH,YAAA,EAAc,SAAS,WAAA,CAAY;AAAA,SACpC,CAAA;AAAA,MACH,CAAA;AAAA,MACA,eAAe,WAAA,EAAa;AAC1B,QAAA,IAAI,OAAA,EAAS;AACX,UAAA,MAAM,IAAI,KAAA;AAAA,YACR;AAAA,WACF;AAAA,QACF;AACA,QAAA,MAAA,CAAO,eAAe,WAAW,CAAA;AAAA,MACnC,CAAA;AAAA,MACA,mBAAmB,KAAA,EAAO;AACxB,QAAA,IAAI,OAAA,EAAS;AACX,UAAA,MAAM,IAAI,KAAA;AAAA,YACR;AAAA,WACF;AAAA,QACF;AACA,QAAA,MAAA,CAAO,mBAAmB,KAAK,CAAA;AAAA,MACjC,CAAA;AAAA,MACA,qBAAqB,WAAA,EAAa;AAChC,QAAA,iBAAA,CAAkB,aAAa,QAAQ,CAAA;AACvC,QAAA,OAAO,MAAA,CAAO,qBAAqB,WAAW,CAAA;AAAA,MAChD;AAAA,KACF;AAAA,EACF;AACF,CAAC
|
|
1
|
+
{"version":3,"file":"permissionsRegistryServiceFactory.cjs.js","sources":["../../../src/entrypoints/permissionsRegistry/permissionsRegistryServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PermissionsRegistryService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n PermissionResourceRef,\n createPermissionIntegrationRouter,\n} from '@backstage/plugin-permission-node';\nimport { NotAllowedError } from '@backstage/errors';\nimport Router from 'express-promise-router';\n\nfunction assertRefPluginId(ref: PermissionResourceRef, pluginId: string) {\n if (ref.pluginId !== pluginId) {\n throw new Error(\n `Resource type '${ref.resourceType}' belongs to plugin '${ref.pluginId}', but was used with plugin '${pluginId}'`,\n );\n }\n}\n\n/**\n * Permission system integration for registering resources and permissions.\n *\n * See {@link @backstage/core-plugin-api#PermissionsRegistryService}\n * and {@link https://backstage.io/docs/backend-system/core-services/permission-integrations | the service docs}\n * for more information.\n *\n * @public\n */\nexport const permissionsRegistryServiceFactory = createServiceFactory({\n service: coreServices.permissionsRegistry,\n deps: {\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n lifecycle: coreServices.lifecycle,\n httpRouter: coreServices.httpRouter,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ auth, httpAuth, httpRouter, lifecycle, pluginMetadata }) {\n const router = createPermissionIntegrationRouter();\n\n const pluginId = pluginMetadata.getId();\n\n const applyConditionMiddleware = Router();\n applyConditionMiddleware.use(\n '/.well-known/backstage/permissions/apply-conditions',\n async (req, _res, next) => {\n const credentials = await httpAuth.credentials(req, {\n allow: ['user', 'service'],\n });\n if (\n auth.isPrincipal(credentials, 'user') &&\n !credentials.principal.actor\n ) {\n throw new NotAllowedError();\n }\n next();\n },\n );\n httpRouter.use(applyConditionMiddleware);\n httpRouter.use(router);\n\n let started = false;\n lifecycle.addStartupHook(() => {\n started = true;\n });\n\n return {\n addResourceType(resource) {\n if (started) {\n throw new Error(\n 'Cannot add permission resource types after the plugin has started',\n );\n }\n assertRefPluginId(resource.resourceRef, pluginId);\n router.addResourceType({\n ...resource,\n resourceType: resource.resourceRef.resourceType,\n });\n },\n addPermissions(permissions) {\n if (started) {\n throw new Error(\n 'Cannot add permissions after the plugin has started',\n );\n }\n router.addPermissions(permissions);\n },\n addPermissionRules(rules) {\n if (started) {\n throw new Error(\n 'Cannot add permission rules after the plugin has started',\n );\n }\n router.addPermissionRules(rules);\n },\n getPermissionRuleset(resourceRef) {\n assertRefPluginId(resourceRef, pluginId);\n return router.getPermissionRuleset(resourceRef);\n },\n } satisfies PermissionsRegistryService;\n },\n});\n"],"names":["createServiceFactory","coreServices","createPermissionIntegrationRouter","Router","NotAllowedError"],"mappings":";;;;;;;;;;;AA4BA,SAAS,iBAAA,CAAkB,KAA4B,QAAA,EAAkB;AACvE,EAAA,IAAI,GAAA,CAAI,aAAa,QAAA,EAAU;AAC7B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,kBAAkB,GAAA,CAAI,YAAY,wBAAwB,GAAA,CAAI,QAAQ,gCAAgC,QAAQ,CAAA,CAAA;AAAA,KAChH;AAAA,EACF;AACF;AAWO,MAAM,oCAAoCA,qCAAA,CAAqB;AAAA,EACpE,SAASC,6BAAA,CAAa,mBAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,MAAMA,6BAAA,CAAa,IAAA;AAAA,IACnB,UAAUA,6BAAA,CAAa,QAAA;AAAA,IACvB,WAAWA,6BAAA,CAAa,SAAA;AAAA,IACxB,YAAYA,6BAAA,CAAa,UAAA;AAAA,IACzB,gBAAgBA,6BAAA,CAAa;AAAA,GAC/B;AAAA,EACA,MAAM,QAAQ,EAAE,IAAA,EAAM,UAAU,UAAA,EAAY,SAAA,EAAW,gBAAe,EAAG;AACvE,IAAA,MAAM,SAASC,sDAAA,EAAkC;AAEjD,IAAA,MAAM,QAAA,GAAW,eAAe,KAAA,EAAM;AAEtC,IAAA,MAAM,2BAA2BC,uBAAA,EAAO;AACxC,IAAA,wBAAA,CAAyB,GAAA;AAAA,MACvB,qDAAA;AAAA,MACA,OAAO,GAAA,EAAK,IAAA,EAAM,IAAA,KAAS;AACzB,QAAA,MAAM,WAAA,GAAc,MAAM,QAAA,CAAS,WAAA,CAAY,GAAA,EAAK;AAAA,UAClD,KAAA,EAAO,CAAC,MAAA,EAAQ,SAAS;AAAA,SAC1B,CAAA;AACD,QAAA,IACE,IAAA,CAAK,YAAY,WAAA,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;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createConfigSecretEnumerator.cjs.js","sources":["../../../src/entrypoints/rootConfig/createConfigSecretEnumerator.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport { ConfigSchema, loadConfigSchema } from '@backstage/config-loader';\nimport { getPackages } from '@manypkg/get-packages';\n\n/** @public */\nexport async function createConfigSecretEnumerator(options: {\n logger: LoggerService;\n dir?: string;\n schema?: ConfigSchema;\n}): Promise<(config: Config) => Iterable<string>> {\n const { logger, dir = process.cwd() } = options;\n const { packages } = await getPackages(dir);\n const schema =\n options.schema ??\n (await loadConfigSchema({\n dependencies: packages.map(p => p.packageJson.name),\n onSchemaError: error => logger.warn(error.message),\n }));\n\n return (config: Config) => {\n const [secretsData] = schema.process(\n [{ data: config.getOptional() ?? {}, context: 'schema-enumerator' }],\n {\n visibility: ['secret'],\n ignoreSchemaErrors: true,\n },\n );\n const secrets = new Set<string>();\n JSON.parse(\n JSON.stringify(secretsData.data),\n (_, v) => typeof v === 'string' && secrets.add(v),\n );\n logger.info(\n `Found ${secrets.size} new secrets in config that will be redacted`,\n );\n return secrets;\n };\n}\n"],"names":["getPackages","loadConfigSchema"],"mappings":";;;;;AAsBA,eAAsB,6BAA6B,OAAA,EAID;AAChD,EAAA,MAAM,EAAE,MAAA,EAAQ,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAM,GAAI,OAAA;AACxC,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAMA,wBAAY,GAAG,CAAA;AAC1C,EAAA,MAAM,MAAA,GACJ,OAAA,CAAQ,MAAA,IACP,MAAMC,6BAAA,CAAiB;AAAA,IACtB,cAAc,QAAA,CAAS,GAAA,CAAI,CAAA,CAAA,KAAK,CAAA,CAAE,YAAY,IAAI,CAAA;AAAA,IAClD,aAAA,EAAe,CAAA,KAAA,KAAS,MAAA,CAAO,IAAA,CAAK,MAAM,OAAO;AAAA,GAClD,CAAA;AAEH,EAAA,OAAO,CAAC,MAAA,KAAmB;AACzB,IAAA,MAAM,CAAC,WAAW,CAAA,GAAI,MAAA,CAAO,OAAA;AAAA,MAC3B,CAAC,EAAE,IAAA,EAAM,MAAA,CAAO,WAAA,MAAiB,EAAC,EAAG,OAAA,EAAS,mBAAA,EAAqB,CAAA;AAAA,MACnE;AAAA,QACE,UAAA,EAAY,CAAC,QAAQ,CAAA;AAAA,QACrB,kBAAA,EAAoB;AAAA;AACtB,KACF;AACA,IAAA,MAAM,OAAA,uBAAc,GAAA,EAAY;AAChC,IAAA,IAAA,CAAK,KAAA;AAAA,MACH,IAAA,CAAK,SAAA,CAAU,WAAA,CAAY,IAAI,CAAA;AAAA,MAC/B,CAAC,GAAG,CAAA,KAAM,OAAO,MAAM,QAAA,IAAY,OAAA,CAAQ,IAAI,CAAC;AAAA,KAClD;AACA,IAAA,MAAA,CAAO,IAAA;AAAA,MACL,CAAA,MAAA,EAAS,QAAQ,IAAI,CAAA,4CAAA;AAAA,KACvB;AACA,IAAA,OAAO,OAAA;AAAA,EACT,CAAA;AACF
|
|
1
|
+
{"version":3,"file":"createConfigSecretEnumerator.cjs.js","sources":["../../../src/entrypoints/rootConfig/createConfigSecretEnumerator.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport { ConfigSchema, loadConfigSchema } from '@backstage/config-loader';\nimport { getPackages } from '@manypkg/get-packages';\n\n/** @public */\nexport async function createConfigSecretEnumerator(options: {\n logger: LoggerService;\n dir?: string;\n schema?: ConfigSchema;\n}): Promise<(config: Config) => Iterable<string>> {\n const { logger, dir = process.cwd() } = options;\n const { packages } = await getPackages(dir);\n const schema =\n options.schema ??\n (await loadConfigSchema({\n dependencies: packages.map(p => p.packageJson.name),\n onSchemaError: error => logger.warn(error.message),\n }));\n\n return (config: Config) => {\n const [secretsData] = schema.process(\n [{ data: config.getOptional() ?? {}, context: 'schema-enumerator' }],\n {\n visibility: ['secret'],\n ignoreSchemaErrors: true,\n },\n );\n const secrets = new Set<string>();\n JSON.parse(\n JSON.stringify(secretsData.data),\n (_, v) => typeof v === 'string' && secrets.add(v),\n );\n logger.info(\n `Found ${secrets.size} new secrets in config that will be redacted`,\n );\n return secrets;\n };\n}\n"],"names":["getPackages","loadConfigSchema"],"mappings":";;;;;AAsBA,eAAsB,6BAA6B,OAAA,EAID;AAChD,EAAA,MAAM,EAAE,MAAA,EAAQ,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAM,GAAI,OAAA;AACxC,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAMA,wBAAY,GAAG,CAAA;AAC1C,EAAA,MAAM,MAAA,GACJ,OAAA,CAAQ,MAAA,IACP,MAAMC,6BAAA,CAAiB;AAAA,IACtB,cAAc,QAAA,CAAS,GAAA,CAAI,CAAA,CAAA,KAAK,CAAA,CAAE,YAAY,IAAI,CAAA;AAAA,IAClD,aAAA,EAAe,CAAA,KAAA,KAAS,MAAA,CAAO,IAAA,CAAK,MAAM,OAAO;AAAA,GAClD,CAAA;AAEH,EAAA,OAAO,CAAC,MAAA,KAAmB;AACzB,IAAA,MAAM,CAAC,WAAW,CAAA,GAAI,MAAA,CAAO,OAAA;AAAA,MAC3B,CAAC,EAAE,IAAA,EAAM,MAAA,CAAO,WAAA,MAAiB,EAAC,EAAG,OAAA,EAAS,mBAAA,EAAqB,CAAA;AAAA,MACnE;AAAA,QACE,UAAA,EAAY,CAAC,QAAQ,CAAA;AAAA,QACrB,kBAAA,EAAoB;AAAA;AACtB,KACF;AACA,IAAA,MAAM,OAAA,uBAAc,GAAA,EAAY;AAChC,IAAA,IAAA,CAAK,KAAA;AAAA,MACH,IAAA,CAAK,SAAA,CAAU,WAAA,CAAY,IAAI,CAAA;AAAA,MAC/B,CAAC,GAAG,CAAA,KAAM,OAAO,MAAM,QAAA,IAAY,OAAA,CAAQ,IAAI,CAAC;AAAA,KAClD;AACA,IAAA,MAAA,CAAO,IAAA;AAAA,MACL,CAAA,MAAA,EAAS,QAAQ,IAAI,CAAA,4CAAA;AAAA,KACvB;AACA,IAAA,OAAO,OAAA;AAAA,EACT,CAAA;AACF;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rootConfigServiceFactory.cjs.js","sources":["../../../src/entrypoints/rootConfig/rootConfigServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n ConfigSources,\n RemoteConfigSourceOptions,\n} from '@backstage/config-loader';\n\n/**\n * Access to static configuration.\n *\n * See {@link @backstage/code-plugin-api#RootConfigService}\n * and {@link https://backstage.io/docs/backend-system/core-services/root-config | the service docs}\n * for more information.\n *\n * @public\n */\nexport interface RootConfigFactoryOptions {\n /**\n * Process arguments to use instead of the default `process.argv()`.\n */\n argv?: string[];\n\n /**\n * Enables and sets options for remote configuration loading.\n */\n remote?: Pick<RemoteConfigSourceOptions, 'reloadInterval'>;\n watch?: boolean;\n}\n\nexport const rootConfigServiceFactoryWithOptions = (\n options?: RootConfigFactoryOptions,\n) =>\n createServiceFactory({\n service: coreServices.rootConfig,\n deps: {},\n async factory() {\n const source = ConfigSources.default({\n argv: options?.argv,\n remote: options?.remote,\n watch: options?.watch,\n });\n console.log(`Loading config from ${source}`);\n return await ConfigSources.toConfig(source);\n },\n });\n\n/**\n * @public\n */\nexport const rootConfigServiceFactory = Object.assign(\n rootConfigServiceFactoryWithOptions,\n rootConfigServiceFactoryWithOptions(),\n);\n"],"names":["createServiceFactory","coreServices","ConfigSources"],"mappings":";;;;;AA+CO,MAAM,mCAAA,GAAsC,CACjD,OAAA,KAEAA,qCAAA,CAAqB;AAAA,EACnB,SAASC,6BAAA,CAAa,UAAA;AAAA,EACtB,MAAM,EAAC;AAAA,EACP,MAAM,OAAA,GAAU;AACd,IAAA,MAAM,MAAA,GAASC,2BAAc,OAAA,CAAQ;AAAA,MACnC,MAAM,OAAA,EAAS,IAAA;AAAA,MACf,QAAQ,OAAA,EAAS,MAAA;AAAA,MACjB,OAAO,OAAA,EAAS;AAAA,KACjB,CAAA;AACD,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,oBAAA,EAAuB,MAAM,CAAA,CAAE,CAAA;AAC3C,IAAA,OAAO,MAAMA,0BAAA,CAAc,QAAA,CAAS,MAAM,CAAA;AAAA,EAC5C;AACF,CAAC;AAKI,MAAM,2BAA2B,MAAA,CAAO,MAAA;AAAA,EAC7C,mCAAA;AAAA,EACA,mCAAA;AACF
|
|
1
|
+
{"version":3,"file":"rootConfigServiceFactory.cjs.js","sources":["../../../src/entrypoints/rootConfig/rootConfigServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n ConfigSources,\n RemoteConfigSourceOptions,\n} from '@backstage/config-loader';\n\n/**\n * Access to static configuration.\n *\n * See {@link @backstage/code-plugin-api#RootConfigService}\n * and {@link https://backstage.io/docs/backend-system/core-services/root-config | the service docs}\n * for more information.\n *\n * @public\n */\nexport interface RootConfigFactoryOptions {\n /**\n * Process arguments to use instead of the default `process.argv()`.\n */\n argv?: string[];\n\n /**\n * Enables and sets options for remote configuration loading.\n */\n remote?: Pick<RemoteConfigSourceOptions, 'reloadInterval'>;\n watch?: boolean;\n}\n\nexport const rootConfigServiceFactoryWithOptions = (\n options?: RootConfigFactoryOptions,\n) =>\n createServiceFactory({\n service: coreServices.rootConfig,\n deps: {},\n async factory() {\n const source = ConfigSources.default({\n argv: options?.argv,\n remote: options?.remote,\n watch: options?.watch,\n });\n console.log(`Loading config from ${source}`);\n return await ConfigSources.toConfig(source);\n },\n });\n\n/**\n * @public\n */\nexport const rootConfigServiceFactory = Object.assign(\n rootConfigServiceFactoryWithOptions,\n rootConfigServiceFactoryWithOptions(),\n);\n"],"names":["createServiceFactory","coreServices","ConfigSources"],"mappings":";;;;;AA+CO,MAAM,mCAAA,GAAsC,CACjD,OAAA,KAEAA,qCAAA,CAAqB;AAAA,EACnB,SAASC,6BAAA,CAAa,UAAA;AAAA,EACtB,MAAM,EAAC;AAAA,EACP,MAAM,OAAA,GAAU;AACd,IAAA,MAAM,MAAA,GAASC,2BAAc,OAAA,CAAQ;AAAA,MACnC,MAAM,OAAA,EAAS,IAAA;AAAA,MACf,QAAQ,OAAA,EAAS,MAAA;AAAA,MACjB,OAAO,OAAA,EAAS;AAAA,KACjB,CAAA;AACD,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,oBAAA,EAAuB,MAAM,CAAA,CAAE,CAAA;AAC3C,IAAA,OAAO,MAAMA,0BAAA,CAAc,QAAA,CAAS,MAAM,CAAA;AAAA,EAC5C;AACF,CAAC;AAKI,MAAM,2BAA2B,MAAA,CAAO,MAAA;AAAA,EAC7C,mCAAA;AAAA,EACA,mCAAA;AACF;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rootHealthServiceFactory.cjs.js","sources":["../../../src/entrypoints/rootHealth/rootHealthServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RootHealthService,\n RootLifecycleService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class DefaultRootHealthService implements RootHealthService {\n #state: 'init' | 'up' | 'down' = 'init';\n readonly options: { lifecycle: RootLifecycleService };\n\n constructor(options: { lifecycle: RootLifecycleService }) {\n this.options = options;\n options.lifecycle.addStartupHook(() => {\n this.#state = 'up';\n });\n options.lifecycle.addBeforeShutdownHook(() => {\n this.#state = 'down';\n });\n }\n\n async getLiveness(): Promise<{ status: number; payload?: any }> {\n return { status: 200, payload: { status: 'ok' } };\n }\n\n async getReadiness(): Promise<{ status: number; payload?: any }> {\n if (this.#state === 'init') {\n return {\n status: 503,\n payload: { message: 'Backend has not started yet', status: 'error' },\n };\n }\n if (this.#state === 'down') {\n return {\n status: 503,\n payload: { message: 'Backend is shutting down', status: 'error' },\n };\n }\n\n return { status: 200, payload: { status: 'ok' } };\n }\n}\n\n/**\n * @public\n */\nexport const rootHealthServiceFactory = createServiceFactory({\n service: coreServices.rootHealth,\n deps: {\n lifecycle: coreServices.rootLifecycle,\n },\n async factory({ lifecycle }) {\n return new DefaultRootHealthService({ lifecycle });\n },\n});\n"],"names":["createServiceFactory","coreServices"],"mappings":";;;;AAwBO,MAAM,wBAAA,CAAsD;AAAA,EACjE,MAAA,GAAiC,MAAA;AAAA,EACxB,OAAA;AAAA,EAET,YAAY,OAAA,EAA8C;AACxD,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,OAAA,CAAQ,SAAA,CAAU,eAAe,MAAM;AACrC,MAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AAAA,IAChB,CAAC,CAAA;AACD,IAAA,OAAA,CAAQ,SAAA,CAAU,sBAAsB,MAAM;AAC5C,MAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,IAChB,CAAC,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,WAAA,GAA0D;AAC9D,IAAA,OAAO,EAAE,MAAA,EAAQ,GAAA,EAAK,SAAS,EAAE,MAAA,EAAQ,MAAK,EAAE;AAAA,EAClD;AAAA,EAEA,MAAM,YAAA,GAA2D;AAC/D,IAAA,IAAI,IAAA,CAAK,WAAW,MAAA,EAAQ;AAC1B,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,GAAA;AAAA,QACR,OAAA,EAAS,EAAE,OAAA,EAAS,6BAAA,EAA+B,QAAQ,OAAA;AAAQ,OACrE;AAAA,IACF;AACA,IAAA,IAAI,IAAA,CAAK,WAAW,MAAA,EAAQ;AAC1B,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,GAAA;AAAA,QACR,OAAA,EAAS,EAAE,OAAA,EAAS,0BAAA,EAA4B,QAAQ,OAAA;AAAQ,OAClE;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,MAAA,EAAQ,GAAA,EAAK,SAAS,EAAE,MAAA,EAAQ,MAAK,EAAE;AAAA,EAClD;AACF;AAKO,MAAM,2BAA2BA,qCAAA,CAAqB;AAAA,EAC3D,SAASC,6BAAA,CAAa,UAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,WAAWA,6BAAA,CAAa;AAAA,GAC1B;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,SAAA,EAAU,EAAG;AAC3B,IAAA,OAAO,IAAI,wBAAA,CAAyB,EAAE,SAAA,EAAW,CAAA;AAAA,EACnD;AACF,CAAC
|
|
1
|
+
{"version":3,"file":"rootHealthServiceFactory.cjs.js","sources":["../../../src/entrypoints/rootHealth/rootHealthServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RootHealthService,\n RootLifecycleService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class DefaultRootHealthService implements RootHealthService {\n #state: 'init' | 'up' | 'down' = 'init';\n readonly options: { lifecycle: RootLifecycleService };\n\n constructor(options: { lifecycle: RootLifecycleService }) {\n this.options = options;\n options.lifecycle.addStartupHook(() => {\n this.#state = 'up';\n });\n options.lifecycle.addBeforeShutdownHook(() => {\n this.#state = 'down';\n });\n }\n\n async getLiveness(): Promise<{ status: number; payload?: any }> {\n return { status: 200, payload: { status: 'ok' } };\n }\n\n async getReadiness(): Promise<{ status: number; payload?: any }> {\n if (this.#state === 'init') {\n return {\n status: 503,\n payload: { message: 'Backend has not started yet', status: 'error' },\n };\n }\n if (this.#state === 'down') {\n return {\n status: 503,\n payload: { message: 'Backend is shutting down', status: 'error' },\n };\n }\n\n return { status: 200, payload: { status: 'ok' } };\n }\n}\n\n/**\n * @public\n */\nexport const rootHealthServiceFactory = createServiceFactory({\n service: coreServices.rootHealth,\n deps: {\n lifecycle: coreServices.rootLifecycle,\n },\n async factory({ lifecycle }) {\n return new DefaultRootHealthService({ lifecycle });\n },\n});\n"],"names":["createServiceFactory","coreServices"],"mappings":";;;;AAwBO,MAAM,wBAAA,CAAsD;AAAA,EACjE,MAAA,GAAiC,MAAA;AAAA,EACxB,OAAA;AAAA,EAET,YAAY,OAAA,EAA8C;AACxD,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,OAAA,CAAQ,SAAA,CAAU,eAAe,MAAM;AACrC,MAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AAAA,IAChB,CAAC,CAAA;AACD,IAAA,OAAA,CAAQ,SAAA,CAAU,sBAAsB,MAAM;AAC5C,MAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,IAChB,CAAC,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,WAAA,GAA0D;AAC9D,IAAA,OAAO,EAAE,MAAA,EAAQ,GAAA,EAAK,SAAS,EAAE,MAAA,EAAQ,MAAK,EAAE;AAAA,EAClD;AAAA,EAEA,MAAM,YAAA,GAA2D;AAC/D,IAAA,IAAI,IAAA,CAAK,WAAW,MAAA,EAAQ;AAC1B,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,GAAA;AAAA,QACR,OAAA,EAAS,EAAE,OAAA,EAAS,6BAAA,EAA+B,QAAQ,OAAA;AAAQ,OACrE;AAAA,IACF;AACA,IAAA,IAAI,IAAA,CAAK,WAAW,MAAA,EAAQ;AAC1B,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,GAAA;AAAA,QACR,OAAA,EAAS,EAAE,OAAA,EAAS,0BAAA,EAA4B,QAAQ,OAAA;AAAQ,OAClE;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,MAAA,EAAQ,GAAA,EAAK,SAAS,EAAE,MAAA,EAAQ,MAAK,EAAE;AAAA,EAClD;AACF;AAKO,MAAM,2BAA2BA,qCAAA,CAAqB;AAAA,EAC3D,SAASC,6BAAA,CAAa,UAAA;AAAA,EACtB,IAAA,EAAM;AAAA,IACJ,WAAWA,6BAAA,CAAa;AAAA,GAC1B;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,SAAA,EAAU,EAAG;AAC3B,IAAA,OAAO,IAAI,wBAAA,CAAyB,EAAE,SAAA,EAAW,CAAA;AAAA,EACnD;AACF,CAAC;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DefaultRootHttpRouter.cjs.js","sources":["../../../src/entrypoints/rootHttpRouter/DefaultRootHttpRouter.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RootHttpRouterService } from '@backstage/backend-plugin-api';\nimport { Handler, Router } from 'express';\nimport trimEnd from 'lodash/trimEnd';\n\nfunction normalizePath(path: string): string {\n return `${trimEnd(path, '/')}/`.toLowerCase();\n}\n\n/**\n * Options for the {@link DefaultRootHttpRouter} class.\n *\n * @public\n */\nexport interface DefaultRootHttpRouterOptions {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n}\n\n/**\n * The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for\n * {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.\n *\n * @public\n */\nexport class DefaultRootHttpRouter implements RootHttpRouterService {\n #indexPath?: string;\n\n #router = Router();\n #namedRoutes = Router();\n #indexRouter = Router();\n #existingPaths = new Array<string>();\n\n static create(options?: DefaultRootHttpRouterOptions) {\n let indexPath;\n if (options?.indexPath === false) {\n indexPath = undefined;\n } else if (options?.indexPath === undefined) {\n indexPath = '/api/app';\n } else if (options?.indexPath === '') {\n throw new Error('indexPath option may not be an empty string');\n } else {\n indexPath = options.indexPath;\n }\n return new DefaultRootHttpRouter(indexPath);\n }\n\n private constructor(indexPath?: string) {\n this.#indexPath = indexPath;\n this.#router.use(this.#namedRoutes);\n\n // Any request with a /api/ prefix will skip the index router, even if no named router matches\n this.#router.use('/api/', (_req, _res, next) => {\n next('router');\n });\n\n if (this.#indexPath) {\n this.#router.use(this.#indexRouter);\n }\n }\n\n use(path: string, handler: Handler) {\n if (path.match(/^[/\\s]*$/)) {\n throw new Error(`Root router path may not be empty`);\n }\n const conflictingPath = this.#findConflictingPath(path);\n if (conflictingPath) {\n throw new Error(\n `Path ${path} conflicts with the existing path ${conflictingPath}`,\n );\n }\n this.#existingPaths.push(path);\n this.#namedRoutes.use(path, handler);\n\n if (this.#indexPath === path) {\n this.#indexRouter.use(handler);\n }\n }\n\n handler(): Handler {\n return this.#router;\n }\n\n #findConflictingPath(newPath: string): string | undefined {\n const normalizedNewPath = normalizePath(newPath);\n for (const path of this.#existingPaths) {\n const normalizedPath = normalizePath(path);\n if (normalizedPath.startsWith(normalizedNewPath)) {\n return path;\n }\n if (normalizedNewPath.startsWith(normalizedPath)) {\n return path;\n }\n }\n return undefined;\n }\n}\n"],"names":["trimEnd","Router"],"mappings":";;;;;;;;;AAoBA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,GAAGA,wBAAA,CAAQ,IAAA,EAAM,GAAG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G;AAC1B,MAAA,MAAM,IAAI,MAAM,CAAA,iCAAA,CAAmC,CAAA;AAAA,IACrD;AACA,IAAA,MAAM,eAAA,GAAkB,IAAA,CAAK,oBAAA,CAAqB,IAAI,CAAA;AACtD,IAAA,IAAI,eAAA,EAAiB;AACnB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,KAAA,EAAQ,IAAI,CAAA,kCAAA,EAAqC,eAAe,CAAA;AAAA,OAClE;AAAA,IACF;AACA,IAAA,IAAA,CAAK,cAAA,CAAe,KAAK,IAAI,CAAA;AAC7B,IAAA,IAAA,CAAK,YAAA,CAAa,GAAA,CAAI,IAAA,EAAM,OAAO,CAAA;AAEnC,IAAA,IAAI,IAAA,CAAK,eAAe,IAAA,EAAM;AAC5B,MAAA,IAAA,CAAK,YAAA,CAAa,IAAI,OAAO,CAAA;AAAA,IAC/B;AAAA,EACF;AAAA,EAEA,OAAA,GAAmB;AACjB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA,EAEA,qBAAqB,OAAA,EAAqC;AACxD,IAAA,MAAM,iBAAA,GAAoB,cAAc,OAAO,CAAA;AAC/C,IAAA,KAAA,MAAW,IAAA,IAAQ,KAAK,cAAA,EAAgB;AACtC,MAAA,MAAM,cAAA,GAAiB,cAAc,IAAI,CAAA;AACzC,MAAA,IAAI,cAAA,CAAe,UAAA,CAAW,iBAAiB,CAAA,EAAG;AAChD,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,IAAI,iBAAA,CAAkB,UAAA,CAAW,cAAc,CAAA,EAAG;AAChD,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF
|
|
1
|
+
{"version":3,"file":"DefaultRootHttpRouter.cjs.js","sources":["../../../src/entrypoints/rootHttpRouter/DefaultRootHttpRouter.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RootHttpRouterService } from '@backstage/backend-plugin-api';\nimport { Handler, Router } from 'express';\nimport trimEnd from 'lodash/trimEnd';\n\nfunction normalizePath(path: string): string {\n return `${trimEnd(path, '/')}/`.toLowerCase();\n}\n\n/**\n * Options for the {@link DefaultRootHttpRouter} class.\n *\n * @public\n */\nexport interface DefaultRootHttpRouterOptions {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n}\n\n/**\n * The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for\n * {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.\n *\n * @public\n */\nexport class DefaultRootHttpRouter implements RootHttpRouterService {\n #indexPath?: string;\n\n #router = Router();\n #namedRoutes = Router();\n #indexRouter = Router();\n #existingPaths = new Array<string>();\n\n static create(options?: DefaultRootHttpRouterOptions) {\n let indexPath;\n if (options?.indexPath === false) {\n indexPath = undefined;\n } else if (options?.indexPath === undefined) {\n indexPath = '/api/app';\n } else if (options?.indexPath === '') {\n throw new Error('indexPath option may not be an empty string');\n } else {\n indexPath = options.indexPath;\n }\n return new DefaultRootHttpRouter(indexPath);\n }\n\n private constructor(indexPath?: string) {\n this.#indexPath = indexPath;\n this.#router.use(this.#namedRoutes);\n\n // Any request with a /api/ prefix will skip the index router, even if no named router matches\n this.#router.use('/api/', (_req, _res, next) => {\n next('router');\n });\n\n if (this.#indexPath) {\n this.#router.use(this.#indexRouter);\n }\n }\n\n use(path: string, handler: Handler) {\n if (path.match(/^[/\\s]*$/)) {\n throw new Error(`Root router path may not be empty`);\n }\n const conflictingPath = this.#findConflictingPath(path);\n if (conflictingPath) {\n throw new Error(\n `Path ${path} conflicts with the existing path ${conflictingPath}`,\n );\n }\n this.#existingPaths.push(path);\n this.#namedRoutes.use(path, handler);\n\n if (this.#indexPath === path) {\n this.#indexRouter.use(handler);\n }\n }\n\n handler(): Handler {\n return this.#router;\n }\n\n #findConflictingPath(newPath: string): string | undefined {\n const normalizedNewPath = normalizePath(newPath);\n for (const path of this.#existingPaths) {\n const normalizedPath = normalizePath(path);\n if (normalizedPath.startsWith(normalizedNewPath)) {\n return path;\n }\n if (normalizedNewPath.startsWith(normalizedPath)) {\n return path;\n }\n }\n return undefined;\n }\n}\n"],"names":["trimEnd","Router"],"mappings":";;;;;;;;;AAoBA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,GAAGA,wBAAA,CAAQ,IAAA,EAAM,GAAG,CAAC,IAAI,WAAA,EAAY;AAC9C;AAqBO,MAAM,qBAAA,CAAuD;AAAA,EAClE,UAAA;AAAA,EAEA,UAAUC,cAAA,EAAO;AAAA,EACjB,eAAeA,cAAA,EAAO;AAAA,EACtB,eAAeA,cAAA,EAAO;AAAA,EACtB,cAAA,GAAiB,IAAI,KAAA,EAAc;AAAA,EAEnC,OAAO,OAAO,OAAA,EAAwC;AACpD,IAAA,IAAI,SAAA;AACJ,IAAA,IAAI,OAAA,EAAS,cAAc,KAAA,EAAO;AAChC,MAAA,SAAA,GAAY,MAAA;AAAA,IACd,CAAA,MAAA,IAAW,OAAA,EAAS,SAAA,KAAc,MAAA,EAAW;AAC3C,MAAA,SAAA,GAAY,UAAA;AAAA,IACd,CAAA,MAAA,IAAW,OAAA,EAAS,SAAA,KAAc,EAAA,EAAI;AACpC,MAAA,MAAM,IAAI,MAAM,6CAA6C,CAAA;AAAA,IAC/D,CAAA,MAAO;AACL,MAAA,SAAA,GAAY,OAAA,CAAQ,SAAA;AAAA,IACtB;AACA,IAAA,OAAO,IAAI,sBAAsB,SAAS,CAAA;AAAA,EAC5C;AAAA,EA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