@backstage/backend-defaults 0.11.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/config.d.ts +195 -0
- package/dist/CreateBackend.cjs.js.map +1 -1
- package/dist/PackageDiscoveryService.cjs.js +13 -3
- 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.map +1 -1
- package/dist/alpha/entrypoints/actionsRegistry/actionsRegistryServiceFactory.cjs.js.map +1 -1
- package/dist/cache.d.ts +20 -1
- package/dist/database.d.ts +1 -1
- package/dist/discovery.d.ts +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/types.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/ExternalTokenHandler.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 +112 -7
- 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 +141 -0
- package/dist/entrypoints/cache/providers/infinispan/InfinispanKeyvStore.cjs.js.map +1 -0
- package/dist/entrypoints/cache/providers/infinispan/InfinispanOptionsMapper.cjs.js +129 -0
- package/dist/entrypoints/cache/providers/infinispan/InfinispanOptionsMapper.cjs.js.map +1 -0
- 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/defaultSchemaOverride.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.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/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 +3 -0
- package/dist/entrypoints/rootLogger/WinstonLogger.cjs.js.map +1 -1
- package/dist/entrypoints/rootLogger/rootLoggerServiceFactory.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/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/BitbucketUrlReader.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/DefaultUserInfoService.cjs.js.map +1 -1
- package/dist/entrypoints/userInfo/userInfoServiceFactory.cjs.js.map +1 -1
- package/dist/httpAuth.d.ts +1 -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 +2 -269
- package/dist/package.json.cjs.js.map +1 -1
- package/dist/urlReader.d.ts +1 -1
- package/package.json +12 -11
|
@@ -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 } from 'express';\nimport { RateLimitStoreFactory } from '../../../lib/RateLimitStoreFactory.ts';\nimport { Config } from '@backstage/config';\nimport { rateLimitMiddleware } from '../../../lib/rateLimitMiddleware.ts';\n\nexport const createRateLimitMiddleware = (options: {\n pluginId: string;\n config: Config;\n}) => {\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":";;;;;
|
|
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 } from 'express';\nimport { RateLimitStoreFactory } from '../../../lib/RateLimitStoreFactory.ts';\nimport { Config } from '@backstage/config';\nimport { rateLimitMiddleware } from '../../../lib/rateLimitMiddleware.ts';\n\nexport const createRateLimitMiddleware = (options: {\n pluginId: string;\n config: Config;\n}) => {\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":";;;;;AAoBO,MAAM,yBAAA,GAA4B,CAAC,OAAA,KAGpC;AACJ,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,
|
|
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,CAA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AAM,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 constructor(\n private readonly logger: LoggerService,\n private readonly pluginMetadata: PluginMetadataService,\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,
|
|
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 constructor(\n private readonly logger: LoggerService,\n private readonly pluginMetadata: PluginMetadataService,\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,EAClE,WAAA,CACmB,QACA,cAAA,EACjB;AAFiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAAA,EAChB;AAAA,EAEH,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,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MAAA,CAAO,KAAA;AAAA,MACV,CAAA,QAAA,EAAW,IAAA,CAAK,cAAA,CAAe,MAAM,CAAA,yBAAA;AAAA,KACvC;AAEA,IAAA,MAAM,OAAA,CAAQ,GAAA;AAAA,MACZ,KAAK,cAAA,CAAe,GAAA,CAAI,OAAO,EAAE,IAAA,EAAM,SAAQ,KAAM;AACnD,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,8BAAA,CAAgC,CAAA;AAAA,QAC/C,SAAS,KAAA,EAAO;AACd,UAAA,MAAA,CAAO,KAAA,CAAM,+BAA+B,KAAK,CAAA;AAAA,QACnD;AAAA,MACF,CAAC;AAAA,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 +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,
|
|
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,
|
|
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,
|
|
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,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D;AAAA,KACF;AAAA,EACF;AACF,CAAC;;;;"}
|
|
@@ -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 }));\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,
|
|
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 }));\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;AAAA,GACnD,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+
|
|
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\n constructor(readonly options: { lifecycle: RootLifecycleService }) {\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 shuttting 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,
|
|
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\n constructor(readonly options: { lifecycle: RootLifecycleService }) {\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 shuttting 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,EAGjE,YAAqB,OAAA,EAA8C;AAA9C,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACnB,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,EATA,MAAA,GAAiC,MAAA;AAAA,EAWjC,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,2BAAA,EAA6B,QAAQ,OAAA;AAAQ,OACnE;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, '/')}/`;\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,
|
|
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, '/')}/`;\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,CAAA,EAAGA,wBAAA,CAAQ,IAAA,EAAM,GAAG,CAAC,CAAA,CAAA,CAAA;AAC9B;AAqBO,MAAM,qBAAA,CAAuD;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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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createHealthRouter.cjs.js","sources":["../../../src/entrypoints/rootHttpRouter/createHealthRouter.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 RootConfigService,\n RootHealthService,\n} from '@backstage/backend-plugin-api';\nimport Router from 'express-promise-router';\nimport { Request, Response } from 'express';\n\nconst HEADER_CONFIG_KEY = 'backend.health.headers';\n\n/**\n * @public\n */\nexport function createHealthRouter(options: {\n health: RootHealthService;\n config: RootConfigService;\n}) {\n const headersConfig = options.config\n .getOptionalConfig(HEADER_CONFIG_KEY)\n ?.get();\n if (headersConfig) {\n for (const [key, value] of Object.entries(headersConfig)) {\n if (!key || typeof key !== 'string') {\n throw new Error(\n `Invalid header name in at ${HEADER_CONFIG_KEY}, must be a non-empty string`,\n );\n }\n if (!value || typeof value !== 'string') {\n throw new Error(\n `Invalid header value in at ${HEADER_CONFIG_KEY}, must be a non-empty string`,\n );\n }\n }\n }\n const headers = headersConfig && new Headers(headersConfig as HeadersInit);\n\n const router = Router();\n\n router.get(\n '/.backstage/health/v1/readiness',\n async (_request: Request, response: Response) => {\n const { status, payload } = await options.health.getReadiness();\n if (headers) {\n response.setHeaders(headers);\n }\n response.status(status).json(payload);\n },\n );\n\n router.get(\n '/.backstage/health/v1/liveness',\n async (_request: Request, response: Response) => {\n const { status, payload } = await options.health.getLiveness();\n if (headers) {\n response.setHeaders(headers);\n }\n response.status(status).json(payload);\n },\n );\n\n return router;\n}\n"],"names":["Router"],"mappings":";;;;;;;;AAuBA,MAAM,
|
|
1
|
+
{"version":3,"file":"createHealthRouter.cjs.js","sources":["../../../src/entrypoints/rootHttpRouter/createHealthRouter.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 RootConfigService,\n RootHealthService,\n} from '@backstage/backend-plugin-api';\nimport Router from 'express-promise-router';\nimport { Request, Response } from 'express';\n\nconst HEADER_CONFIG_KEY = 'backend.health.headers';\n\n/**\n * @public\n */\nexport function createHealthRouter(options: {\n health: RootHealthService;\n config: RootConfigService;\n}) {\n const headersConfig = options.config\n .getOptionalConfig(HEADER_CONFIG_KEY)\n ?.get();\n if (headersConfig) {\n for (const [key, value] of Object.entries(headersConfig)) {\n if (!key || typeof key !== 'string') {\n throw new Error(\n `Invalid header name in at ${HEADER_CONFIG_KEY}, must be a non-empty string`,\n );\n }\n if (!value || typeof value !== 'string') {\n throw new Error(\n `Invalid header value in at ${HEADER_CONFIG_KEY}, must be a non-empty string`,\n );\n }\n }\n }\n const headers = headersConfig && new Headers(headersConfig as HeadersInit);\n\n const router = Router();\n\n router.get(\n '/.backstage/health/v1/readiness',\n async (_request: Request, response: Response) => {\n const { status, payload } = await options.health.getReadiness();\n if (headers) {\n response.setHeaders(headers);\n }\n response.status(status).json(payload);\n },\n );\n\n router.get(\n '/.backstage/health/v1/liveness',\n async (_request: Request, response: Response) => {\n const { status, payload } = await options.health.getLiveness();\n if (headers) {\n response.setHeaders(headers);\n }\n response.status(status).json(payload);\n },\n );\n\n return router;\n}\n"],"names":["Router"],"mappings":";;;;;;;;AAuBA,MAAM,iBAAA,GAAoB,wBAAA;AAKnB,SAAS,mBAAmB,OAAA,EAGhC;AACD,EAAA,MAAM,gBAAgB,OAAA,CAAQ,MAAA,CAC3B,iBAAA,CAAkB,iBAAiB,GAClC,GAAA,EAAI;AACR,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO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T;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareFactory.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/MiddlewareFactory.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 {\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport {\n ErrorRequestHandler,\n NextFunction,\n Request,\n RequestHandler,\n Response,\n} from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport compression from 'compression';\nimport { readHelmetOptions } from './readHelmetOptions';\nimport { readCorsOptions } from './readCorsOptions';\nimport {\n AuthenticationError,\n ConflictError,\n ErrorResponseBody,\n InputError,\n NotAllowedError,\n NotFoundError,\n NotImplementedError,\n NotModifiedError,\n serializeError,\n ServiceUnavailableError,\n} from '@backstage/errors';\nimport { applyInternalErrorFilter } from './applyInternalErrorFilter';\nimport { RateLimitStoreFactory } from '../../../lib/RateLimitStoreFactory.ts';\nimport { rateLimitMiddleware } from '../../../lib/rateLimitMiddleware.ts';\n\ntype LogMeta = {\n date: string;\n method: string;\n url: string;\n status: number;\n httpVersion: string;\n userAgent?: string;\n contentLength?: number;\n referrer?: string;\n};\n\nfunction getLogMeta(req: Request, res: Response): LogMeta {\n const referrer = req.headers.referer ?? req.headers.referrer;\n const userAgent = req.headers['user-agent'];\n const contentLength = Number(res.getHeader('content-length'));\n\n const meta: LogMeta = {\n date: new Date().toISOString(),\n method: req.method,\n url: req.originalUrl ?? req.url,\n status: res.statusCode,\n httpVersion: `${req.httpVersionMajor}.${req.httpVersionMinor}`,\n };\n\n if (userAgent) {\n meta.userAgent = userAgent;\n }\n\n if (isFinite(contentLength)) {\n meta.contentLength = contentLength;\n }\n\n if (referrer) {\n meta.referrer = Array.isArray(referrer) ? referrer.join(', ') : referrer;\n }\n\n return meta;\n}\n\n/**\n * Options used to create a {@link MiddlewareFactory}.\n *\n * @public\n */\nexport interface MiddlewareFactoryOptions {\n config: RootConfigService;\n logger: LoggerService;\n}\n\n/**\n * Options passed to the {@link MiddlewareFactory.error} middleware.\n *\n * @public\n */\nexport interface MiddlewareFactoryErrorOptions {\n /**\n * Whether error response bodies should show error stack traces or not.\n *\n * If not specified, by default shows stack traces only in development mode.\n */\n showStackTraces?: boolean;\n\n /**\n * Whether any 4xx errors should be logged or not.\n *\n * If not specified, default to only logging 5xx errors.\n */\n logAllErrors?: boolean;\n}\n\n/**\n * A utility to configure common middleware.\n *\n * @public\n */\nexport class MiddlewareFactory {\n #config: RootConfigService;\n #logger: LoggerService;\n\n /**\n * Creates a new {@link MiddlewareFactory}.\n */\n static create(options: MiddlewareFactoryOptions) {\n return new MiddlewareFactory(options);\n }\n\n private constructor(options: MiddlewareFactoryOptions) {\n this.#config = options.config;\n this.#logger = options.logger;\n }\n\n /**\n * Returns a middleware that unconditionally produces a 404 error response.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the end of the chain, such\n * that it's the last one attempted after no other routes matched.\n *\n * @returns An Express request handler\n */\n notFound(): RequestHandler {\n return (_req: Request, res: Response) => {\n res.status(404).end();\n };\n }\n\n /**\n * Returns the compression middleware.\n *\n * @remarks\n *\n * The middleware will attempt to compress response bodies for all requests\n * that traverse through the middleware.\n */\n compression(): RequestHandler {\n return compression();\n }\n\n /**\n * Returns a request logging middleware.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the start of the chain, such\n * that it always logs requests whether they are \"caught\" by handlers farther\n * down or not.\n *\n * @returns An Express request handler\n */\n logging(): RequestHandler {\n const logger = this.#logger;\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', () => {\n const meta = getLogMeta(req, res);\n logger.info(\n `[${meta.date}] \"${meta.method} ${meta.url} HTTP/${\n meta.httpVersion\n }\" ${meta.status} ${meta.contentLength ?? 0} \"${\n meta.referrer ?? '-'\n }\" \"${meta.userAgent ?? '-'}\"`,\n {\n type: 'incomingRequest',\n ...meta,\n },\n );\n });\n next();\n };\n }\n\n /**\n * Returns a middleware that implements the helmet library.\n *\n * @remarks\n *\n * This middleware applies security policies to incoming requests and outgoing\n * responses. It is configured using config keys such as `backend.csp`.\n *\n * @see {@link https://helmetjs.github.io/}\n *\n * @returns An Express request handler\n */\n helmet(): RequestHandler {\n return helmet(readHelmetOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements the cors library.\n *\n * @remarks\n *\n * This middleware handles CORS. It is configured using the config key\n * `backend.cors`.\n *\n * @see {@link https://github.com/expressjs/cors}\n *\n * @returns An Express request handler\n */\n cors(): RequestHandler {\n return cors(readCorsOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements rate limiting.\n *\n * @remarks\n *\n * Rate limiting is a common technique to prevent abuse of APIs. This middleware is\n * configured using the config key `backend.rateLimit`.\n *\n * @returns An Express request handler\n */\n rateLimit(): RequestHandler {\n const enabled = this.#config.has('backend.rateLimit');\n if (!enabled) {\n return (_req: Request, _res: Response, next: NextFunction) => {\n next();\n };\n }\n\n const useDefaults = this.#config.getOptional('backend.rateLimit') === true;\n const rateLimitOptions = useDefaults\n ? undefined\n : this.#config.getOptionalConfig('backend.rateLimit');\n\n // Global rate limiting disabled\n if (\n rateLimitOptions &&\n rateLimitOptions.getOptionalBoolean('global') === false\n ) {\n return (_req: Request, _res: Response, next: NextFunction) => {\n next();\n };\n }\n\n return rateLimitMiddleware({\n store: useDefaults\n ? undefined\n : RateLimitStoreFactory.create({ config: this.#config }),\n config: rateLimitOptions,\n });\n }\n\n /**\n * Express middleware to handle errors during request processing.\n *\n * @remarks\n *\n * This is commonly the very last middleware in the chain.\n *\n * Its primary purpose is not to do translation of business logic exceptions,\n * but rather to be a global catch-all for uncaught \"fatal\" errors that are\n * expected to result in a 500 error. However, it also does handle some common\n * error types (such as http-error exceptions, and the well-known error types\n * in the `@backstage/errors` package) and returns the enclosed status code\n * accordingly.\n *\n * It will also produce a response body with a serialized form of the error,\n * unless a previous handler already did send a body. See\n * {@link @backstage/errors#ErrorResponseBody} for the response shape used.\n *\n * @returns An Express error request handler\n */\n error(options: MiddlewareFactoryErrorOptions = {}): ErrorRequestHandler {\n const showStackTraces =\n options.showStackTraces ?? process.env.NODE_ENV === 'development';\n\n const logger = this.#logger.child({\n type: 'errorHandler',\n });\n\n return (\n rawError: Error,\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n const error = applyInternalErrorFilter(rawError, logger);\n\n const statusCode = getStatusCode(error);\n if (options.logAllErrors || statusCode >= 500) {\n logger.error(`Request failed with status ${statusCode}`, error);\n }\n\n if (res.headersSent) {\n // If the headers have already been sent, do not send the response again\n // as this will throw an error in the backend.\n next(error);\n return;\n }\n\n const body: ErrorResponseBody = {\n error: serializeError(error, { includeStack: showStackTraces }),\n request: { method: req.method, url: req.url },\n response: { statusCode },\n };\n\n res.status(statusCode).json(body);\n };\n }\n}\n\nfunction getStatusCode(error: Error): number {\n // Look for common http library status codes\n const knownStatusCodeFields = ['statusCode', 'status'];\n for (const field of knownStatusCodeFields) {\n const statusCode = (error as any)[field];\n if (\n typeof statusCode === 'number' &&\n (statusCode | 0) === statusCode && // is whole integer\n statusCode >= 100 &&\n statusCode <= 599\n ) {\n return statusCode;\n }\n }\n\n // Handle well-known error types\n switch (error.name) {\n case NotModifiedError.name:\n return 304;\n case InputError.name:\n return 400;\n case AuthenticationError.name:\n return 401;\n case NotAllowedError.name:\n return 403;\n case NotFoundError.name:\n return 404;\n case ConflictError.name:\n return 409;\n case NotImplementedError.name:\n return 501;\n case ServiceUnavailableError.name:\n return 503;\n default:\n break;\n }\n\n // Fall back to internal server error\n return 500;\n}\n"],"names":["compression","helmet","readHelmetOptions","cors","readCorsOptions","rateLimitMiddleware","RateLimitStoreFactory","applyInternalErrorFilter","serializeError","NotModifiedError","InputError","AuthenticationError","NotAllowedError","NotFoundError","ConflictError","NotImplementedError","ServiceUnavailableError"],"mappings":";;;;;;;;;;;;;;;;;;AA2DA,SAAS,UAAA,CAAW,KAAc,GAAwB,EAAA;AACxD,EAAA,MAAM,QAAW,GAAA,GAAA,CAAI,OAAQ,CAAA,OAAA,IAAW,IAAI,OAAQ,CAAA,QAAA;AACpD,EAAM,MAAA,SAAA,GAAY,GAAI,CAAA,OAAA,CAAQ,YAAY,CAAA;AAC1C,EAAA,MAAM,aAAgB,GAAA,MAAA,CAAO,GAAI,CAAA,SAAA,CAAU,gBAAgB,CAAC,CAAA;AAE5D,EAAA,MAAM,IAAgB,GAAA;AAAA,IACpB,IAAM,EAAA,iBAAA,IAAI,IAAK,EAAA,EAAE,WAAY,EAAA;AAAA,IAC7B,QAAQ,GAAI,CAAA,MAAA;AAAA,IACZ,GAAA,EAAK,GAAI,CAAA,WAAA,IAAe,GAAI,CAAA,GAAA;AAAA,IAC5B,QAAQ,GAAI,CAAA,UAAA;AAAA,IACZ,aAAa,CAAG,EAAA,GAAA,CAAI,gBAAgB,CAAA,CAAA,EAAI,IAAI,gBAAgB,CAAA;AAAA,GAC9D;AAEA,EAAA,IAAI,SAAW,EAAA;AACb,IAAA,IAAA,CAAK,SAAY,GAAA,SAAA;AAAA;AAGnB,EAAI,IAAA,QAAA,CAAS,aAAa,CAAG,EAAA;AAC3B,IAAA,IAAA,CAAK,aAAgB,GAAA,aAAA;AAAA;AAGvB,EAAA,IAAI,QAAU,EAAA;AACZ,IAAK,IAAA,CAAA,QAAA,GAAW,MAAM,OAAQ,CAAA,QAAQ,IAAI,QAAS,CAAA,IAAA,CAAK,IAAI,CAAI,GAAA,QAAA;AAAA;AAGlE,EAAO,OAAA,IAAA;AACT;AAsCO,MAAM,iBAAkB,CAAA;AAAA,EAC7B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yright 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 {\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport {\n ErrorRequestHandler,\n NextFunction,\n Request,\n RequestHandler,\n Response,\n} from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport compression from 'compression';\nimport { readHelmetOptions } from './readHelmetOptions';\nimport { readCorsOptions } from './readCorsOptions';\nimport {\n AuthenticationError,\n ConflictError,\n ErrorResponseBody,\n InputError,\n NotAllowedError,\n NotFoundError,\n NotImplementedError,\n NotModifiedError,\n serializeError,\n ServiceUnavailableError,\n} from '@backstage/errors';\nimport { applyInternalErrorFilter } from './applyInternalErrorFilter';\nimport { RateLimitStoreFactory } from '../../../lib/RateLimitStoreFactory.ts';\nimport { rateLimitMiddleware } from '../../../lib/rateLimitMiddleware.ts';\n\ntype LogMeta = {\n date: string;\n method: string;\n url: string;\n status: number;\n httpVersion: string;\n userAgent?: string;\n contentLength?: number;\n referrer?: string;\n};\n\nfunction getLogMeta(req: Request, res: Response): LogMeta {\n const referrer = req.headers.referer ?? req.headers.referrer;\n const userAgent = req.headers['user-agent'];\n const contentLength = Number(res.getHeader('content-length'));\n\n const meta: LogMeta = {\n date: new Date().toISOString(),\n method: req.method,\n url: req.originalUrl ?? req.url,\n status: res.statusCode,\n httpVersion: `${req.httpVersionMajor}.${req.httpVersionMinor}`,\n };\n\n if (userAgent) {\n meta.userAgent = userAgent;\n }\n\n if (isFinite(contentLength)) {\n meta.contentLength = contentLength;\n }\n\n if (referrer) {\n meta.referrer = Array.isArray(referrer) ? referrer.join(', ') : referrer;\n }\n\n return meta;\n}\n\n/**\n * Options used to create a {@link MiddlewareFactory}.\n *\n * @public\n */\nexport interface MiddlewareFactoryOptions {\n config: RootConfigService;\n logger: LoggerService;\n}\n\n/**\n * Options passed to the {@link MiddlewareFactory.error} middleware.\n *\n * @public\n */\nexport interface MiddlewareFactoryErrorOptions {\n /**\n * Whether error response bodies should show error stack traces or not.\n *\n * If not specified, by default shows stack traces only in development mode.\n */\n showStackTraces?: boolean;\n\n /**\n * Whether any 4xx errors should be logged or not.\n *\n * If not specified, default to only logging 5xx errors.\n */\n logAllErrors?: boolean;\n}\n\n/**\n * A utility to configure common middleware.\n *\n * @public\n */\nexport class MiddlewareFactory {\n #config: RootConfigService;\n #logger: LoggerService;\n\n /**\n * Creates a new {@link MiddlewareFactory}.\n */\n static create(options: MiddlewareFactoryOptions) {\n return new MiddlewareFactory(options);\n }\n\n private constructor(options: MiddlewareFactoryOptions) {\n this.#config = options.config;\n this.#logger = options.logger;\n }\n\n /**\n * Returns a middleware that unconditionally produces a 404 error response.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the end of the chain, such\n * that it's the last one attempted after no other routes matched.\n *\n * @returns An Express request handler\n */\n notFound(): RequestHandler {\n return (_req: Request, res: Response) => {\n res.status(404).end();\n };\n }\n\n /**\n * Returns the compression middleware.\n *\n * @remarks\n *\n * The middleware will attempt to compress response bodies for all requests\n * that traverse through the middleware.\n */\n compression(): RequestHandler {\n return compression();\n }\n\n /**\n * Returns a request logging middleware.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the start of the chain, such\n * that it always logs requests whether they are \"caught\" by handlers farther\n * down or not.\n *\n * @returns An Express request handler\n */\n logging(): RequestHandler {\n const logger = this.#logger;\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', () => {\n const meta = getLogMeta(req, res);\n logger.info(\n `[${meta.date}] \"${meta.method} ${meta.url} HTTP/${\n meta.httpVersion\n }\" ${meta.status} ${meta.contentLength ?? 0} \"${\n meta.referrer ?? '-'\n }\" \"${meta.userAgent ?? '-'}\"`,\n {\n type: 'incomingRequest',\n ...meta,\n },\n );\n });\n next();\n };\n }\n\n /**\n * Returns a middleware that implements the helmet library.\n *\n * @remarks\n *\n * This middleware applies security policies to incoming requests and outgoing\n * responses. It is configured using config keys such as `backend.csp`.\n *\n * @see {@link https://helmetjs.github.io/}\n *\n * @returns An Express request handler\n */\n helmet(): RequestHandler {\n return helmet(readHelmetOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements the cors library.\n *\n * @remarks\n *\n * This middleware handles CORS. It is configured using the config key\n * `backend.cors`.\n *\n * @see {@link https://github.com/expressjs/cors}\n *\n * @returns An Express request handler\n */\n cors(): RequestHandler {\n return cors(readCorsOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements rate limiting.\n *\n * @remarks\n *\n * Rate limiting is a common technique to prevent abuse of APIs. This middleware is\n * configured using the config key `backend.rateLimit`.\n *\n * @returns An Express request handler\n */\n rateLimit(): RequestHandler {\n const enabled = this.#config.has('backend.rateLimit');\n if (!enabled) {\n return (_req: Request, _res: Response, next: NextFunction) => {\n next();\n };\n }\n\n const useDefaults = this.#config.getOptional('backend.rateLimit') === true;\n const rateLimitOptions = useDefaults\n ? undefined\n : this.#config.getOptionalConfig('backend.rateLimit');\n\n // Global rate limiting disabled\n if (\n rateLimitOptions &&\n rateLimitOptions.getOptionalBoolean('global') === false\n ) {\n return (_req: Request, _res: Response, next: NextFunction) => {\n next();\n };\n }\n\n return rateLimitMiddleware({\n store: useDefaults\n ? undefined\n : RateLimitStoreFactory.create({ config: this.#config }),\n config: rateLimitOptions,\n });\n }\n\n /**\n * Express middleware to handle errors during request processing.\n *\n * @remarks\n *\n * This is commonly the very last middleware in the chain.\n *\n * Its primary purpose is not to do translation of business logic exceptions,\n * but rather to be a global catch-all for uncaught \"fatal\" errors that are\n * expected to result in a 500 error. However, it also does handle some common\n * error types (such as http-error exceptions, and the well-known error types\n * in the `@backstage/errors` package) and returns the enclosed status code\n * accordingly.\n *\n * It will also produce a response body with a serialized form of the error,\n * unless a previous handler already did send a body. See\n * {@link @backstage/errors#ErrorResponseBody} for the response shape used.\n *\n * @returns An Express error request handler\n */\n error(options: MiddlewareFactoryErrorOptions = {}): ErrorRequestHandler {\n const showStackTraces =\n options.showStackTraces ?? process.env.NODE_ENV === 'development';\n\n const logger = this.#logger.child({\n type: 'errorHandler',\n });\n\n return (\n rawError: Error,\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n const error = applyInternalErrorFilter(rawError, logger);\n\n const statusCode = getStatusCode(error);\n if (options.logAllErrors || statusCode >= 500) {\n logger.error(`Request failed with status ${statusCode}`, error);\n }\n\n if (res.headersSent) {\n // If the headers have already been sent, do not send the response again\n // as this will throw an error in the backend.\n next(error);\n return;\n }\n\n const body: ErrorResponseBody = {\n error: serializeError(error, { includeStack: showStackTraces }),\n request: { method: req.method, url: req.url },\n response: { statusCode },\n };\n\n res.status(statusCode).json(body);\n };\n }\n}\n\nfunction getStatusCode(error: Error): number {\n // Look for common http library status codes\n const knownStatusCodeFields = ['statusCode', 'status'];\n for (const field of knownStatusCodeFields) {\n const statusCode = (error as any)[field];\n if (\n typeof statusCode === 'number' &&\n (statusCode | 0) === statusCode && // is whole integer\n statusCode >= 100 &&\n statusCode <= 599\n ) {\n return statusCode;\n }\n }\n\n // Handle well-known error types\n switch (error.name) {\n case NotModifiedError.name:\n return 304;\n case InputError.name:\n return 400;\n case AuthenticationError.name:\n return 401;\n case NotAllowedError.name:\n return 403;\n case NotFoundError.name:\n return 404;\n case ConflictError.name:\n return 409;\n case NotImplementedError.name:\n return 501;\n case ServiceUnavailableError.name:\n return 503;\n default:\n break;\n }\n\n // Fall back to internal server error\n return 500;\n}\n"],"names":["compression","helmet","readHelmetOptions","cors","readCorsOptions","rateLimitMiddleware","RateLimitStoreFactory","applyInternalErrorFilter","serializeError","NotModifiedError","InputError","AuthenticationError","NotAllowedError","NotFoundError","ConflictError","Not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,QAAA,EAAU,EAAE,UAAA;AAAW,OACzB;AAEA,MAAA,GAAA,CAAI,MAAA,CAAO,UAAU,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA;AAAA,IAClC,CAAA;AAAA,EACF;AACF;AAEA,SAAS,cAAc,KAAA,EAAsB;AAE3C,EAAA,MAAM,qBAAA,GAAwB,CAAC,YAAA,EAAc,QAAQ,CAAA;AACrD,EAAA,KAAA,MAAW,SAAS,qBAAA,EAAuB;AACzC,IAAA,MAAM,UAAA,GAAc,MAAc,KAAK,CAAA;AACvC,IAAA,IACE,OAAO,UAAA,KAAe,QAAA,IAAA,CACrB,UAAA,GAAa,CAAA,MAAO,UAAA;AAAA,IACrB,UAAA,IAAc,GAAA,IACd,UAAA,IAAc,GAAA,EACd;AACA,MAAA,OAAO,UAAA;AAAA,IACT;AAAA,EACF;AAGA,EAAA,QAAQ,MAAM,IAAA;AAAM,IAClB,KAAKC,uBAAA,CAAiB,IAAA;AACpB,MAAA,OAAO,GAAA;AAAA,IACT,KAAKC,iBAAA,CAAW,IAAA;AACd,MAAA,OAAO,GAAA;AAAA,IACT,KAAKC,0BAAA,CAAoB,IAAA;AACvB,MAAA,OAAO,GAAA;AAAA,IACT,KAAKC,sBAAA,CAAgB,IAAA;AACnB,MAAA,OAAO,GAAA;AAAA,IACT,KAAKC,oBAAA,CAAc,IAAA;AACjB,MAAA,OAAO,GAAA;AAAA,IACT,KAAKC,oBAAA,CAAc,IAAA;AACjB,MAAA,OAAO,GAAA;AAAA,IACT,KAAKC,0BAAA,CAAoB,IAAA;AACvB,MAAA,OAAO,GAAA;AAAA,IACT,KAAKC,8BAAA,CAAwB,IAAA;AAC3B,MAAA,OAAO,GAAA;AAEP;AAIJ,EAAA,OAAO,GAAA;AACT;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applyInternalErrorFilter.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/applyInternalErrorFilter.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 { LoggerService } from '@backstage/backend-plugin-api';\nimport { assertError } from '@backstage/errors';\nimport { randomBytes } from 'crypto';\n\nfunction handleBadError(error: Error, logger: LoggerService) {\n const logId = randomBytes(10).toString('hex');\n logger\n .child({ logId })\n .error(`Filtered internal error with logId=${logId} from response`, error);\n const newError = new Error(`An internal error occurred logId=${logId}`);\n delete newError.stack; // Trim the stack since it's not particularly useful\n return newError;\n}\n\n/**\n * Filters out certain known error types that should never be returned in responses.\n *\n * @internal\n */\nexport function applyInternalErrorFilter(\n error: unknown,\n logger: LoggerService,\n): Error {\n try {\n assertError(error);\n } catch (assertionError: unknown) {\n assertError(assertionError);\n return handleBadError(assertionError, logger);\n }\n\n const constructorName = error.constructor.name;\n\n // DatabaseError are thrown by the pg-protocol module\n if (constructorName === 'DatabaseError') {\n return handleBadError(error, logger);\n }\n\n return error;\n}\n"],"names":["randomBytes","assertError"],"mappings":";;;;;AAoBA,SAAS,cAAA,CAAe,OAAc,
|
|
1
|
+
{"version":3,"file":"applyInternalErrorFilter.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/applyInternalErrorFilter.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 { LoggerService } from '@backstage/backend-plugin-api';\nimport { assertError } from '@backstage/errors';\nimport { randomBytes } from 'crypto';\n\nfunction handleBadError(error: Error, logger: LoggerService) {\n const logId = randomBytes(10).toString('hex');\n logger\n .child({ logId })\n .error(`Filtered internal error with logId=${logId} from response`, error);\n const newError = new Error(`An internal error occurred logId=${logId}`);\n delete newError.stack; // Trim the stack since it's not particularly useful\n return newError;\n}\n\n/**\n * Filters out certain known error types that should never be returned in responses.\n *\n * @internal\n */\nexport function applyInternalErrorFilter(\n error: unknown,\n logger: LoggerService,\n): Error {\n try {\n assertError(error);\n } catch (assertionError: unknown) {\n assertError(assertionError);\n return handleBadError(assertionError, logger);\n }\n\n const constructorName = error.constructor.name;\n\n // DatabaseError are thrown by the pg-protocol module\n if (constructorName === 'DatabaseError') {\n return handleBadError(error, logger);\n }\n\n return error;\n}\n"],"names":["randomBytes","assertError"],"mappings":";;;;;AAoBA,SAAS,cAAA,CAAe,OAAc,MAAA,EAAuB;AAC3D,EAAA,MAAM,KAAA,GAAQA,kBAAA,CAAY,EAAE,CAAA,CAAE,SAAS,KAAK,CAAA;AAC5C,EAAA,MAAA,CACG,KAAA,CAAM,EAAE,KAAA,EAAO,EACf,KAAA,CAAM,CAAA,mCAAA,EAAsC,KAAK,CAAA,cAAA,CAAA,EAAkB,KAAK,CAAA;AAC3E,EAAA,MAAM,QAAA,GAAW,IAAI,KAAA,CAAM,CAAA,iCAAA,EAAoC,KAAK,CAAA,CAAE,CAAA;AACtE,EAAA,OAAO,QAAA,CAAS,KAAA;AAChB,EAAA,OAAO,QAAA;AACT;AAOO,SAAS,wBAAA,CACd,OACA,MAAA,EACO;AACP,EAAA,IAAI;AACF,IAAAC,kBAAA,CAAY,KAAK,CAAA;AAAA,EACnB,SAAS,cAAA,EAAyB;AAChC,IAAAA,kBAAA,CAAY,cAAc,CAAA;AAC1B,IAAA,OAAO,cAAA,CAAe,gBAAgB,MAAM,CAAA;AAAA,EAC9C;AAEA,EAAA,MAAM,eAAA,GAAkB,MAAM,WAAA,CAAY,IAAA;AAG1C,EAAA,IAAI,oBAAoB,eAAA,EAAiB;AACvC,IAAA,OAAO,cAAA,CAAe,OAAO,MAAM,CAAA;AAAA,EACrC;AAEA,EAAA,OAAO,KAAA;AACT;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/config.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 { Config } from '@backstage/config';\nimport { HttpServerOptions } from './types';\n\nconst DEFAULT_PORT = 7007;\nconst DEFAULT_HOST = '';\n\n/**\n * Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.\n *\n * @public\n * @remarks\n *\n * The provided configuration object should contain the `listen` and\n * additional keys directly.\n *\n * @example\n * ```ts\n * const opts = readHttpServerOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHttpServerOptions(config?: Config): HttpServerOptions {\n return {\n listen: readHttpListenOptions(config),\n https: readHttpsOptions(config),\n };\n}\n\nfunction readHttpListenOptions(config?: Config): HttpServerOptions['listen'] {\n const listen = config?.getOptional('listen');\n if (typeof listen === 'string') {\n const parts = String(listen).split(':');\n const port = parseInt(parts[parts.length - 1], 10);\n if (!isNaN(port)) {\n if (parts.length === 1) {\n return { port, host: DEFAULT_HOST };\n }\n if (parts.length === 2) {\n return { host: parts[0], port };\n }\n }\n throw new Error(\n `Unable to parse listen address ${listen}, expected <port> or <host>:<port>`,\n );\n }\n\n // Workaround to allow empty string\n const host = config?.getOptional('listen.host') ?? DEFAULT_HOST;\n if (typeof host !== 'string') {\n config?.getOptionalString('listen.host'); // will throw\n throw new Error('unreachable');\n }\n\n return {\n port: config?.getOptionalNumber('listen.port') ?? DEFAULT_PORT,\n host,\n };\n}\n\nfunction readHttpsOptions(config?: Config): HttpServerOptions['https'] {\n const https = config?.getOptional('https');\n if (https === true) {\n const baseUrl = config!.getString('baseUrl');\n let hostname;\n try {\n hostname = new URL(baseUrl).hostname;\n } catch (error) {\n throw new Error(`Invalid baseUrl \"${baseUrl}\"`);\n }\n\n return { certificate: { type: 'generated', hostname } };\n }\n\n const cc = config?.getOptionalConfig('https');\n if (!cc) {\n return undefined;\n }\n\n return {\n certificate: {\n type: 'pem',\n cert: cc.getString('certificate.cert'),\n key: cc.getString('certificate.key'),\n },\n };\n}\n"],"names":[],"mappings":";;AAmBA,MAAM,
|
|
1
|
+
{"version":3,"file":"config.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/config.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 { Config } from '@backstage/config';\nimport { HttpServerOptions } from './types';\n\nconst DEFAULT_PORT = 7007;\nconst DEFAULT_HOST = '';\n\n/**\n * Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.\n *\n * @public\n * @remarks\n *\n * The provided configuration object should contain the `listen` and\n * additional keys directly.\n *\n * @example\n * ```ts\n * const opts = readHttpServerOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHttpServerOptions(config?: Config): HttpServerOptions {\n return {\n listen: readHttpListenOptions(config),\n https: readHttpsOptions(config),\n };\n}\n\nfunction readHttpListenOptions(config?: Config): HttpServerOptions['listen'] {\n const listen = config?.getOptional('listen');\n if (typeof listen === 'string') {\n const parts = String(listen).split(':');\n const port = parseInt(parts[parts.length - 1], 10);\n if (!isNaN(port)) {\n if (parts.length === 1) {\n return { port, host: DEFAULT_HOST };\n }\n if (parts.length === 2) {\n return { host: parts[0], port };\n }\n }\n throw new Error(\n `Unable to parse listen address ${listen}, expected <port> or <host>:<port>`,\n );\n }\n\n // Workaround to allow empty string\n const host = config?.getOptional('listen.host') ?? DEFAULT_HOST;\n if (typeof host !== 'string') {\n config?.getOptionalString('listen.host'); // will throw\n throw new Error('unreachable');\n }\n\n return {\n port: config?.getOptionalNumber('listen.port') ?? DEFAULT_PORT,\n host,\n };\n}\n\nfunction readHttpsOptions(config?: Config): HttpServerOptions['https'] {\n const https = config?.getOptional('https');\n if (https === true) {\n const baseUrl = config!.getString('baseUrl');\n let hostname;\n try {\n hostname = new URL(baseUrl).hostname;\n } catch (error) {\n throw new Error(`Invalid baseUrl \"${baseUrl}\"`);\n }\n\n return { certificate: { type: 'generated', hostname } };\n }\n\n const cc = config?.getOptionalConfig('https');\n if (!cc) {\n return undefined;\n }\n\n return {\n certificate: {\n type: 'pem',\n cert: cc.getString('certificate.cert'),\n key: cc.getString('certificate.key'),\n },\n };\n}\n"],"names":[],"mappings":";;AAmBA,MAAM,YAAA,GAAe,IAAA;AACrB,MAAM,YAAA,GAAe,EAAA;AAgBd,SAAS,sBAAsB,MAAA,EAAoC;AACxE,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,sBAAsB,MAAM,CAAA;AAAA,IACpC,KAAA,EAAO,iBAAiB,MAAM;AAAA,GAChC;AACF;AAEA,SAAS,sBAAsB,MAAA,EAA8C;AAC3E,EAAA,MAAM,MAAA,GAAS,MAAA,EAAQ,WAAA,CAAY,QAAQ,CAAA;AAC3C,EAAA,IAAI,OAAO,WAAW,QAA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,CAAE,QAAA;AAAA,IAC9B,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,iBAAA,EAAoB,OAAO,CAAA,CAAA,CAAG,CAAA;AAAA,IAChD;AAEA,IAAA,OAAO,EAAE,WAAA,EAAa,EAAE,IAAA,EAAM,WAAA,EAAa,UAAS,EAAE;AAAA,EACxD;AAEA,EAAA,MAAM,EAAA,GAAK,MAAA,EAAQ,iBAAA,CAAkB,OAAO,CAAA;AAC5C,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO;AAAA,IACL,WAAA,EAAa;AAAA,MACX,IAAA,EAAM,KAAA;AAAA,MACN,IAAA,EAAM,EAAA,CAAG,SAAA,CAAU,kBAAkB,CAAA;AAAA,MACrC,GAAA,EAAK,EAAA,CAAG,SAAA,CAAU,iBAAiB;AAAA;AACrC,GACF;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createHttpServer.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/createHttpServer.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 * as http from 'http';\nimport * as https from 'https';\nimport { RequestListener } from 'http';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { HttpServerOptions, ExtendedHttpServer } from './types';\nimport { getGeneratedCertificate } from './getGeneratedCertificate';\n\n/**\n * Creates a Node.js HTTP or HTTPS server instance.\n *\n * @public\n */\nexport async function createHttpServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<ExtendedHttpServer> {\n const server = await createServer(listener, options, deps);\n return Object.assign(server, {\n start() {\n return new Promise<void>((resolve, reject) => {\n const handleStartupError = (error: Error) => {\n server.close();\n reject(error);\n };\n\n server.on('error', handleStartupError);\n\n const { host, port } = options.listen;\n server.listen(port, host, () => {\n server.off('error', handleStartupError);\n deps.logger.info(`Listening on ${host}:${port}`);\n resolve();\n });\n });\n },\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n if (process.env.NODE_ENV === 'development') {\n // Ensure that various polling connections are shut down fast in development\n server.closeAllConnections();\n } else {\n server.closeIdleConnections();\n }\n server.close(error => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n },\n\n port() {\n const address = server.address();\n if (typeof address === 'string' || address === null) {\n throw new Error(`Unexpected server address '${address}'`);\n }\n return address.port;\n },\n });\n}\n\nasync function createServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<http.Server> {\n if (options.https) {\n const { certificate } = options.https;\n if (certificate.type === 'generated') {\n const credentials = await getGeneratedCertificate(\n certificate.hostname,\n deps.logger,\n );\n return https.createServer(credentials, listener);\n }\n return https.createServer(certificate, listener);\n }\n\n return http.createServer(listener);\n}\n"],"names":["getGeneratedCertificate","https","http"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"createHttpServer.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/createHttpServer.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 * as http from 'http';\nimport * as https from 'https';\nimport { RequestListener } from 'http';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { HttpServerOptions, ExtendedHttpServer } from './types';\nimport { getGeneratedCertificate } from './getGeneratedCertificate';\n\n/**\n * Creates a Node.js HTTP or HTTPS server instance.\n *\n * @public\n */\nexport async function createHttpServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<ExtendedHttpServer> {\n const server = await createServer(listener, options, deps);\n return Object.assign(server, {\n start() {\n return new Promise<void>((resolve, reject) => {\n const handleStartupError = (error: Error) => {\n server.close();\n reject(error);\n };\n\n server.on('error', handleStartupError);\n\n const { host, port } = options.listen;\n server.listen(port, host, () => {\n server.off('error', handleStartupError);\n deps.logger.info(`Listening on ${host}:${port}`);\n resolve();\n });\n });\n },\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n if (process.env.NODE_ENV === 'development') {\n // Ensure that various polling connections are shut down fast in development\n server.closeAllConnections();\n } else {\n server.closeIdleConnections();\n }\n server.close(error => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n },\n\n port() {\n const address = server.address();\n if (typeof address === 'string' || address === null) {\n throw new Error(`Unexpected server address '${address}'`);\n }\n return address.port;\n },\n });\n}\n\nasync function createServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<http.Server> {\n if (options.https) {\n const { certificate } = options.https;\n if (certificate.type === 'generated') {\n const credentials = await getGeneratedCertificate(\n certificate.hostname,\n deps.logger,\n );\n return https.createServer(credentials, listener);\n }\n return https.createServer(certificate, listener);\n }\n\n return http.createServer(listener);\n}\n"],"names":["getGeneratedCertificate","https","http"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,gBAAA,CACpB,QAAA,EACA,OAAA,EACA,IAAA,EAC6B;AAC7B,EAAA,MAAM,MAAA,GAAS,MAAM,YAAA,CAAa,QAAA,EAAU,SAAS,IAAI,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AAA,IACH,CAAA;AAAA,IAEA,IAAA,GAAO;AACL,MAAA,MAAM,OAAA,GAAU,OAAO,OAAA,EAAQ;AAC/B,MAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA,KAAY,IAAA,EAAM;AACnD,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8B,OAAO,CAAA,CAAA,CAAG,CAAA;AAAA,MAC1D;AACA,MAAA,OAAO,OAAA,CAAQ,IAAA;AAAA,IACjB;AAAA,GACD,CAAA;AACH;AAEA,eAAe,YAAA,CACb,QAAA,EACA,OAAA,EACA,IAAA,EACsB;AACtB,EAAA,IAAI,QAAQ,KAAA,EAAO;AACjB,IAAA,MAAM,EAAE,WAAA,EAAY,GAAI,OAAA,CAAQ,KAAA;AAChC,IAAA,IAAI,WAAA,CAAY,SAAS,WAAA,EAAa;AACpC,MAAA,MAAM,cAAc,MAAMA,+CAAA;AAAA,QACxB,WAAA,CAAY,QAAA;AAAA,QACZ,IAAA,CAAK;AAAA,OACP;AACA,MAAA,OAAOC,gBAAA,CAAM,YAAA,CAAa,WAAA,EAAa,QAAQ,CAAA;AAAA,IACjD;AACA,IAAA,OAAOA,gBAAA,CAAM,YAAA,CAAa,WAAA,EAAa,QAAQ,CAAA;AAAA,EACjD;AAEA,EAAA,OAAOC,eAAA,CAAK,aAAa,QAAQ,CAAA;AACnC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getGeneratedCertificate.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/getGeneratedCertificate.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 fs from 'fs-extra';\nimport { resolve as resolvePath, dirname } from 'path';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport forge from 'node-forge';\n\nconst FIVE_DAYS_IN_MS = 5 * 24 * 60 * 60 * 1000;\n\nconst IP_HOSTNAME_REGEX = /:|^\\d+\\.\\d+\\.\\d+\\.\\d+$/;\n\nexport async function getGeneratedCertificate(\n hostname: string,\n logger: LoggerService,\n) {\n const hasModules = await fs.pathExists('node_modules');\n let certPath;\n if (hasModules) {\n certPath = resolvePath(\n 'node_modules/.cache/backstage-backend/dev-cert.pem',\n );\n await fs.ensureDir(dirname(certPath));\n } else {\n certPath = resolvePath('.dev-cert.pem');\n }\n\n if (await fs.pathExists(certPath)) {\n try {\n const cert = await fs.readFile(certPath);\n\n const crt = forge.pki.certificateFromPem(cert.toString());\n const remainingMs = crt.validity.notAfter.getTime() - Date.now();\n if (remainingMs > FIVE_DAYS_IN_MS) {\n logger.info('Using existing self-signed certificate');\n return {\n key: cert,\n cert,\n };\n }\n } catch (error) {\n logger.warn(`Unable to use existing self-signed certificate, ${error}`);\n }\n }\n\n logger.info('Generating new self-signed certificate');\n const newCert = await generateCertificate(hostname);\n await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');\n return newCert;\n}\n\nasync function generateCertificate(hostname: string) {\n const attributes = [\n {\n name: 'commonName',\n value: 'dev-cert',\n },\n ];\n\n const sans = [\n {\n type: 2, // DNS\n value: 'localhost',\n },\n {\n type: 2,\n value: 'localhost.localdomain',\n },\n {\n type: 2,\n value: '[::1]',\n },\n {\n type: 7, // IP\n ip: '127.0.0.1',\n },\n {\n type: 7,\n ip: 'fe80::1',\n },\n ];\n\n // Add hostname from backend.baseUrl if it doesn't already exist in our list of SANs\n if (!sans.find(({ value, ip }) => value === hostname || ip === hostname)) {\n sans.push(\n IP_HOSTNAME_REGEX.test(hostname)\n ? {\n type: 7,\n ip: hostname,\n }\n : {\n type: 2,\n value: hostname,\n },\n );\n }\n\n const params = {\n algorithm: 'sha256',\n keySize: 2048,\n days: 30,\n extensions: [\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true,\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n timeStamping: true,\n },\n {\n name: 'subjectAltName',\n altNames: sans,\n },\n ],\n };\n\n return new Promise<{ key: string; cert: string }>((resolve, reject) =>\n require('selfsigned').generate(\n attributes,\n params,\n (err: Error, bundle: { private: string; cert: string }) => {\n if (err) {\n reject(err);\n } else {\n resolve({ key: bundle.private, cert: bundle.cert });\n }\n },\n ),\n );\n}\n"],"names":["fs","resolvePath","dirname","forge"],"mappings":";;;;;;;;;;;AAqBA,MAAM,
|
|
1
|
+
{"version":3,"file":"getGeneratedCertificate.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/getGeneratedCertificate.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 fs from 'fs-extra';\nimport { resolve as resolvePath, dirname } from 'path';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport forge from 'node-forge';\n\nconst FIVE_DAYS_IN_MS = 5 * 24 * 60 * 60 * 1000;\n\nconst IP_HOSTNAME_REGEX = /:|^\\d+\\.\\d+\\.\\d+\\.\\d+$/;\n\nexport async function getGeneratedCertificate(\n hostname: string,\n logger: LoggerService,\n) {\n const hasModules = await fs.pathExists('node_modules');\n let certPath;\n if (hasModules) {\n certPath = resolvePath(\n 'node_modules/.cache/backstage-backend/dev-cert.pem',\n );\n await fs.ensureDir(dirname(certPath));\n } else {\n certPath = resolvePath('.dev-cert.pem');\n }\n\n if (await fs.pathExists(certPath)) {\n try {\n const cert = await fs.readFile(certPath);\n\n const crt = forge.pki.certificateFromPem(cert.toString());\n const remainingMs = crt.validity.notAfter.getTime() - Date.now();\n if (remainingMs > FIVE_DAYS_IN_MS) {\n logger.info('Using existing self-signed certificate');\n return {\n key: cert,\n cert,\n };\n }\n } catch (error) {\n logger.warn(`Unable to use existing self-signed certificate, ${error}`);\n }\n }\n\n logger.info('Generating new self-signed certificate');\n const newCert = await generateCertificate(hostname);\n await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');\n return newCert;\n}\n\nasync function generateCertificate(hostname: string) {\n const attributes = [\n {\n name: 'commonName',\n value: 'dev-cert',\n },\n ];\n\n const sans = [\n {\n type: 2, // DNS\n value: 'localhost',\n },\n {\n type: 2,\n value: 'localhost.localdomain',\n },\n {\n type: 2,\n value: '[::1]',\n },\n {\n type: 7, // IP\n ip: '127.0.0.1',\n },\n {\n type: 7,\n ip: 'fe80::1',\n },\n ];\n\n // Add hostname from backend.baseUrl if it doesn't already exist in our list of SANs\n if (!sans.find(({ value, ip }) => value === hostname || ip === hostname)) {\n sans.push(\n IP_HOSTNAME_REGEX.test(hostname)\n ? {\n type: 7,\n ip: hostname,\n }\n : {\n type: 2,\n value: hostname,\n },\n );\n }\n\n const params = {\n algorithm: 'sha256',\n keySize: 2048,\n days: 30,\n extensions: [\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true,\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n timeStamping: true,\n },\n {\n name: 'subjectAltName',\n altNames: sans,\n },\n ],\n };\n\n return new Promise<{ key: string; cert: string }>((resolve, reject) =>\n require('selfsigned').generate(\n attributes,\n params,\n (err: Error, bundle: { private: string; cert: string }) => {\n if (err) {\n reject(err);\n } else {\n resolve({ key: bundle.private, cert: bundle.cert });\n }\n },\n ),\n );\n}\n"],"names":["fs","resolvePath","dirname","forge"],"mappings":";;;;;;;;;;;AAqBA,MAAM,eAAA,GAAkB,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAE3C,MAAM,iBAAA,GAAoB,wBAAA;AAE1B,eAAsB,uBAAA,CACpB,UACA,MAAA,EACA;AACA,EAAA,MAAM,UAAA,GAAa,MAAMA,mBAAA,CAAG,UAAA,CAAW,cAAc,CAAA;AACrD,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,QAAA,GAAWC,oBAAA;AAAA,MACT;AAAA,KACF;AACA,IAAA,MAAMD,mBAAA,CAAG,SAAA,CAAUE,oBAAA,CAAQ,QAAQ,CAAC,CAAA;AAAA,EACtC,CAAA,MAAO;AACL,IAAA,QAAA,GAAWD,qBAAY,eAAe,CAAA;AAAA,EACxC;AAEA,EAAA,IAAI,MAAMD,mBAAA,CAAG,UAAA,CAAW,QAAQ,CAAA,EAAG;AACjC,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,GAAO,MAAMA,mBAAA,CAAG,QAAA,CAAS,QAAQ,CAAA;AAEvC,MAAA,MAAM,MAAMG,sBAAA,CAAM,GAAA,CAAI,kBAAA,CAAmB,IAAA,CAAK,UAAU,CAAA;AACxD,MAAA,MAAM,cAAc,GAAA,CAAI,QAAA,CAAS,SAAS,OAAA,EAAQ,GAAI,KAAK,GAAA,EAAI;AAC/D,MAAA,IAAI,cAAc,eAAA,EAAiB;AACjC,QAAA,MAAA,CAAO,KAAK,wCAAwC,CAAA;AACpD,QAAA,OAAO;AAAA,UACL,GAAA,EAAK,IAAA;AAAA,UACL;AAAA,SACF;AAAA,MACF;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,MAAA,CAAO,IAAA,CAAK,CAAA,gDAAA,EAAmD,KAAK,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M,MAAA,GAAS;AAAA,IACb,SAAA,EAAW,QAAA;AAAA,IACX,OAAA,EAAS,IAAA;AAAA,IACT,IAAA,EAAM,EAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV;AAAA,QACE,IAAA,EAAM,UAAA;AAAA,QACN,WAAA,EAAa,IAAA;AAAA,QACb,gBAAA,EAAkB,IAAA;AAAA,QAClB,cAAA,EAAgB,IAAA;AAAA,QAChB,eAAA,EAAiB,IAAA;AAAA,QACjB,gBAAA,EAAkB;AAAA,OACpB;AAAA,MACA;AAAA,QACE,IAAA,EAAM,aAAA;AAAA,QACN,UAAA,EAAY,IAAA;AAAA,QACZ,UAAA,EAAY,IAAA;AAAA,QACZ,WAAA,EAAa,IAAA;AAAA,QACb,YAAA,EAAc;AAAA,OAChB;AAAA,MACA;AAAA,QACE,IAAA,EAAM,gBAAA;AAAA,QACN,QAAA,EAAU;AAAA;AACZ;AACF,GACF;AAEA,EAAA,OAAO,IAAI,OAAA;AAAA,IAAuC,CAAC,OAAA,EAAS,MAAA,KAC1D,OAAA,CAAQ,YAAY,CAAA,CAAE,QAAA;AAAA,MACpB,UAAA;AAAA,MACA,MAAA;AAAA,MACA,CAAC,KAAY,MAAA,KAA8C;AACzD,QAAA,IAAI,GAAA,EAAK;AACP,UAAA,MAAA,CAAO,GAAG,CAAA;AAAA,QACZ,CAAA,MAAO;AACL,UAAA,OAAA,CAAQ,EAAE,GAAA,EAAK,MAAA,CAAO,SAAS,IAAA,EAAM,MAAA,CAAO,MAAM,CAAA;AAAA,QACpD;AAAA,MACF;AAAA;AACF,GACF;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readCorsOptions.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/readCorsOptions.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 { Config } from '@backstage/config';\nimport { CorsOptions } from 'cors';\nimport { Minimatch } from 'minimatch';\n\n/**\n * Attempts to read a CORS options object from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A CORS options object, or undefined if no cors configuration is present.\n *\n * @example\n * ```ts\n * const corsOptions = readCorsOptions(config.getConfig('backend'));\n * ```\n */\nexport function readCorsOptions(config?: Config): CorsOptions {\n const cc = config?.getOptionalConfig('cors');\n if (!cc) {\n return { origin: false }; // Disable CORS\n }\n\n return removeUnknown({\n origin: createCorsOriginMatcher(readStringArray(cc, 'origin')),\n methods: readStringArray(cc, 'methods'),\n allowedHeaders: readStringArray(cc, 'allowedHeaders'),\n exposedHeaders: readStringArray(cc, 'exposedHeaders'),\n credentials: cc.getOptionalBoolean('credentials'),\n maxAge: cc.getOptionalNumber('maxAge'),\n preflightContinue: cc.getOptionalBoolean('preflightContinue'),\n optionsSuccessStatus: cc.getOptionalNumber('optionsSuccessStatus'),\n });\n}\n\nfunction removeUnknown<T extends object>(obj: T): T {\n return Object.fromEntries(\n Object.entries(obj).filter(([, v]) => v !== undefined),\n ) as T;\n}\n\nfunction readStringArray(config: Config, key: string): string[] | undefined {\n const value = config.getOptional(key);\n if (typeof value === 'string') {\n return [value];\n } else if (!value) {\n return undefined;\n }\n return config.getStringArray(key);\n}\n\nfunction createCorsOriginMatcher(allowedOriginPatterns: string[] | undefined) {\n if (!allowedOriginPatterns) {\n return undefined;\n }\n\n const allowedOriginMatchers = allowedOriginPatterns.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n );\n\n return (\n origin: string | undefined,\n callback: (\n err: Error | null,\n origin: boolean | string | RegExp | (boolean | string | RegExp)[],\n ) => void,\n ) => {\n return callback(\n null,\n allowedOriginMatchers.some(pattern => pattern.match(origin ?? '')),\n );\n };\n}\n"],"names":["Minimatch"],"mappings":";;;;AAgCO,SAAS,gBAAgB,
|
|
1
|
+
{"version":3,"file":"readCorsOptions.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/readCorsOptions.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 { Config } from '@backstage/config';\nimport { CorsOptions } from 'cors';\nimport { Minimatch } from 'minimatch';\n\n/**\n * Attempts to read a CORS options object from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A CORS options object, or undefined if no cors configuration is present.\n *\n * @example\n * ```ts\n * const corsOptions = readCorsOptions(config.getConfig('backend'));\n * ```\n */\nexport function readCorsOptions(config?: Config): CorsOptions {\n const cc = config?.getOptionalConfig('cors');\n if (!cc) {\n return { origin: false }; // Disable CORS\n }\n\n return removeUnknown({\n origin: createCorsOriginMatcher(readStringArray(cc, 'origin')),\n methods: readStringArray(cc, 'methods'),\n allowedHeaders: readStringArray(cc, 'allowedHeaders'),\n exposedHeaders: readStringArray(cc, 'exposedHeaders'),\n credentials: cc.getOptionalBoolean('credentials'),\n maxAge: cc.getOptionalNumber('maxAge'),\n preflightContinue: cc.getOptionalBoolean('preflightContinue'),\n optionsSuccessStatus: cc.getOptionalNumber('optionsSuccessStatus'),\n });\n}\n\nfunction removeUnknown<T extends object>(obj: T): T {\n return Object.fromEntries(\n Object.entries(obj).filter(([, v]) => v !== undefined),\n ) as T;\n}\n\nfunction readStringArray(config: Config, key: string): string[] | undefined {\n const value = config.getOptional(key);\n if (typeof value === 'string') {\n return [value];\n } else if (!value) {\n return undefined;\n }\n return config.getStringArray(key);\n}\n\nfunction createCorsOriginMatcher(allowedOriginPatterns: string[] | undefined) {\n if (!allowedOriginPatterns) {\n return undefined;\n }\n\n const allowedOriginMatchers = allowedOriginPatterns.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n );\n\n return (\n origin: string | undefined,\n callback: (\n err: Error | null,\n origin: boolean | string | RegExp | (boolean | string | RegExp)[],\n ) => void,\n ) => {\n return callback(\n null,\n allowedOriginMatchers.some(pattern => pattern.match(origin ?? '')),\n );\n };\n}\n"],"names":["Minimatch"],"mappings":";;;;AAgCO,SAAS,gBAAgB,MAAA,EAA8B;AAC5D,EAAA,MAAM,EAAA,GAAK,MAAA,EAAQ,iBAAA,CAAkB,MAAM,CAAA;AAC3C,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,OAAO,EAAE,QAAQ,KAAA,EAAM;AAAA,EACzB;AAEA,EAAA,OAAO,aAAA,CAAc;AAAA,IACnB,MAAA,EAAQ,uBAAA,CAAwB,eAAA,CAAgB,EAAA,EAAI,QAAQ,CAAC,CAAA;AAAA,IAC7D,OAAA,EAAS,eAAA,CAAgB,EAAA,EAAI,SAAS,CAAA;AAAA,IACtC,cAAA,EAAgB,eAAA,CAAgB,EAAA,EAAI,gBAAgB,CAAA;AAAA,IACpD,cAAA,EAAgB,eAAA,CAAgB,EAAA,EAAI,gBAAgB,CAAA;AAAA,IACpD,WAAA,EAAa,EAAA,CAAG,kBAAA,CAAmB,aAAa,CAAA;AAAA,IAChD,MAAA,EAAQ,EAAA,CAAG,iBAAA,CAAkB,QAAQ,CAAA;AAAA,IACrC,iBAAA,EAAmB,EAAA,CAAG,kBAAA,CAAmB,mBAAmB,CAAA;AAAA,IAC5D,oBAAA,EAAsB,EAAA,CAAG,iBAAA,CAAkB,sBAAsB;AAAA,GAClE,CAAA;AACH;AAEA,SAAS,cAAgC,GAAA,EAAW;AAClD,EAAA,OAAO,MAAA,CAAO,WAAA;AAAA,IACZ,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,CAAE,MAAA,CAAO,CAAC,GAAG,CAAC,CAAA,KAAM,CAAA,KAAM,MAAS;AAAA,GACvD;AACF;AAEA,SAAS,eAAA,CAAgB,QAAgB,GAAA,EAAmC;AAC1E,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,WAAA,CAAY,GAAG,CAAA;AACpC,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,CAAC,KAAK,CAAA;AAAA,EACf,CAAA,MAAA,IAAW,CAAC,KAAA,EAAO;AACjB,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,MAAA,CAAO,eAAe,GAAG,CAAA;AAClC;AAEA,SAAS,wBAAwB,qBAAA,EAA6C;AAC5E,EAAA,IAAI,CAAC,qBAAA,EAAuB;AAC1B,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,wBAAwB,qBAAA,CAAsB,GAAA;AAAA,IAClD,CAAA,OAAA,KAAW,IAAIA,mBAAA,CAAU,OAAA,EAAS,EAAE,MAAA,EAAQ,IAAA,EAAM,UAAA,EAAY,IAAA,EAAM;AAAA,GACtE;AAEA,EAAA,OAAO,CACL,QACA,QAAA,KAIG;AACH,IAAA,OAAO,QAAA;AAAA,MACL,IAAA;AAAA,MACA,sBAAsB,IAAA,CAAK,CAAA,OAAA,KAAW,QAAQ,KAAA,CAAM,MAAA,IAAU,EAAE,CAAC;AAAA,KACnE;AAAA,EACF,CAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readHelmetOptions.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/readHelmetOptions.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 helmet from 'helmet';\nimport { HelmetOptions } from 'helmet';\nimport kebabCase from 'lodash/kebabCase';\n\n/**\n * Attempts to read Helmet options from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A Helmet options object, or undefined if no Helmet configuration is present.\n *\n * @example\n * ```ts\n * const helmetOptions = readHelmetOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHelmetOptions(config?: Config): HelmetOptions {\n const cspOptions = readCspDirectives(config);\n return {\n contentSecurityPolicy: {\n useDefaults: false,\n directives: applyCspDirectives(cspOptions),\n },\n // These are all disabled in order to maintain backwards compatibility\n // when bumping helmet v5. We can't enable these by default because\n // there is no way for users to configure them.\n // TODO(Rugvip): We should give control of this setup to consumers\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n };\n}\n\ntype CspDirectives = Record<string, string[] | false> | undefined;\n\n/**\n * Attempts to read a CSP directives from the backend configuration object.\n *\n * @example\n * ```yaml\n * backend:\n * csp:\n * connect-src: [\"'self'\", 'http:', 'https:']\n * upgrade-insecure-requests: false\n * ```\n */\nfunction readCspDirectives(config?: Config): CspDirectives {\n const cc = config?.getOptionalConfig('csp');\n if (!cc) {\n return undefined;\n }\n\n const result: Record<string, string[] | false> = {};\n for (const key of cc.keys()) {\n if (cc.get(key) === false) {\n result[key] = false;\n } else {\n result[key] = cc.getStringArray(key);\n }\n }\n\n return result;\n}\n\ntype ContentSecurityPolicyDirectives = Exclude<\n HelmetOptions['contentSecurityPolicy'],\n boolean | undefined\n>['directives'];\n\nexport function applyCspDirectives(\n directives: CspDirectives,\n): ContentSecurityPolicyDirectives {\n const result: ContentSecurityPolicyDirectives =\n helmet.contentSecurityPolicy.getDefaultDirectives();\n\n // TODO(Rugvip): We currently use non-precompiled AJV for validation in the frontend, which uses eval.\n // It should be replaced by any other solution that doesn't require unsafe-eval.\n result['script-src'] = [\"'self'\", \"'unsafe-eval'\"];\n\n // TODO(Rugvip): This is removed so that we maintained backwards compatibility\n // when bumping to helmet v5, we could remove this as well as\n // skip setting `useDefaults: false` in the future.\n delete result['form-action'];\n\n if (directives) {\n for (const [key, value] of Object.entries(directives)) {\n const kebabCaseKey = kebabCase(key);\n if (value === false) {\n delete result[kebabCaseKey];\n } else {\n result[kebabCaseKey] = value;\n }\n }\n }\n\n return result;\n}\n"],"names":["helmet","kebabCase"],"mappings":";;;;;;;;;;AAiCO,SAAS,kBAAkB,
|
|
1
|
+
{"version":3,"file":"readHelmetOptions.cjs.js","sources":["../../../../src/entrypoints/rootHttpRouter/http/readHelmetOptions.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 helmet from 'helmet';\nimport { HelmetOptions } from 'helmet';\nimport kebabCase from 'lodash/kebabCase';\n\n/**\n * Attempts to read Helmet options from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A Helmet options object, or undefined if no Helmet configuration is present.\n *\n * @example\n * ```ts\n * const helmetOptions = readHelmetOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHelmetOptions(config?: Config): HelmetOptions {\n const cspOptions = readCspDirectives(config);\n return {\n contentSecurityPolicy: {\n useDefaults: false,\n directives: applyCspDirectives(cspOptions),\n },\n // These are all disabled in order to maintain backwards compatibility\n // when bumping helmet v5. We can't enable these by default because\n // there is no way for users to configure them.\n // TODO(Rugvip): We should give control of this setup to consumers\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n };\n}\n\ntype CspDirectives = Record<string, string[] | false> | undefined;\n\n/**\n * Attempts to read a CSP directives from the backend configuration object.\n *\n * @example\n * ```yaml\n * backend:\n * csp:\n * connect-src: [\"'self'\", 'http:', 'https:']\n * upgrade-insecure-requests: false\n * ```\n */\nfunction readCspDirectives(config?: Config): CspDirectives {\n const cc = config?.getOptionalConfig('csp');\n if (!cc) {\n return undefined;\n }\n\n const result: Record<string, string[] | false> = {};\n for (const key of cc.keys()) {\n if (cc.get(key) === false) {\n result[key] = false;\n } else {\n result[key] = cc.getStringArray(key);\n }\n }\n\n return result;\n}\n\ntype ContentSecurityPolicyDirectives = Exclude<\n HelmetOptions['contentSecurityPolicy'],\n boolean | undefined\n>['directives'];\n\nexport function applyCspDirectives(\n directives: CspDirectives,\n): ContentSecurityPolicyDirectives {\n const result: ContentSecurityPolicyDirectives =\n helmet.contentSecurityPolicy.getDefaultDirectives();\n\n // TODO(Rugvip): We currently use non-precompiled AJV for validation in the frontend, which uses eval.\n // It should be replaced by any other solution that doesn't require unsafe-eval.\n result['script-src'] = [\"'self'\", \"'unsafe-eval'\"];\n\n // TODO(Rugvip): This is removed so that we maintained backwards compatibility\n // when bumping to helmet v5, we could remove this as well as\n // skip setting `useDefaults: false` in the future.\n delete result['form-action'];\n\n if (directives) {\n for (const [key, value] of Object.entries(directives)) {\n const kebabCaseKey = kebabCase(key);\n if (value === false) {\n delete result[kebabCaseKey];\n } else {\n result[kebabCaseKey] = value;\n }\n }\n }\n\n return result;\n}\n"],"names":["helmet","kebabCase"],"mappings":";;;;;;;;;;AAiCO,SAAS,kBAAkB,MAAA,EAAgC;AAChE,EAAA,MAAM,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