@contember/engine-http 2.2.0-alpha.2 → 2.2.0-alpha.4
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/CLAUDE.md +2 -0
- package/dist/development/index.cjs +9 -0
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +6 -0
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/MasterContainer.cjs +4 -2
- package/dist/development/src/MasterContainer.cjs.map +1 -1
- package/dist/development/src/MasterContainer.js +4 -2
- package/dist/development/src/MasterContainer.js.map +1 -1
- package/dist/development/src/application/PanelApiMount.cjs +8 -0
- package/dist/development/src/application/PanelApiMount.cjs.map +1 -0
- package/dist/development/src/application/PanelApiMount.js +8 -0
- package/dist/development/src/application/PanelApiMount.js.map +1 -0
- package/dist/development/src/application/application.cjs +5 -0
- package/dist/development/src/application/application.cjs.map +1 -1
- package/dist/development/src/application/application.js +5 -0
- package/dist/development/src/application/application.js.map +1 -1
- package/dist/development/src/common/Authorizator.cjs +22 -19
- package/dist/development/src/common/Authorizator.cjs.map +1 -1
- package/dist/development/src/common/Authorizator.js +22 -19
- package/dist/development/src/common/Authorizator.js.map +1 -1
- package/dist/development/src/common/HttpResponse.cjs +5 -3
- package/dist/development/src/common/HttpResponse.cjs.map +1 -1
- package/dist/development/src/common/HttpResponse.js +5 -3
- package/dist/development/src/common/HttpResponse.js.map +1 -1
- package/dist/development/src/config/config.cjs +2 -1
- package/dist/development/src/config/config.cjs.map +1 -1
- package/dist/development/src/config/config.js +2 -1
- package/dist/development/src/config/config.js.map +1 -1
- package/dist/development/src/config/configSchema.cjs +7 -0
- package/dist/development/src/config/configSchema.cjs.map +1 -1
- package/dist/development/src/config/configSchema.js +7 -0
- package/dist/development/src/config/configSchema.js.map +1 -1
- package/dist/development/src/config/configTemplate.cjs +4 -0
- package/dist/development/src/config/configTemplate.cjs.map +1 -1
- package/dist/development/src/config/configTemplate.js +4 -0
- package/dist/development/src/config/configTemplate.js.map +1 -1
- package/dist/development/src/config/projectConfigResolver.cjs +1 -0
- package/dist/development/src/config/projectConfigResolver.cjs.map +1 -1
- package/dist/development/src/config/projectConfigResolver.js +2 -1
- package/dist/development/src/config/projectConfigResolver.js.map +1 -1
- package/dist/development/src/content/ContentApiControllerFactory.cjs +1 -0
- package/dist/development/src/content/ContentApiControllerFactory.cjs.map +1 -1
- package/dist/development/src/content/ContentApiControllerFactory.js +1 -0
- package/dist/development/src/content/ContentApiControllerFactory.js.map +1 -1
- package/dist/development/src/misc/HomepageMiddlewareFactory.cjs +1 -0
- package/dist/development/src/misc/HomepageMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/misc/HomepageMiddlewareFactory.js +1 -0
- package/dist/development/src/misc/HomepageMiddlewareFactory.js.map +1 -1
- package/dist/development/src/project/ProjectContainer.cjs +1 -0
- package/dist/development/src/project/ProjectContainer.cjs.map +1 -1
- package/dist/development/src/project/ProjectContainer.js +1 -0
- package/dist/development/src/project/ProjectContainer.js.map +1 -1
- package/dist/development/src/project-common/ProjectContextResolver.cjs +1 -0
- package/dist/development/src/project-common/ProjectContextResolver.cjs.map +1 -1
- package/dist/development/src/project-common/ProjectContextResolver.js +1 -0
- package/dist/development/src/project-common/ProjectContextResolver.js.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +1 -0
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.js +1 -0
- package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupResolver.cjs +1 -0
- package/dist/development/src/projectGroup/ProjectGroupResolver.cjs.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupResolver.js +1 -0
- package/dist/development/src/projectGroup/ProjectGroupResolver.js.map +1 -1
- package/dist/development/src/system/SystemApiMiddlewareFactory.cjs +1 -0
- package/dist/development/src/system/SystemApiMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/system/SystemApiMiddlewareFactory.js +1 -0
- package/dist/development/src/system/SystemApiMiddlewareFactory.js.map +1 -1
- package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs +1 -0
- package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js +1 -0
- package/dist/development/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js.map +1 -1
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs +1 -0
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.js +1 -0
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
- package/dist/development/src/transfer/ExportApiControllerFactory.cjs +1 -0
- package/dist/development/src/transfer/ExportApiControllerFactory.cjs.map +1 -1
- package/dist/development/src/transfer/ExportApiControllerFactory.js +1 -0
- package/dist/development/src/transfer/ExportApiControllerFactory.js.map +1 -1
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +1 -0
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.js +1 -0
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.js.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.cjs +1 -0
- package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.js +1 -0
- package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/production/index.cjs +9 -0
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +6 -0
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/MasterContainer.cjs +4 -2
- package/dist/production/src/MasterContainer.cjs.map +1 -1
- package/dist/production/src/MasterContainer.js +4 -2
- package/dist/production/src/MasterContainer.js.map +1 -1
- package/dist/production/src/application/PanelApiMount.cjs +8 -0
- package/dist/production/src/application/PanelApiMount.cjs.map +1 -0
- package/dist/production/src/application/PanelApiMount.js +8 -0
- package/dist/production/src/application/PanelApiMount.js.map +1 -0
- package/dist/production/src/application/application.cjs +5 -0
- package/dist/production/src/application/application.cjs.map +1 -1
- package/dist/production/src/application/application.js +5 -0
- package/dist/production/src/application/application.js.map +1 -1
- package/dist/production/src/common/Authorizator.cjs +22 -19
- package/dist/production/src/common/Authorizator.cjs.map +1 -1
- package/dist/production/src/common/Authorizator.js +22 -19
- package/dist/production/src/common/Authorizator.js.map +1 -1
- package/dist/production/src/common/HttpResponse.cjs +5 -3
- package/dist/production/src/common/HttpResponse.cjs.map +1 -1
- package/dist/production/src/common/HttpResponse.js +5 -3
- package/dist/production/src/common/HttpResponse.js.map +1 -1
- package/dist/production/src/config/config.cjs +2 -1
- package/dist/production/src/config/config.cjs.map +1 -1
- package/dist/production/src/config/config.js +2 -1
- package/dist/production/src/config/config.js.map +1 -1
- package/dist/production/src/config/configSchema.cjs +7 -0
- package/dist/production/src/config/configSchema.cjs.map +1 -1
- package/dist/production/src/config/configSchema.js +7 -0
- package/dist/production/src/config/configSchema.js.map +1 -1
- package/dist/production/src/config/configTemplate.cjs +4 -0
- package/dist/production/src/config/configTemplate.cjs.map +1 -1
- package/dist/production/src/config/configTemplate.js +4 -0
- package/dist/production/src/config/configTemplate.js.map +1 -1
- package/dist/production/src/config/projectConfigResolver.cjs +1 -0
- package/dist/production/src/config/projectConfigResolver.cjs.map +1 -1
- package/dist/production/src/config/projectConfigResolver.js +2 -1
- package/dist/production/src/config/projectConfigResolver.js.map +1 -1
- package/dist/production/src/content/ContentApiControllerFactory.cjs +1 -0
- package/dist/production/src/content/ContentApiControllerFactory.cjs.map +1 -1
- package/dist/production/src/content/ContentApiControllerFactory.js +1 -0
- package/dist/production/src/content/ContentApiControllerFactory.js.map +1 -1
- package/dist/production/src/misc/HomepageMiddlewareFactory.cjs +1 -0
- package/dist/production/src/misc/HomepageMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/misc/HomepageMiddlewareFactory.js +1 -0
- package/dist/production/src/misc/HomepageMiddlewareFactory.js.map +1 -1
- package/dist/production/src/project/ProjectContainer.cjs +1 -0
- package/dist/production/src/project/ProjectContainer.cjs.map +1 -1
- package/dist/production/src/project/ProjectContainer.js +1 -0
- package/dist/production/src/project/ProjectContainer.js.map +1 -1
- package/dist/production/src/project-common/ProjectContextResolver.cjs +1 -0
- package/dist/production/src/project-common/ProjectContextResolver.cjs.map +1 -1
- package/dist/production/src/project-common/ProjectContextResolver.js +1 -0
- package/dist/production/src/project-common/ProjectContextResolver.js.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +1 -0
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.js +1 -0
- package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupResolver.cjs +1 -0
- package/dist/production/src/projectGroup/ProjectGroupResolver.cjs.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupResolver.js +1 -0
- package/dist/production/src/projectGroup/ProjectGroupResolver.js.map +1 -1
- package/dist/production/src/system/SystemApiMiddlewareFactory.cjs +1 -0
- package/dist/production/src/system/SystemApiMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/system/SystemApiMiddlewareFactory.js +1 -0
- package/dist/production/src/system/SystemApiMiddlewareFactory.js.map +1 -1
- package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs +1 -0
- package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js +1 -0
- package/dist/production/src/tenant/OidcBackchannelLogoutMiddlewareFactory.js.map +1 -1
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs +1 -0
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.js +1 -0
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
- package/dist/production/src/transfer/ExportApiControllerFactory.cjs +1 -0
- package/dist/production/src/transfer/ExportApiControllerFactory.cjs.map +1 -1
- package/dist/production/src/transfer/ExportApiControllerFactory.js +1 -0
- package/dist/production/src/transfer/ExportApiControllerFactory.js.map +1 -1
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +1 -0
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.js +1 -0
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.js.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.cjs +1 -0
- package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.js +1 -0
- package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +17 -7
- package/dist/types/MasterContainer.d.ts.map +1 -1
- package/dist/types/application/PanelApiMount.d.ts +29 -0
- package/dist/types/application/PanelApiMount.d.ts.map +1 -0
- package/dist/types/application/application.d.ts.map +1 -1
- package/dist/types/application/forceHttpOk.d.ts.map +1 -1
- package/dist/types/application/index.d.ts +1 -0
- package/dist/types/application/index.d.ts.map +1 -1
- package/dist/types/bootstrap/Initializer.d.ts.map +1 -1
- package/dist/types/common/Authorizator.d.ts +9 -1
- package/dist/types/common/Authorizator.d.ts.map +1 -1
- package/dist/types/common/HttpResponse.d.ts +6 -2
- package/dist/types/common/HttpResponse.d.ts.map +1 -1
- package/dist/types/common/ModuleInfoMiddleware.d.ts.map +1 -1
- package/dist/types/common/index.d.ts +2 -0
- package/dist/types/common/index.d.ts.map +1 -1
- package/dist/types/config/config.d.ts +1 -0
- package/dist/types/config/config.d.ts.map +1 -1
- package/dist/types/config/configSchema.d.ts +26 -12
- package/dist/types/config/configSchema.d.ts.map +1 -1
- package/dist/types/config/configTemplate.d.ts.map +1 -1
- package/dist/types/config/projectConfigResolver.d.ts +1 -0
- package/dist/types/config/projectConfigResolver.d.ts.map +1 -1
- package/dist/types/config/tenantConfigResolver.d.ts.map +1 -1
- package/dist/types/content/ContentApiControllerFactory.d.ts.map +1 -1
- package/dist/types/content/ContentApiSpecificCache.d.ts.map +1 -1
- package/dist/types/content/ContentQueryHandlerFactory.d.ts.map +1 -1
- package/dist/types/content/ContentSchemaResolver.d.ts.map +1 -1
- package/dist/types/content/GraphQlSchemaFactory.d.ts.map +1 -1
- package/dist/types/content/NotModifiedChecker.d.ts.map +1 -1
- package/dist/types/content/ProjectMembershipFetcher.d.ts.map +1 -1
- package/dist/types/content/ProjectMembershipResolver.d.ts.map +1 -1
- package/dist/types/graphql/dbQueriesListener.d.ts.map +1 -1
- package/dist/types/graphql/execution.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/project/ProjectContainer.d.ts.map +1 -1
- package/dist/types/project/ProjectContainerResolver.d.ts.map +1 -1
- package/dist/types/project/ProjectContainerStore.d.ts.map +1 -1
- package/dist/types/project/ProjectDatabaseMetadataResolver.d.ts.map +1 -1
- package/dist/types/project/ProjectInitializer.d.ts.map +1 -1
- package/dist/types/project/ProjectSchemaResolver.d.ts.map +1 -1
- package/dist/types/project-common/ProjectContextResolver.d.ts.map +1 -1
- package/dist/types/projectGroup/ProjectGroupContainer.d.ts.map +1 -1
- package/dist/types/projectGroup/ProjectGroupContainerResolver.d.ts.map +1 -1
- package/dist/types/projectGroup/ProjectGroupResolver.d.ts.map +1 -1
- package/dist/types/prometheus/CollectHttpMetricsMiddelware.d.ts.map +1 -1
- package/dist/types/prometheus/CustomMetric.d.ts.map +1 -1
- package/dist/types/prometheus/ProjectGroupContainerMetricsHook.d.ts.map +1 -1
- package/dist/types/prometheus/PrometheusRegistryFactory.d.ts.map +1 -1
- package/dist/types/prometheus/ShowMetricsMiddleware.d.ts.map +1 -1
- package/dist/types/prometheus/contemberEngineInfoMetric.d.ts.map +1 -1
- package/dist/types/prometheus/dbMetrics.d.ts.map +1 -1
- package/dist/types/providers.d.ts.map +1 -1
- package/dist/types/system/ContentQueryExecutor.d.ts.map +1 -1
- package/dist/types/system/SystemApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/types/system/SystemGraphQLContextFactory.d.ts.map +1 -1
- package/dist/types/system/SystemGraphQLHandlerFactory.d.ts.map +1 -1
- package/dist/types/tenant/OidcBackchannelLogoutMiddlewareFactory.d.ts.map +1 -1
- package/dist/types/tenant/TenantApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/types/tenant/TenantGraphQLHandlerFactory.d.ts.map +1 -1
- package/dist/types/testing/TestTransactions.d.ts.map +1 -1
- package/dist/types/transfer/Command.d.ts +5 -5
- package/dist/types/transfer/Command.d.ts.map +1 -1
- package/dist/types/transfer/ContentSchemaTransferMappingFactory.d.ts.map +1 -1
- package/dist/types/transfer/ExportApiControllerFactory.d.ts.map +1 -1
- package/dist/types/transfer/ExportExecutor.d.ts.map +1 -1
- package/dist/types/transfer/ImportApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
- package/dist/types/transfer/SystemSchemaTransferMappingFactory.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/CryptoWrapper.d.ts +1 -1
- package/dist/types/utils/CryptoWrapper.d.ts.map +1 -1
- package/dist/types/utils/memoizeObject.d.ts.map +1 -1
- package/dist/types/utils/sentry.d.ts.map +1 -1
- package/dist/types/utils/serverStartup.d.ts +1 -0
- package/dist/types/utils/serverStartup.d.ts.map +1 -1
- package/dist/types/utils/serverTermination.d.ts.map +1 -1
- package/dist/types/utils/strings.d.ts.map +1 -1
- package/dist/types/workers/ApplicationWorkerManager.d.ts.map +1 -1
- package/package.json +15 -15
- package/src/MasterContainer.ts +9 -2
- package/src/application/PanelApiMount.ts +33 -0
- package/src/application/application.ts +4 -0
- package/src/application/index.ts +1 -0
- package/src/common/Authorizator.ts +41 -21
- package/src/common/HttpResponse.ts +4 -0
- package/src/common/index.ts +2 -0
- package/src/config/config.ts +2 -0
- package/src/config/configSchema.ts +7 -0
- package/src/config/configTemplate.ts +4 -0
- package/src/config/projectConfigResolver.ts +1 -1
- package/src/index.ts +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["logger","module","WebSocketServer","http","getClientIP","URL","HttpErrorResponse","ws","performance","HttpResponse","shouldForceHttpOk","isForceHttpOkRequested","remoteAddress","FingerCrossedLoggerHandler","cpuUsage","memoryUsage","Readable","pathTo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G,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;;;"}
|
|
1
|
+
{"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tfor (const [name, value] of Object.entries(response.headers ?? {})) {\n\t\t\tctx.set(name, value)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t...response.headers,\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["logger","module","WebSocketServer","http","getClientIP","URL","HttpErrorResponse","ws","performance","HttpResponse","shouldForceHttpOk","isForceHttpOkRequested","remoteAddress","FingerCr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A,aAAa,IAAI;AAE1C,QAAM,QAAQ,SAAS,KAA4B;AAClD,UAAMC,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;;;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { pathToRegexp } from "path-to-regexp";
|
|
2
2
|
import { HttpErrorResponse, HttpResponse } from "../common/HttpResponse.js";
|
|
3
3
|
import "ipaddr.js";
|
|
4
|
+
import "@contember/engine-tenant-api";
|
|
4
5
|
import Koa from "koa";
|
|
5
6
|
import * as http from "node:http";
|
|
6
7
|
import { WebSocketServer } from "ws";
|
|
@@ -290,6 +291,9 @@ class Application {
|
|
|
290
291
|
if (response.contentType) {
|
|
291
292
|
ctx.set("Content-type", response.contentType);
|
|
292
293
|
}
|
|
294
|
+
for (const [name, value] of Object.entries(response.headers ?? {})) {
|
|
295
|
+
ctx.set(name, value);
|
|
296
|
+
}
|
|
293
297
|
ctx.status = response.code;
|
|
294
298
|
if (response.body !== void 0) {
|
|
295
299
|
ctx.body = response.body;
|
|
@@ -297,6 +301,7 @@ class Application {
|
|
|
297
301
|
}
|
|
298
302
|
sendRawHttpResponse(socket, response) {
|
|
299
303
|
const headers = {
|
|
304
|
+
...response.headers,
|
|
300
305
|
"Connection": "close",
|
|
301
306
|
"Content-Type": response.contentType ?? "text/plain",
|
|
302
307
|
"Content-Length": String(response.body?.length ?? 0)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"application.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["ws","match"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBO,MAAM,YAAY;AAAA,EAWxB,YACkB,sBACA,cACA,WACA,SACA,QAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AAflB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AACR,kBAAA,MAAQ,gBAAA;AACR,kBAAA,MAAQ,oBAAA;AASP,UAAM,uBAAuB,aAAa,MAAM;AAChD,SAAK,oBAAoB,yBAAyB,OA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,MAAM,EAAE,KAAK;AAClC,UAAI,WAAW,MAAM;AACpB,eAAO,EAAE,QAAQ,YAAY,MAAM,YAAY,QAAQ,MAAM,OAAA;AAAA,MAC9D;AAAA,IACD;AACA,WAAO;AAAA,EACR;AACD;AAyDA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,EAAE,QAAQ,SAAS,aAAa,IAAI;AAE1C,QAAM,QAAQ,SAAS,KAA4B;AAClD,UAAMC,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;"}
|
|
1
|
+
{"version":3,"file":"application.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve =>\n\t\t\t\twss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\t\tresolve(ws)\n\t\t\t\t})\n\t\t\t)\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tfor (const [name, value] of Object.entries(response.headers ?? {})) {\n\t\t\tctx.set(name, value)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t...response.headers,\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t;(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["ws","match"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBO,MAAM,YAAY;AAAA,EAWxB,YACkB,sBACA,cACA,WACA,SACA,QAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AAflB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AACR,kBAAA,MAAQ,gBAAA;AACR,kBAAA,MAAQ,oBAAA;AASP,UAAM,uBAAuB,aAAa,MAAM;AAChD,SAAK,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAC1H,SAAK,iBAAiB,aAAa,MAAM,kBAAkB,CAAA;AAC3D,SAAK,qBAAqB,aAAa,MAAM,wBAAwB;AAAA,EACtE;AAAA,EAEA,cAAc,YAAgC;AAC7C,SAAK,YAAY,KAAK,UAAU;AAAA,EACjC;AAAA,EAEO,SAAS,QAAgB,MAAc,YAAkC;AAC/E,SAAK,OAAO,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EACF;AAAA,EAEO,iBAAiB,QAAgB,MAAc,YAA0C;AAC/F,SAAK,eAAe,KAAK;AAAA,MACxB;AAAA,MACA;AAAA,M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QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;"}
|
|
@@ -52,17 +52,8 @@ class Authenticator {
|
|
|
52
52
|
this.geoCountryHeader = geoCountryHeader;
|
|
53
53
|
__publicField(this, "createAuthError", (message) => new HttpResponse.HttpErrorResponse(401, `Authorization failure: ${message}`));
|
|
54
54
|
}
|
|
55
|
-
async authenticate({ request, timer, clientIp }) {
|
|
56
|
-
const authHeader = request.headers.authorization;
|
|
57
|
-
if (!authHeader) {
|
|
58
|
-
return null;
|
|
59
|
-
}
|
|
60
|
-
const authHeaderPattern = /^Bearer\s+(\w+)$/i;
|
|
61
|
-
const match = authHeader.match(authHeaderPattern);
|
|
62
|
-
if (match === null) {
|
|
63
|
-
throw this.createAuthError(`invalid Authorization header format`);
|
|
64
|
-
}
|
|
65
|
-
const [, token] = match;
|
|
55
|
+
async authenticate({ request, timer, clientIp, fallbackIdentity }) {
|
|
56
|
+
const authHeader = request.headers.authorization || void 0;
|
|
66
57
|
const socketIp = sanitizeIp(clientIp);
|
|
67
58
|
const socketUserAgent = sanitizeUserAgent(readHeader(request, "user-agent"));
|
|
68
59
|
const forwardedIp = sanitizeIp(readHeader(request, forwardedClientIpHeader));
|
|
@@ -70,21 +61,18 @@ class Authenticator {
|
|
|
70
61
|
const forwardedGeoCountry = this.geoCountryHeader !== void 0 ? sanitizeGeoCountry(readHeader(request, this.geoCountryHeader.toLowerCase())) : void 0;
|
|
71
62
|
const socketInfo = { ip: socketIp, userAgent: socketUserAgent };
|
|
72
63
|
const forwardedInfo = forwardedIp !== void 0 || forwardedUserAgent !== void 0 ? { ip: forwardedIp, userAgent: forwardedUserAgent } : void 0;
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
);
|
|
77
|
-
if (!authResult.ok) {
|
|
78
|
-
throw this.createAuthError(authResult.errorMessage);
|
|
64
|
+
const verified = authHeader !== void 0 ? await this.verifyAuthorizationHeader(authHeader, timer, socketInfo, forwardedInfo) : fallbackIdentity;
|
|
65
|
+
if (verified === void 0) {
|
|
66
|
+
return null;
|
|
79
67
|
}
|
|
80
68
|
const assumedIdentityId = request.headers[assumeIdentityHeader] ?? void 0;
|
|
81
69
|
if (Array.isArray(assumedIdentityId)) {
|
|
82
70
|
throw new HttpResponse.HttpErrorResponse(400, `Invalid ${assumedIdentityId} header format`);
|
|
83
71
|
}
|
|
84
|
-
const trustForwarded =
|
|
72
|
+
const trustForwarded = verified.trustForwardedInfo && forwardedInfo !== void 0;
|
|
85
73
|
const trustGeo = trustForwarded && forwardedGeoCountry !== void 0;
|
|
86
74
|
return {
|
|
87
|
-
...
|
|
75
|
+
...verified,
|
|
88
76
|
assumedIdentityId,
|
|
89
77
|
clientIp: trustForwarded ? forwardedInfo?.ip ?? socketIp : socketIp,
|
|
90
78
|
clientUserAgent: trustForwarded ? forwardedInfo?.userAgent ?? socketUserAgent : socketUserAgent,
|
|
@@ -93,6 +81,21 @@ class Authenticator {
|
|
|
93
81
|
geoCountry: trustGeo ? forwardedGeoCountry : void 0
|
|
94
82
|
};
|
|
95
83
|
}
|
|
84
|
+
async verifyAuthorizationHeader(authHeader, timer, socketInfo, forwardedInfo) {
|
|
85
|
+
const match = authHeader.match(/^Bearer\s+(\w+)$/i);
|
|
86
|
+
if (match === null) {
|
|
87
|
+
throw this.createAuthError(`invalid Authorization header format`);
|
|
88
|
+
}
|
|
89
|
+
const [, token] = match;
|
|
90
|
+
const authResult = await timer(
|
|
91
|
+
"Auth",
|
|
92
|
+
() => this.apiKeyManager.verifyAndProlong(this.tenantDatabase, this.tenantReadDatabase, token, socketInfo, forwardedInfo)
|
|
93
|
+
);
|
|
94
|
+
if (!authResult.ok) {
|
|
95
|
+
throw this.createAuthError(authResult.errorMessage);
|
|
96
|
+
}
|
|
97
|
+
return authResult.result;
|
|
98
|
+
}
|
|
96
99
|
}
|
|
97
100
|
exports.Authenticator = Authenticator;
|
|
98
101
|
//# sourceMappingURL=Authorizator.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Authorizator.cjs","sources":["../../../../../packages/engine-http/src/common/Authorizator.ts"],"sourcesContent":["import { ApiKeyManager, DatabaseContext, VerifyResult } from '@contember/engine-tenant-api'\nimport { HttpErrorResponse } from './HttpResponse.js'\nimport { Timer } from '../application/index.js'\nimport { IncomingMessage } from 'node:http'\nimport ipaddr from 'ipaddr.js'\n\nexport type AuthResult =\n\t& VerifyResult\n\t& {\n\t\tassumedIdentityId?: string\n\t\tclientIp?: string\n\t\tclientUserAgent?: string\n\t\tforwarderIp?: string\n\t\tforwarderUserAgent?: string\n\t\t/** A03: client country from the trusted reverse-proxy geo header, when configured + trusted. */\n\t\tgeoCountry?: string\n\t}\n\nconst assumeIdentityHeader = 'x-contember-assume-identity'\nconst forwardedClientIpHeader = 'x-contember-client-ip'\nconst forwardedClientUserAgentHeader = 'x-contember-client-user-agent'\n\nconst USER_AGENT_MAX_LENGTH = 512\n// A03: cap the trusted country header so a misbehaving/overlong upstream value\n// can never bloat the auth-log row. A country code is 2 chars; allow some slack\n// for names/regions but keep it bounded.\nconst GEO_COUNTRY_MAX_LENGTH = 64\n\nconst readHeader = (request: IncomingMessage, name: string): string | undefined => {\n\tconst value = request.headers[name]\n\tif (Array.isArray(value)) {\n\t\treturn value[0]\n\t}\n\treturn typeof value === 'string' ? value : undefined\n}\n\nconst sanitizeGeoCountry = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst trimmed = value.trim()\n\tif (trimmed.length === 0) {\n\t\treturn undefined\n\t}\n\treturn trimmed.length > GEO_COUNTRY_MAX_LENGTH ? trimmed.slice(0, GEO_COUNTRY_MAX_LENGTH) : trimmed\n}\n\nconst sanitizeUserAgent = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\treturn value.length > USER_AGENT_MAX_LENGTH ? value.slice(0, USER_AGENT_MAX_LENGTH) : value\n}\n\nconst sanitizeIp = (value: string | undefined): string | undefined => {\n\tif (!value) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tipaddr.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n\treturn value\n}\n\nexport class Authenticator {\n\tprivate createAuthError = (message: string) => new HttpErrorResponse(401, `Authorization failure: ${message}`)\n\n\tconstructor(\n\t\tprivate readonly tenantDatabase: DatabaseContext,\n\t\tprivate readonly tenantReadDatabase: DatabaseContext,\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\t/** A03: configured trusted geo-country header name (lower-cased), or undefined when the feature is off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {\n\t}\n\n\tpublic async authenticate(\n\t\t{ request, timer, clientIp
|
|
1
|
+
{"version":3,"file":"Authorizator.cjs","sources":["../../../../../packages/engine-http/src/common/Authorizator.ts"],"sourcesContent":["import { ApiKeyManager, DatabaseContext, VerifyResult } from '@contember/engine-tenant-api'\nimport { HttpErrorResponse } from './HttpResponse.js'\nimport { Timer } from '../application/index.js'\nimport { IncomingMessage } from 'node:http'\nimport ipaddr from 'ipaddr.js'\n\nexport type AuthResult =\n\t& VerifyResult\n\t& {\n\t\tassumedIdentityId?: string\n\t\tclientIp?: string\n\t\tclientUserAgent?: string\n\t\tforwarderIp?: string\n\t\tforwarderUserAgent?: string\n\t\t/** A03: client country from the trusted reverse-proxy geo header, when configured + trusted. */\n\t\tgeoCountry?: string\n\t}\n\nconst assumeIdentityHeader = 'x-contember-assume-identity'\nconst forwardedClientIpHeader = 'x-contember-client-ip'\nconst forwardedClientUserAgentHeader = 'x-contember-client-user-agent'\n\nconst USER_AGENT_MAX_LENGTH = 512\n// A03: cap the trusted country header so a misbehaving/overlong upstream value\n// can never bloat the auth-log row. A country code is 2 chars; allow some slack\n// for names/regions but keep it bounded.\nconst GEO_COUNTRY_MAX_LENGTH = 64\n\nconst readHeader = (request: IncomingMessage, name: string): string | undefined => {\n\tconst value = request.headers[name]\n\tif (Array.isArray(value)) {\n\t\treturn value[0]\n\t}\n\treturn typeof value === 'string' ? value : undefined\n}\n\nconst sanitizeGeoCountry = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst trimmed = value.trim()\n\tif (trimmed.length === 0) {\n\t\treturn undefined\n\t}\n\treturn trimmed.length > GEO_COUNTRY_MAX_LENGTH ? trimmed.slice(0, GEO_COUNTRY_MAX_LENGTH) : trimmed\n}\n\nconst sanitizeUserAgent = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\treturn value.length > USER_AGENT_MAX_LENGTH ? value.slice(0, USER_AGENT_MAX_LENGTH) : value\n}\n\nconst sanitizeIp = (value: string | undefined): string | undefined => {\n\tif (!value) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tipaddr.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n\treturn value\n}\n\nexport class Authenticator {\n\tprivate createAuthError = (message: string) => new HttpErrorResponse(401, `Authorization failure: ${message}`)\n\n\tconstructor(\n\t\tprivate readonly tenantDatabase: DatabaseContext,\n\t\tprivate readonly tenantReadDatabase: DatabaseContext,\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\t/** A03: configured trusted geo-country header name (lower-cased), or undefined when the feature is off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {\n\t}\n\n\tpublic async authenticate(\n\t\t{ request, timer, clientIp, fallbackIdentity }: {\n\t\t\trequest: IncomingMessage\n\t\t\ttimer: Timer\n\t\t\tclientIp?: string\n\t\t\t/**\n\t\t\t * Identity to act as when the request carries no Authorization header. Lets a first-party UI\n\t\t\t * served by this process reach a pre-sign-in surface without a token existing anywhere to be\n\t\t\t * leaked or misconfigured — the roles come from the caller, not from the database. An actual\n\t\t\t * Authorization header always wins, so this can never widen a credentialed request.\n\t\t\t */\n\t\t\tfallbackIdentity?: VerifyResult\n\t\t},\n\t): Promise<AuthResult | null> {\n\t\tconst authHeader = request.headers.authorization || undefined\n\t\tconst socketIp = sanitizeIp(clientIp)\n\t\tconst socketUserAgent = sanitizeUserAgent(readHeader(request, 'user-agent'))\n\t\tconst forwardedIp = sanitizeIp(readHeader(request, forwardedClientIpHeader))\n\t\tconst forwardedUserAgent = sanitizeUserAgent(readHeader(request, forwardedClientUserAgentHeader))\n\t\t// Header lookup is case-insensitive: Node lower-cases all incoming header\n\t\t// names, so the configured name is lower-cased to match.\n\t\tconst forwardedGeoCountry = this.geoCountryHeader !== undefined\n\t\t\t? sanitizeGeoCountry(readHeader(request, this.geoCountryHeader.toLowerCase()))\n\t\t\t: undefined\n\t\tconst socketInfo = { ip: socketIp, userAgent: socketUserAgent }\n\t\tconst forwardedInfo = (forwardedIp !== undefined || forwardedUserAgent !== undefined)\n\t\t\t? { ip: forwardedIp, userAgent: forwardedUserAgent }\n\t\t\t: undefined\n\t\tconst verified = authHeader !== undefined\n\t\t\t? await this.verifyAuthorizationHeader(authHeader, timer, socketInfo, forwardedInfo)\n\t\t\t: fallbackIdentity\n\t\tif (verified === undefined) {\n\t\t\treturn null\n\t\t}\n\t\tconst assumedIdentityId = request.headers[assumeIdentityHeader] ?? undefined\n\t\tif (Array.isArray(assumedIdentityId)) {\n\t\t\tthrow new HttpErrorResponse(400, `Invalid ${assumedIdentityId} header format`)\n\t\t}\n\t\tconst trustForwarded = verified.trustForwardedInfo && forwardedInfo !== undefined\n\t\t// A03: the geo country is only ever exposed under the exact same gate as the\n\t\t// forwarded IP/UA — a trusted key that actually forwarded client info. This\n\t\t// keeps the signals consistent: we never score a real client country against\n\t\t// the proxy's own socket IP (which is what `clientIp` falls back to when no\n\t\t// forwarded info was sent). An untrusted key, or one that forwarded nothing,\n\t\t// yields no country.\n\t\tconst trustGeo = trustForwarded && forwardedGeoCountry !== undefined\n\t\treturn {\n\t\t\t...verified,\n\t\t\tassumedIdentityId,\n\t\t\tclientIp: trustForwarded ? (forwardedInfo?.ip ?? socketIp) : socketIp,\n\t\t\tclientUserAgent: trustForwarded ? (forwardedInfo?.userAgent ?? socketUserAgent) : socketUserAgent,\n\t\t\tforwarderIp: trustForwarded ? socketIp : undefined,\n\t\t\tforwarderUserAgent: trustForwarded ? socketUserAgent : undefined,\n\t\t\tgeoCountry: trustGeo ? forwardedGeoCountry : undefined,\n\t\t}\n\t}\n\n\tprivate async verifyAuthorizationHeader(\n\t\tauthHeader: string,\n\t\ttimer: Timer,\n\t\tsocketInfo: { ip?: string; userAgent?: string },\n\t\tforwardedInfo: { ip?: string; userAgent?: string } | undefined,\n\t): Promise<VerifyResult> {\n\t\tconst match = authHeader.match(/^Bearer\\s+(\\w+)$/i)\n\t\tif (match === null) {\n\t\t\tthrow this.createAuthError(`invalid Authorization header format`)\n\t\t}\n\t\tconst [, token] = match\n\t\tconst authResult = await timer(\n\t\t\t'Auth',\n\t\t\t() => this.apiKeyManager.verifyAndProlong(this.tenantDatabase, this.tenantReadDatabase, token, socketInfo, forwardedInfo),\n\t\t)\n\t\tif (!authResult.ok) {\n\t\t\tthrow this.createAuthError(authResult.errorMessage)\n\t\t}\n\t\treturn authResult.result\n\t}\n}\n"],"names":["HttpErrorResponse"],"mappings":";;;;;;;AAkBA,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,iCAAiC;AAEvC,MAAM,wBAAwB;AAI9B,MAAM,yBAAyB;AAE/B,MAAM,aAAa,CAAC,SAA0B,SAAqC;AAClF,QAAM,QAAQ,QAAQ,QAAQ,IAAI;AAClC,MAAI,MAAM,QAAQ,KAAK,GAAG;AACzB,WAAO,MAAM,CAAC;AAAA,EACf;AACA,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC5C;AAEA,MAAM,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
|
|
51
51
|
__publicField(this, "createAuthError", (message) => new HttpErrorResponse(401, `Authorization failure: ${message}`));
|
|
52
52
|
}
|
|
53
|
-
async authenticate({ request, timer, clientIp }) {
|
|
54
|
-
const authHeader = request.headers.authorization;
|
|
55
|
-
if (!authHeader) {
|
|
56
|
-
return null;
|
|
57
|
-
}
|
|
58
|
-
const authHeaderPattern = /^Bearer\s+(\w+)$/i;
|
|
59
|
-
const match = authHeader.match(authHeaderPattern);
|
|
60
|
-
if (match === null) {
|
|
61
|
-
throw this.createAuthError(`invalid Authorization header format`);
|
|
62
|
-
}
|
|
63
|
-
const [, token] = match;
|
|
53
|
+
async authenticate({ request, timer, clientIp, fallbackIdentity }) {
|
|
54
|
+
const authHeader = request.headers.authorization || void 0;
|
|
64
55
|
const socketIp = sanitizeIp(clientIp);
|
|
65
56
|
const socketUserAgent = sanitizeUserAgent(readHeader(request, "user-agent"));
|
|
66
57
|
const forwardedIp = sanitizeIp(readHeader(request, forwardedClientIpHeader));
|
|
@@ -68,21 +59,18 @@ class Authenticator {
|
|
|
68
59
|
const forwardedGeoCountry = this.geoCountryHeader !== void 0 ? sanitizeGeoCountry(readHeader(request, this.geoCountryHeader.toLowerCase())) : void 0;
|
|
69
60
|
const socketInfo = { ip: socketIp, userAgent: socketUserAgent };
|
|
70
61
|
const forwardedInfo = forwardedIp !== void 0 || forwardedUserAgent !== void 0 ? { ip: forwardedIp, userAgent: forwardedUserAgent } : void 0;
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
);
|
|
75
|
-
if (!authResult.ok) {
|
|
76
|
-
throw this.createAuthError(authResult.errorMessage);
|
|
62
|
+
const verified = authHeader !== void 0 ? await this.verifyAuthorizationHeader(authHeader, timer, socketInfo, forwardedInfo) : fallbackIdentity;
|
|
63
|
+
if (verified === void 0) {
|
|
64
|
+
return null;
|
|
77
65
|
}
|
|
78
66
|
const assumedIdentityId = request.headers[assumeIdentityHeader] ?? void 0;
|
|
79
67
|
if (Array.isArray(assumedIdentityId)) {
|
|
80
68
|
throw new HttpErrorResponse(400, `Invalid ${assumedIdentityId} header format`);
|
|
81
69
|
}
|
|
82
|
-
const trustForwarded =
|
|
70
|
+
const trustForwarded = verified.trustForwardedInfo && forwardedInfo !== void 0;
|
|
83
71
|
const trustGeo = trustForwarded && forwardedGeoCountry !== void 0;
|
|
84
72
|
return {
|
|
85
|
-
...
|
|
73
|
+
...verified,
|
|
86
74
|
assumedIdentityId,
|
|
87
75
|
clientIp: trustForwarded ? forwardedInfo?.ip ?? socketIp : socketIp,
|
|
88
76
|
clientUserAgent: trustForwarded ? forwardedInfo?.userAgent ?? socketUserAgent : socketUserAgent,
|
|
@@ -91,6 +79,21 @@ class Authenticator {
|
|
|
91
79
|
geoCountry: trustGeo ? forwardedGeoCountry : void 0
|
|
92
80
|
};
|
|
93
81
|
}
|
|
82
|
+
async verifyAuthorizationHeader(authHeader, timer, socketInfo, forwardedInfo) {
|
|
83
|
+
const match = authHeader.match(/^Bearer\s+(\w+)$/i);
|
|
84
|
+
if (match === null) {
|
|
85
|
+
throw this.createAuthError(`invalid Authorization header format`);
|
|
86
|
+
}
|
|
87
|
+
const [, token] = match;
|
|
88
|
+
const authResult = await timer(
|
|
89
|
+
"Auth",
|
|
90
|
+
() => this.apiKeyManager.verifyAndProlong(this.tenantDatabase, this.tenantReadDatabase, token, socketInfo, forwardedInfo)
|
|
91
|
+
);
|
|
92
|
+
if (!authResult.ok) {
|
|
93
|
+
throw this.createAuthError(authResult.errorMessage);
|
|
94
|
+
}
|
|
95
|
+
return authResult.result;
|
|
96
|
+
}
|
|
94
97
|
}
|
|
95
98
|
export {
|
|
96
99
|
Authenticator
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Authorizator.js","sources":["../../../../../packages/engine-http/src/common/Authorizator.ts"],"sourcesContent":["import { ApiKeyManager, DatabaseContext, VerifyResult } from '@contember/engine-tenant-api'\nimport { HttpErrorResponse } from './HttpResponse.js'\nimport { Timer } from '../application/index.js'\nimport { IncomingMessage } from 'node:http'\nimport ipaddr from 'ipaddr.js'\n\nexport type AuthResult =\n\t& VerifyResult\n\t& {\n\t\tassumedIdentityId?: string\n\t\tclientIp?: string\n\t\tclientUserAgent?: string\n\t\tforwarderIp?: string\n\t\tforwarderUserAgent?: string\n\t\t/** A03: client country from the trusted reverse-proxy geo header, when configured + trusted. */\n\t\tgeoCountry?: string\n\t}\n\nconst assumeIdentityHeader = 'x-contember-assume-identity'\nconst forwardedClientIpHeader = 'x-contember-client-ip'\nconst forwardedClientUserAgentHeader = 'x-contember-client-user-agent'\n\nconst USER_AGENT_MAX_LENGTH = 512\n// A03: cap the trusted country header so a misbehaving/overlong upstream value\n// can never bloat the auth-log row. A country code is 2 chars; allow some slack\n// for names/regions but keep it bounded.\nconst GEO_COUNTRY_MAX_LENGTH = 64\n\nconst readHeader = (request: IncomingMessage, name: string): string | undefined => {\n\tconst value = request.headers[name]\n\tif (Array.isArray(value)) {\n\t\treturn value[0]\n\t}\n\treturn typeof value === 'string' ? value : undefined\n}\n\nconst sanitizeGeoCountry = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst trimmed = value.trim()\n\tif (trimmed.length === 0) {\n\t\treturn undefined\n\t}\n\treturn trimmed.length > GEO_COUNTRY_MAX_LENGTH ? trimmed.slice(0, GEO_COUNTRY_MAX_LENGTH) : trimmed\n}\n\nconst sanitizeUserAgent = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\treturn value.length > USER_AGENT_MAX_LENGTH ? value.slice(0, USER_AGENT_MAX_LENGTH) : value\n}\n\nconst sanitizeIp = (value: string | undefined): string | undefined => {\n\tif (!value) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tipaddr.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n\treturn value\n}\n\nexport class Authenticator {\n\tprivate createAuthError = (message: string) => new HttpErrorResponse(401, `Authorization failure: ${message}`)\n\n\tconstructor(\n\t\tprivate readonly tenantDatabase: DatabaseContext,\n\t\tprivate readonly tenantReadDatabase: DatabaseContext,\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\t/** A03: configured trusted geo-country header name (lower-cased), or undefined when the feature is off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {\n\t}\n\n\tpublic async authenticate(\n\t\t{ request, timer, clientIp
|
|
1
|
+
{"version":3,"file":"Authorizator.js","sources":["../../../../../packages/engine-http/src/common/Authorizator.ts"],"sourcesContent":["import { ApiKeyManager, DatabaseContext, VerifyResult } from '@contember/engine-tenant-api'\nimport { HttpErrorResponse } from './HttpResponse.js'\nimport { Timer } from '../application/index.js'\nimport { IncomingMessage } from 'node:http'\nimport ipaddr from 'ipaddr.js'\n\nexport type AuthResult =\n\t& VerifyResult\n\t& {\n\t\tassumedIdentityId?: string\n\t\tclientIp?: string\n\t\tclientUserAgent?: string\n\t\tforwarderIp?: string\n\t\tforwarderUserAgent?: string\n\t\t/** A03: client country from the trusted reverse-proxy geo header, when configured + trusted. */\n\t\tgeoCountry?: string\n\t}\n\nconst assumeIdentityHeader = 'x-contember-assume-identity'\nconst forwardedClientIpHeader = 'x-contember-client-ip'\nconst forwardedClientUserAgentHeader = 'x-contember-client-user-agent'\n\nconst USER_AGENT_MAX_LENGTH = 512\n// A03: cap the trusted country header so a misbehaving/overlong upstream value\n// can never bloat the auth-log row. A country code is 2 chars; allow some slack\n// for names/regions but keep it bounded.\nconst GEO_COUNTRY_MAX_LENGTH = 64\n\nconst readHeader = (request: IncomingMessage, name: string): string | undefined => {\n\tconst value = request.headers[name]\n\tif (Array.isArray(value)) {\n\t\treturn value[0]\n\t}\n\treturn typeof value === 'string' ? value : undefined\n}\n\nconst sanitizeGeoCountry = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst trimmed = value.trim()\n\tif (trimmed.length === 0) {\n\t\treturn undefined\n\t}\n\treturn trimmed.length > GEO_COUNTRY_MAX_LENGTH ? trimmed.slice(0, GEO_COUNTRY_MAX_LENGTH) : trimmed\n}\n\nconst sanitizeUserAgent = (value: string | undefined): string | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\treturn value.length > USER_AGENT_MAX_LENGTH ? value.slice(0, USER_AGENT_MAX_LENGTH) : value\n}\n\nconst sanitizeIp = (value: string | undefined): string | undefined => {\n\tif (!value) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tipaddr.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n\treturn value\n}\n\nexport class Authenticator {\n\tprivate createAuthError = (message: string) => new HttpErrorResponse(401, `Authorization failure: ${message}`)\n\n\tconstructor(\n\t\tprivate readonly tenantDatabase: DatabaseContext,\n\t\tprivate readonly tenantReadDatabase: DatabaseContext,\n\t\tprivate readonly apiKeyManager: ApiKeyManager,\n\t\t/** A03: configured trusted geo-country header name (lower-cased), or undefined when the feature is off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {\n\t}\n\n\tpublic async authenticate(\n\t\t{ request, timer, clientIp, fallbackIdentity }: {\n\t\t\trequest: IncomingMessage\n\t\t\ttimer: Timer\n\t\t\tclientIp?: string\n\t\t\t/**\n\t\t\t * Identity to act as when the request carries no Authorization header. Lets a first-party UI\n\t\t\t * served by this process reach a pre-sign-in surface without a token existing anywhere to be\n\t\t\t * leaked or misconfigured — the roles come from the caller, not from the database. An actual\n\t\t\t * Authorization header always wins, so this can never widen a credentialed request.\n\t\t\t */\n\t\t\tfallbackIdentity?: VerifyResult\n\t\t},\n\t): Promise<AuthResult | null> {\n\t\tconst authHeader = request.headers.authorization || undefined\n\t\tconst socketIp = sanitizeIp(clientIp)\n\t\tconst socketUserAgent = sanitizeUserAgent(readHeader(request, 'user-agent'))\n\t\tconst forwardedIp = sanitizeIp(readHeader(request, forwardedClientIpHeader))\n\t\tconst forwardedUserAgent = sanitizeUserAgent(readHeader(request, forwardedClientUserAgentHeader))\n\t\t// Header lookup is case-insensitive: Node lower-cases all incoming header\n\t\t// names, so the configured name is lower-cased to match.\n\t\tconst forwardedGeoCountry = this.geoCountryHeader !== undefined\n\t\t\t? sanitizeGeoCountry(readHeader(request, this.geoCountryHeader.toLowerCase()))\n\t\t\t: undefined\n\t\tconst socketInfo = { ip: socketIp, userAgent: socketUserAgent }\n\t\tconst forwardedInfo = (forwardedIp !== undefined || forwardedUserAgent !== undefined)\n\t\t\t? { ip: forwardedIp, userAgent: forwardedUserAgent }\n\t\t\t: undefined\n\t\tconst verified = authHeader !== undefined\n\t\t\t? await this.verifyAuthorizationHeader(authHeader, timer, socketInfo, forwardedInfo)\n\t\t\t: fallbackIdentity\n\t\tif (verified === undefined) {\n\t\t\treturn null\n\t\t}\n\t\tconst assumedIdentityId = request.headers[assumeIdentityHeader] ?? undefined\n\t\tif (Array.isArray(assumedIdentityId)) {\n\t\t\tthrow new HttpErrorResponse(400, `Invalid ${assumedIdentityId} header format`)\n\t\t}\n\t\tconst trustForwarded = verified.trustForwardedInfo && forwardedInfo !== undefined\n\t\t// A03: the geo country is only ever exposed under the exact same gate as the\n\t\t// forwarded IP/UA — a trusted key that actually forwarded client info. This\n\t\t// keeps the signals consistent: we never score a real client country against\n\t\t// the proxy's own socket IP (which is what `clientIp` falls back to when no\n\t\t// forwarded info was sent). An untrusted key, or one that forwarded nothing,\n\t\t// yields no country.\n\t\tconst trustGeo = trustForwarded && forwardedGeoCountry !== undefined\n\t\treturn {\n\t\t\t...verified,\n\t\t\tassumedIdentityId,\n\t\t\tclientIp: trustForwarded ? (forwardedInfo?.ip ?? socketIp) : socketIp,\n\t\t\tclientUserAgent: trustForwarded ? (forwardedInfo?.userAgent ?? socketUserAgent) : socketUserAgent,\n\t\t\tforwarderIp: trustForwarded ? socketIp : undefined,\n\t\t\tforwarderUserAgent: trustForwarded ? socketUserAgent : undefined,\n\t\t\tgeoCountry: trustGeo ? forwardedGeoCountry : undefined,\n\t\t}\n\t}\n\n\tprivate async verifyAuthorizationHeader(\n\t\tauthHeader: string,\n\t\ttimer: Timer,\n\t\tsocketInfo: { ip?: string; userAgent?: string },\n\t\tforwardedInfo: { ip?: string; userAgent?: string } | undefined,\n\t): Promise<VerifyResult> {\n\t\tconst match = authHeader.match(/^Bearer\\s+(\\w+)$/i)\n\t\tif (match === null) {\n\t\t\tthrow this.createAuthError(`invalid Authorization header format`)\n\t\t}\n\t\tconst [, token] = match\n\t\tconst authResult = await timer(\n\t\t\t'Auth',\n\t\t\t() => this.apiKeyManager.verifyAndProlong(this.tenantDatabase, this.tenantReadDatabase, token, socketInfo, forwardedInfo),\n\t\t)\n\t\tif (!authResult.ok) {\n\t\t\tthrow this.createAuthError(authResult.errorMessage)\n\t\t}\n\t\treturn authResult.result\n\t}\n}\n"],"names":[],"mappings":";;;;;AAkBA,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,iCAAiC;AAEvC,MAAM,wBAAwB;AAI9B,MAAM,yBAAyB;AAE/B,MAAM,aAAa,CAAC,SAA0B,SAAqC;AAClF,QAAM,QAAQ,QAAQ,QAAQ,IAAI;AAClC,MAAI,MAAM,QAAQ,KAAK,GAAG;AACzB,WAAO,MAAM,CAAC;AAAA,EACf;AACA,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC5C;AAEA,MAAM,qBAAqB,CAAC,UAAkD;AAC7E,MAAI,UAAU,QAAW;AACxB,WAAO;AAAA,EACR;AACA,QAAM,UAAU,MAAM,KAAA;AACtB,MAAI,QAAQ,WAAW,GAAG;AACzB,WAAO;AAAA,EACR;AACA,SAAO,QAAQ,SAAS,yBAAyB,QAAQ,MAAM,GAAG,sBAAsB,IAAI;AAC7F;AAEA,MAAM,oBAAoB,CAAC,UAAkD;AAC5E,MAAI,UAAU,QAAW;AACxB,WAAO;AAAA,EACR;AACA,SAAO,MAAM,SAAS,wBAAwB,MAAM,MAAM,GAAG,qBAAqB,IAAI;AACvF;AAEA,MAAM,aAAa,CAAC,UAAkD;AACrE,MAAI,CAAC,OAAO;AACX,W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AAwB;AAC3D,WAAO;AAAA,MACN,GAAG;AAAA,MACH;AAAA,MACA,UAAU,iBAAkB,eAAe,MAAM,WAAY;AAAA,MAC7D,iBAAiB,iBAAkB,eAAe,aAAa,kBAAmB;AAAA,MAClF,aAAa,iBAAiB,WAAW;AAAA,MACzC,oBAAoB,iBAAiB,kBAAkB;AAAA,MACvD,YAAY,WAAW,sBAAsB;AAAA,IAAA;AAAA,EAE/C;AAAA,EAEA,MAAc,0BACb,YACA,OACA,YACA,eACwB;AACxB,UAAM,QAAQ,WAAW,MAAM,mBAAmB;AAClD,QAAI,UAAU,MAAM;AACnB,YAAM,KAAK,gBAAgB,qCAAqC;AAAA,IACjE;AACA,UAAM,CAAA,EAAG,KAAK,IAAI;AAClB,UAAM,aAAa,MAAM;AAAA,MACxB;AAAA,MACA,MAAM,KAAK,cAAc,iBAAiB,KAAK,gBAAgB,KAAK,oBAAoB,OAAO,YAAY,aAAa;AAAA,IAAA;AAEzH,QAAI,CAAC,WAAW,IAAI;AACnB,YAAM,KAAK,gBAAgB,WAAW,YAAY;AAAA,IACnD;AACA,WAAO,WAAW;AAAA,EACnB;AACD;"}
|
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
class HttpResponse {
|
|
4
|
-
constructor(code, body, contentType) {
|
|
4
|
+
constructor(code, body, contentType, headers) {
|
|
5
5
|
this.code = code;
|
|
6
6
|
this.body = body;
|
|
7
7
|
this.contentType = contentType;
|
|
8
|
+
this.headers = headers;
|
|
8
9
|
}
|
|
9
10
|
}
|
|
10
11
|
class HttpErrorResponse extends HttpResponse {
|
|
11
|
-
constructor(code, message) {
|
|
12
|
+
constructor(code, message, headers) {
|
|
12
13
|
super(
|
|
13
14
|
code,
|
|
14
15
|
message ? JSON.stringify({ errors: [{ code, message }] }) : void 0,
|
|
15
|
-
"application/json"
|
|
16
|
+
"application/json",
|
|
17
|
+
headers
|
|
16
18
|
);
|
|
17
19
|
this.message = message;
|
|
18
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpResponse.cjs","sources":["../../../../../packages/engine-http/src/common/HttpResponse.ts"],"sourcesContent":["export class HttpResponse {\n\tconstructor(\n\t\tpublic readonly code: number,\n\t\tpublic readonly body?: string,\n\t\tpublic readonly contentType?: string,\n\t) {\n\t}\n}\n\nexport class HttpErrorResponse extends HttpResponse {\n\tconstructor(\n\t\tcode: number,\n\t\tpublic readonly message?: string,\n\t) {\n\t\tsuper(\n\t\t\tcode,\n\t\t\tmessage ? JSON.stringify({ errors: [{ code, message }] }) : undefined,\n\t\t\t'application/json',\n\t\t)\n\t}\n}\n"],"names":[],"mappings":";;AAAO,MAAM,aAAa;AAAA,EACzB,YACiB,MACA,MACA,
|
|
1
|
+
{"version":3,"file":"HttpResponse.cjs","sources":["../../../../../packages/engine-http/src/common/HttpResponse.ts"],"sourcesContent":["export class HttpResponse {\n\tconstructor(\n\t\tpublic readonly code: number,\n\t\tpublic readonly body?: string,\n\t\tpublic readonly contentType?: string,\n\t\t/** Extra response headers. Use for signals a client must act on, since an error body is not always readable. */\n\t\tpublic readonly headers?: Readonly<Record<string, string>>,\n\t) {\n\t}\n}\n\nexport class HttpErrorResponse extends HttpResponse {\n\tconstructor(\n\t\tcode: number,\n\t\tpublic readonly message?: string,\n\t\theaders?: Readonly<Record<string, string>>,\n\t) {\n\t\tsuper(\n\t\t\tcode,\n\t\t\tmessage ? JSON.stringify({ errors: [{ code, message }] }) : undefined,\n\t\t\t'application/json',\n\t\t\theaders,\n\t\t)\n\t}\n}\n"],"names":[],"mappings":";;AAAO,MAAM,aAAa;AAAA,EACzB,YACiB,MACA,MACA,aAEA,SACf;AALe,SAAA,OAAA;AACA,SAAA,OAAA;AACA,SAAA,cAAA;AAEA,SAAA,UAAA;AAAA,EAEjB;AACD;AAEO,MAAM,0BAA0B,aAAa;AAAA,EACnD,YACC,MACgB,SAChB,SACC;AACD;AAAA,MACC;AAAA,MACA,UAAU,KAAK,UAAU,EAAE,QAAQ,CAAC,EAAE,MAAM,QAAA,CAAS,EAAA,CAAG,IAAI;AAAA,MAC5D;AAAA,MACA;AAAA,IAAA;AAPe,SAAA,UAAA;AAAA,EASjB;AACD;;;"}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
class HttpResponse {
|
|
2
|
-
constructor(code, body, contentType) {
|
|
2
|
+
constructor(code, body, contentType, headers) {
|
|
3
3
|
this.code = code;
|
|
4
4
|
this.body = body;
|
|
5
5
|
this.contentType = contentType;
|
|
6
|
+
this.headers = headers;
|
|
6
7
|
}
|
|
7
8
|
}
|
|
8
9
|
class HttpErrorResponse extends HttpResponse {
|
|
9
|
-
constructor(code, message) {
|
|
10
|
+
constructor(code, message, headers) {
|
|
10
11
|
super(
|
|
11
12
|
code,
|
|
12
13
|
message ? JSON.stringify({ errors: [{ code, message }] }) : void 0,
|
|
13
|
-
"application/json"
|
|
14
|
+
"application/json",
|
|
15
|
+
headers
|
|
14
16
|
);
|
|
15
17
|
this.message = message;
|
|
16
18
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpResponse.js","sources":["../../../../../packages/engine-http/src/common/HttpResponse.ts"],"sourcesContent":["export class HttpResponse {\n\tconstructor(\n\t\tpublic readonly code: number,\n\t\tpublic readonly body?: string,\n\t\tpublic readonly contentType?: string,\n\t) {\n\t}\n}\n\nexport class HttpErrorResponse extends HttpResponse {\n\tconstructor(\n\t\tcode: number,\n\t\tpublic readonly message?: string,\n\t) {\n\t\tsuper(\n\t\t\tcode,\n\t\t\tmessage ? JSON.stringify({ errors: [{ code, message }] }) : undefined,\n\t\t\t'application/json',\n\t\t)\n\t}\n}\n"],"names":[],"mappings":"AAAO,MAAM,aAAa;AAAA,EACzB,YACiB,MACA,MACA,
|
|
1
|
+
{"version":3,"file":"HttpResponse.js","sources":["../../../../../packages/engine-http/src/common/HttpResponse.ts"],"sourcesContent":["export class HttpResponse {\n\tconstructor(\n\t\tpublic readonly code: number,\n\t\tpublic readonly body?: string,\n\t\tpublic readonly contentType?: string,\n\t\t/** Extra response headers. Use for signals a client must act on, since an error body is not always readable. */\n\t\tpublic readonly headers?: Readonly<Record<string, string>>,\n\t) {\n\t}\n}\n\nexport class HttpErrorResponse extends HttpResponse {\n\tconstructor(\n\t\tcode: number,\n\t\tpublic readonly message?: string,\n\t\theaders?: Readonly<Record<string, string>>,\n\t) {\n\t\tsuper(\n\t\t\tcode,\n\t\t\tmessage ? JSON.stringify({ errors: [{ code, message }] }) : undefined,\n\t\t\t'application/json',\n\t\t\theaders,\n\t\t)\n\t}\n}\n"],"names":[],"mappings":"AAAO,MAAM,aAAa;AAAA,EACzB,YACiB,MACA,MACA,aAEA,SACf;AALe,SAAA,OAAA;AACA,SAAA,OAAA;AACA,SAAA,cAAA;AAEA,SAAA,UAAA;AAAA,EAEjB;AACD;AAEO,MAAM,0BAA0B,aAAa;AAAA,EACnD,YACC,MACgB,SAChB,SACC;AACD;AAAA,MACC;AAAA,MACA,UAAU,KAAK,UAAU,EAAE,QAAQ,CAAC,EAAE,MAAM,QAAA,CAAS,EAAA,CAAG,IAAI;AAAA,MAC5D;AAAA,MACA;AAAA,IAAA;AAPe,SAAA,UAAA;AAAA,EASjB;AACD;"}
|
|
@@ -27,7 +27,8 @@ async function readConfig(configSources = [], configProcessors = [], serverConfi
|
|
|
27
27
|
return {
|
|
28
28
|
serverConfig,
|
|
29
29
|
projectConfigResolver: projectConfigResolver.createProjectConfigResolver(env, rawConfig, configProcessors),
|
|
30
|
-
tenantConfigResolver: tenantConfigResolver.createTenantConfigResolver(env, rawConfig.tenant)
|
|
30
|
+
tenantConfigResolver: tenantConfigResolver.createTenantConfigResolver(env, rawConfig.tenant),
|
|
31
|
+
env
|
|
31
32
|
};
|
|
32
33
|
}
|
|
33
34
|
exports.readConfig = readConfig;
|