@contember/engine-http 2.2.0-alpha.17 → 2.2.0-alpha.19
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/dist/development/index.cjs +3 -1
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +4 -2
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/MasterContainer.cjs +5 -4
- package/dist/development/src/MasterContainer.cjs.map +1 -1
- package/dist/development/src/MasterContainer.js +5 -4
- package/dist/development/src/MasterContainer.js.map +1 -1
- package/dist/development/src/application/PanelApiMount.cjs.map +1 -1
- package/dist/development/src/application/PanelApiMount.js.map +1 -1
- package/dist/development/src/application/application.cjs +27 -21
- package/dist/development/src/application/application.cjs.map +1 -1
- package/dist/development/src/application/application.js +27 -21
- package/dist/development/src/application/application.js.map +1 -1
- package/dist/development/src/application/compression.cjs +99 -0
- package/dist/development/src/application/compression.cjs.map +1 -0
- package/dist/development/src/application/compression.js +82 -0
- package/dist/development/src/application/compression.js.map +1 -0
- package/dist/development/src/application/cors.cjs +52 -0
- package/dist/development/src/application/cors.cjs.map +1 -0
- package/dist/development/src/application/cors.js +52 -0
- package/dist/development/src/application/cors.js.map +1 -0
- package/dist/development/src/application/requestBody.cjs +242 -0
- package/dist/development/src/application/requestBody.cjs.map +1 -0
- package/dist/development/src/application/requestBody.js +242 -0
- package/dist/development/src/application/requestBody.js.map +1 -0
- package/dist/development/src/application/requestBodyMasking.cjs +97 -0
- package/dist/development/src/application/requestBodyMasking.cjs.map +1 -0
- package/dist/development/src/application/requestBodyMasking.js +97 -0
- package/dist/development/src/application/requestBodyMasking.js.map +1 -0
- package/dist/development/src/config/configSchema.cjs +36 -1
- package/dist/development/src/config/configSchema.cjs.map +1 -1
- package/dist/development/src/config/configSchema.js +36 -1
- package/dist/development/src/config/configSchema.js.map +1 -1
- package/dist/development/src/config/configTemplate.cjs +5 -0
- package/dist/development/src/config/configTemplate.cjs.map +1 -1
- package/dist/development/src/config/configTemplate.js +5 -0
- package/dist/development/src/config/configTemplate.js.map +1 -1
- package/dist/development/src/content/ProjectMembershipResolver.cjs +10 -3
- package/dist/development/src/content/ProjectMembershipResolver.cjs.map +1 -1
- package/dist/development/src/content/ProjectMembershipResolver.js +10 -3
- package/dist/development/src/content/ProjectMembershipResolver.js.map +1 -1
- package/dist/development/src/graphql/execution.cjs +3 -9
- package/dist/development/src/graphql/execution.cjs.map +1 -1
- package/dist/development/src/graphql/execution.js +3 -9
- package/dist/development/src/graphql/execution.js.map +1 -1
- package/dist/development/src/project/ProjectContainer.cjs +1 -1
- package/dist/development/src/project/ProjectContainer.js +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +3 -2
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.js +3 -2
- package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/development/src/providers.cjs +2 -2
- package/dist/development/src/providers.cjs.map +1 -1
- package/dist/development/src/providers.js +2 -2
- package/dist/development/src/providers.js.map +1 -1
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.cjs +33 -5
- package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.js +33 -5
- package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/development/src/utils/CryptoWrapper.cjs +11 -0
- package/dist/development/src/utils/CryptoWrapper.cjs.map +1 -1
- package/dist/development/src/utils/CryptoWrapper.js +11 -0
- package/dist/development/src/utils/CryptoWrapper.js.map +1 -1
- package/dist/development/src/utils/sentry.cjs +32 -49
- package/dist/development/src/utils/sentry.cjs.map +1 -1
- package/dist/development/src/utils/sentry.js +33 -33
- package/dist/development/src/utils/sentry.js.map +1 -1
- package/dist/development/src/utils/serverStartup.cjs +5 -3
- package/dist/development/src/utils/serverStartup.cjs.map +1 -1
- package/dist/development/src/utils/serverStartup.js +5 -3
- package/dist/development/src/utils/serverStartup.js.map +1 -1
- package/dist/production/index.cjs +3 -1
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +4 -2
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/MasterContainer.cjs +5 -4
- package/dist/production/src/MasterContainer.cjs.map +1 -1
- package/dist/production/src/MasterContainer.js +5 -4
- package/dist/production/src/MasterContainer.js.map +1 -1
- package/dist/production/src/application/PanelApiMount.cjs.map +1 -1
- package/dist/production/src/application/PanelApiMount.js.map +1 -1
- package/dist/production/src/application/application.cjs +27 -21
- package/dist/production/src/application/application.cjs.map +1 -1
- package/dist/production/src/application/application.js +27 -21
- package/dist/production/src/application/application.js.map +1 -1
- package/dist/production/src/application/compression.cjs +99 -0
- package/dist/production/src/application/compression.cjs.map +1 -0
- package/dist/production/src/application/compression.js +82 -0
- package/dist/production/src/application/compression.js.map +1 -0
- package/dist/production/src/application/cors.cjs +52 -0
- package/dist/production/src/application/cors.cjs.map +1 -0
- package/dist/production/src/application/cors.js +52 -0
- package/dist/production/src/application/cors.js.map +1 -0
- package/dist/production/src/application/requestBody.cjs +242 -0
- package/dist/production/src/application/requestBody.cjs.map +1 -0
- package/dist/production/src/application/requestBody.js +242 -0
- package/dist/production/src/application/requestBody.js.map +1 -0
- package/dist/production/src/application/requestBodyMasking.cjs +97 -0
- package/dist/production/src/application/requestBodyMasking.cjs.map +1 -0
- package/dist/production/src/application/requestBodyMasking.js +97 -0
- package/dist/production/src/application/requestBodyMasking.js.map +1 -0
- package/dist/production/src/config/configSchema.cjs +36 -1
- package/dist/production/src/config/configSchema.cjs.map +1 -1
- package/dist/production/src/config/configSchema.js +36 -1
- package/dist/production/src/config/configSchema.js.map +1 -1
- package/dist/production/src/config/configTemplate.cjs +5 -0
- package/dist/production/src/config/configTemplate.cjs.map +1 -1
- package/dist/production/src/config/configTemplate.js +5 -0
- package/dist/production/src/config/configTemplate.js.map +1 -1
- package/dist/production/src/content/ProjectMembershipResolver.cjs +10 -3
- package/dist/production/src/content/ProjectMembershipResolver.cjs.map +1 -1
- package/dist/production/src/content/ProjectMembershipResolver.js +10 -3
- package/dist/production/src/content/ProjectMembershipResolver.js.map +1 -1
- package/dist/production/src/graphql/execution.cjs +3 -9
- package/dist/production/src/graphql/execution.cjs.map +1 -1
- package/dist/production/src/graphql/execution.js +3 -9
- package/dist/production/src/graphql/execution.js.map +1 -1
- package/dist/production/src/project/ProjectContainer.cjs +1 -1
- package/dist/production/src/project/ProjectContainer.js +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +3 -2
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.js +3 -2
- package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/production/src/providers.cjs +2 -2
- package/dist/production/src/providers.cjs.map +1 -1
- package/dist/production/src/providers.js +2 -2
- package/dist/production/src/providers.js.map +1 -1
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.cjs +33 -5
- package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.js +33 -5
- package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/production/src/utils/CryptoWrapper.cjs +11 -0
- package/dist/production/src/utils/CryptoWrapper.cjs.map +1 -1
- package/dist/production/src/utils/CryptoWrapper.js +11 -0
- package/dist/production/src/utils/CryptoWrapper.js.map +1 -1
- package/dist/production/src/utils/sentry.cjs +32 -49
- package/dist/production/src/utils/sentry.cjs.map +1 -1
- package/dist/production/src/utils/sentry.js +33 -33
- package/dist/production/src/utils/sentry.js.map +1 -1
- package/dist/production/src/utils/serverStartup.cjs +5 -3
- package/dist/production/src/utils/serverStartup.cjs.map +1 -1
- package/dist/production/src/utils/serverStartup.js +5 -3
- package/dist/production/src/utils/serverStartup.js.map +1 -1
- package/dist/tests/cases/unit/compression.test.d.ts +2 -0
- package/dist/tests/cases/unit/compression.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/cors.test.d.ts +2 -0
- package/dist/tests/cases/unit/cors.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/requestBody.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestBody.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/requestBodyLogging.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestBodyLogging.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/requestBodyMasking.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestBodyMasking.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +8 -1
- package/dist/types/MasterContainer.d.ts.map +1 -1
- package/dist/types/application/PanelApiMount.d.ts +2 -0
- package/dist/types/application/PanelApiMount.d.ts.map +1 -1
- package/dist/types/application/application.d.ts +7 -1
- package/dist/types/application/application.d.ts.map +1 -1
- package/dist/types/application/compression.d.ts +19 -0
- package/dist/types/application/compression.d.ts.map +1 -0
- package/dist/types/application/cors.d.ts +10 -0
- package/dist/types/application/cors.d.ts.map +1 -0
- package/dist/types/application/index.d.ts +1 -0
- package/dist/types/application/index.d.ts.map +1 -1
- package/dist/types/application/requestBody.d.ts +45 -0
- package/dist/types/application/requestBody.d.ts.map +1 -0
- package/dist/types/application/requestBodyMasking.d.ts +10 -0
- package/dist/types/application/requestBodyMasking.d.ts.map +1 -0
- package/dist/types/config/configSchema.d.ts +13 -3
- package/dist/types/config/configSchema.d.ts.map +1 -1
- package/dist/types/config/configTemplate.d.ts.map +1 -1
- package/dist/types/content/ProjectMembershipResolver.d.ts.map +1 -1
- package/dist/types/graphql/execution.d.ts.map +1 -1
- package/dist/types/projectGroup/ProjectGroupContainer.d.ts.map +1 -1
- package/dist/types/transfer/ImportExecutor.d.ts +2 -0
- package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/CryptoWrapper.d.ts +5 -0
- package/dist/types/utils/CryptoWrapper.d.ts.map +1 -1
- package/dist/types/utils/sentry.d.ts +13 -6
- package/dist/types/utils/sentry.d.ts.map +1 -1
- package/dist/types/utils/serverStartup.d.ts.map +1 -1
- package/package.json +18 -24
- package/src/MasterContainer.ts +5 -3
- package/src/application/PanelApiMount.ts +2 -0
- package/src/application/application.ts +38 -20
- package/src/application/compression.ts +118 -0
- package/src/application/cors.ts +61 -0
- package/src/application/index.ts +1 -0
- package/src/application/requestBody.ts +295 -0
- package/src/application/requestBodyMasking.ts +117 -0
- package/src/config/configSchema.ts +38 -1
- package/src/config/configTemplate.ts +5 -0
- package/src/content/ProjectMembershipResolver.ts +13 -5
- package/src/graphql/execution.ts +3 -9
- package/src/projectGroup/ProjectGroupContainer.ts +1 -0
- package/src/providers.ts +2 -2
- package/src/transfer/ImportExecutor.ts +37 -5
- package/src/tsconfig.json +3 -1
- package/src/utils/CryptoWrapper.ts +12 -0
- package/src/utils/sentry.ts +42 -39
- package/src/utils/serverStartup.ts +7 -5
- package/tests/cases/unit/compression.test.ts +172 -0
- package/tests/cases/unit/cors.test.ts +106 -0
- package/tests/cases/unit/crypto.test.ts +16 -0
- package/tests/cases/unit/projectMembershipResolver.test.ts +50 -0
- package/tests/cases/unit/requestBody.test.ts +333 -0
- package/tests/cases/unit/requestBodyLogging.test.ts +89 -0
- package/tests/cases/unit/requestBodyMasking.test.ts +102 -0
- package/tests/cases/unit/sentryLoggerHandler.test.ts +74 -20
- package/tests/cases/unit/serverConfig.test.ts +42 -0
- package/dist/tests/cases/unit/sentryIntegrations.test.d.ts +0 -2
- package/dist/tests/cases/unit/sentryIntegrations.test.d.ts.map +0 -1
- package/tests/cases/unit/sentryIntegrations.test.ts +0 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.cjs","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationDefinitionNode,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from 'lru-cache'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\ninterface FactoryArgs<Context> {\n\tschema: GraphQLSchema\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\tschema,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>({\n\t\tmax: hitCacheMax,\n\t\tttl: hitCacheMaxAgeSeconds * 1000,\n\t})\n\tconst documentCache = new LRUCache<string, DocumentNode>({\n\t\tmax: documentCacheMax,\n\t\tttl: documentCacheMaxAgeSeconds * 1000,\n\t})\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = validateSchema(schema)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = validate(schema, doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await execute({\n\t\t\t\tschema,\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["LRUCache","validateSchema","createHash","parse","validate","execute","response","GraphQLError","ForbiddenError","logger","RequestMemoryBudgetExceededError","UserError","Kind"],"mappings":";;;;;;;;;AA8CA,MAAM,wBAAwB;AAE9B,MAAM,wBAAwB,KAAK;AACnC,MAAM,6BAA6B,wBAAwB;AAC3D,MAAM,uBAAuB,6BAA6B;AAC1D,MAAM,mBAAmB;AACzB,MAAM,cAAc,mBAAmB;AAEhC,MAAM,4BAA4B,CAAU;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AACD,MAA0D;AACzD,MAAI,kBAAkB;AACtB,QAAM,WAAW,IAAIA,kBAAuB;AAAA,IAC3C,KAAK;AAAA,IACL,KAAK,wBAAwB;AAAA,EAAA,CAC7B;AACD,QAAM,gBAAgB,IAAIA,kBAA+B;AAAA,IACxD,KAAK;AAAA,IACL,KAAK,6BAA6B;AAAA,EAAA,CAClC;AACD,MAAI,YAAY,KAAK,IAAA;AAErB,SAAO,OAAO,EAAE,SAAS,UAAU,oBAAoB;AACtD,UAAM,MAAM,KAAK,IAAA;AACjB,QAAK,MAAM,YAAa,uBAAuB,KAAM;AACpD,oBAAc,WAAA;AACd,kBAAY;AAAA,IACb;AACA,UAAM,iBAAiB,CAAC,GAAG,SAAS;AAEpC,mBAAe,QAAQ,CAAA,OAAM;AAC5B,SAAG,WAAW,eAAe,KAAK,GAAG,QAAQ,CAAA,CAAE,KAAK,EAAE;AAAA,IACvD,CAAC;AAED,UAAM,UAAU,CAAC,MAAc,SAAc;AAC5C,eAAS,SAAS;AAClB,eAAS,OAAO,KAAK,UAAU,IAAI;AACnC,eAAS,IAAI,gBAAgB,kBAAkB;AAE/C,qBAAe,QAAQ,CAAA,OAAM;AAC5B,WAAG,cAAc,eAAe,KAAK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vE,eAAO,WAAW;AAAA,MACnB;AAAA,IACD;AAAA,EACD;AACA,QAAM,IAAIL,QAAAA,aAAa,4BAA4B;AACpD;;;"}
|
|
1
|
+
{"version":3,"file":"execution.cjs","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationDefinitionNode,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from '@contember/utilities'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\ninterface FactoryArgs<Context> {\n\tschema: GraphQLSchema\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\tschema,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })\n\tconst documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = validateSchema(schema)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = validate(schema, doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await execute({\n\t\t\t\tschema,\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["LRUCache","validateSchema","createHash","parse","validate","execute","response","GraphQLError","ForbiddenError","logger","RequestMemoryBudgetExceededError","UserError","Kind"],"mappings":";;;;;;;;;AA8CA,MAAM,wBAAwB;AAE9B,MAAM,wBAAwB,KAAK;AACnC,MAAM,6BAA6B,wBAAwB;AAC3D,MAAM,uBAAuB,6BAA6B;AAC1D,MAAM,mBAAmB;AACzB,MAAM,cAAc,mBAAmB;AAEhC,MAAM,4BAA4B,CAAU;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AACD,MAA0D;AACzD,MAAI,kBAAkB;AACtB,QAAM,WAAW,IAAIA,mBAAuB,aAAa,EAAE,KAAK,wBAAwB,KAAM;AAC9F,QAAM,gBAAgB,IAAIA,mBAA+B,kBAAkB,EAAE,KAAK,6BAA6B,KAAM;AACrH,MAAI,YAAY,KAAK,IAAA;AAErB,SAAO,OAAO,EAAE,SAAS,UAAU,oBAAoB;AACtD,UAAM,MAAM,KAAK,IAAA;AACjB,QAAK,MAAM,YAAa,uBAAuB,KAAM;AACpD,oBAAc,WAAA;AACd,kBAAY;AAAA,IACb;AACA,UAAM,iBAAiB,CAAC,GAAG,SAAS;AAEpC,mBAAe,QAAQ,CAAA,OAAM;AAC5B,SAAG,WAAW,eAAe,KAAK,GAAG,QAAQ,CAAA,CAAE,KAAK,EAAE;AAAA,IACvD,CAAC;AAED,UAAM,UAAU,CAAC,MAAc,SAAc;AAC5C,eAAS,SAAS;AAClB,eAAS,OAAO,KAAK,UAAU,IAAI;AACnC,eAAS,IAAI,gBAAgB,kBAAkB;AAE/C,qBAAe,QAAQ,CAAA,OAAM;AAC5B,WAAG,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M,UAAU,eAAe;AACvE,eAAO,WAAW;AAAA,MACnB;AAAA,IACD;AAAA,EACD;AACA,QAAM,IAAIL,QAAAA,aAAa,4BAA4B;AACpD;;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { validateSchema, parse, validate, execute, GraphQLError, Kind } from "graphql";
|
|
2
|
-
import { LRUCache } from "
|
|
2
|
+
import { LRUCache } from "@contember/utilities";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { logger } from "@contember/logger";
|
|
5
5
|
import { ForbiddenError } from "@contember/graphql-utils";
|
|
@@ -17,14 +17,8 @@ const createGraphQLQueryHandler = ({
|
|
|
17
17
|
getMemoryBudget
|
|
18
18
|
}) => {
|
|
19
19
|
let schemaValidated = false;
|
|
20
|
-
const hitCache = new LRUCache({
|
|
21
|
-
|
|
22
|
-
ttl: hitCacheMaxAgeSeconds * 1e3
|
|
23
|
-
});
|
|
24
|
-
const documentCache = new LRUCache({
|
|
25
|
-
max: documentCacheMax,
|
|
26
|
-
ttl: documentCacheMaxAgeSeconds * 1e3
|
|
27
|
-
});
|
|
20
|
+
const hitCache = new LRUCache(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1e3 });
|
|
21
|
+
const documentCache = new LRUCache(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1e3 });
|
|
28
22
|
let lastPrune = Date.now();
|
|
29
23
|
return async ({ request, response, createContext }) => {
|
|
30
24
|
const now = Date.now();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationDefinitionNode,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from 'lru-cache'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\ninterface FactoryArgs<Context> {\n\tschema: GraphQLSchema\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\tschema,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>({\n\t\tmax: hitCacheMax,\n\t\tttl: hitCacheMaxAgeSeconds * 1000,\n\t})\n\tconst documentCache = new LRUCache<string, DocumentNode>({\n\t\tmax: documentCacheMax,\n\t\tttl: documentCacheMaxAgeSeconds * 1000,\n\t})\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = validateSchema(schema)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = validate(schema, doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await execute({\n\t\t\t\tschema,\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["response"],"mappings":";;;;;;;AA8CA,MAAM,wBAAwB;AAE9B,MAAM,wBAAwB,KAAK;AACnC,MAAM,6BAA6B,wBAAwB;AAC3D,MAAM,uBAAuB,6BAA6B;AAC1D,MAAM,m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AyB,gBAAgB;AACnD,mBAAa,KAAK,KAAK;AACvB,eAAS;AAAA,IACV,WAAW,yBAAyB,kCAAkC;AACrE,mBAAa,KAAK,EAAE,SAAS,MAAM,SAAS,WAAW,MAAM,WAAW,MAAM,MAAM,MAAM,YAAY,EAAE,MAAM,sBAAA,GAAyB;AACvI,iCAA2B;AAAA,IAC5B,WAAW,yBAAyB,WAAW;AAC9C,mBAAa,KAAK,EAAE,SAAS,MAAM,SAAS,WAAW,MAAM,WAAW,MAAM,MAAM,KAAA,CAAM;AAC1F,eAAS;AAAA,IACV,OAAO;AACN,aAAO,MAAM,iBAAiB,KAAK;AACnC,mBAAa,KAAK,EAAE,SAAS,yBAAyB,WAAW,QAAW,MAAM,QAAW;AAC7F,eAAS;AAAA,IACV;AAAA,EACD;AACA,SAAO,CAAC,SAAS,MAAM,2BAA2B,MAAM,SAAS,MAAM,SAAS,MAAM,MAAM,YAAY;AACzG;AAEA,MAAM,uBAAuB,CAAC,UAAwB,kBAAoD;AACzG,aAAW,cAAc,SAAS,aAAa;AAC9C,QAAI,WAAW,SAAS,KAAK,sBAAsB;AAClD,UAAI,kBAAkB,QAAQ,WAAW,MAAM,UAAU,eAAe;AACvE,eAAO,WAAW;AAAA,MACnB;AAAA,IACD;AAAA,EACD;AACA,QAAM,IAAI,aAAa,4BAA4B;AACpD;"}
|
|
1
|
+
{"version":3,"file":"execution.js","sources":["../../../../../packages/engine-http/src/graphql/execution.ts"],"sourcesContent":["import {\n\tDocumentNode,\n\texecute,\n\tGraphQLError,\n\tGraphQLSchema,\n\tKind,\n\tOperationDefinitionNode,\n\tOperationTypeNode,\n\tparse,\n\tvalidate,\n\tvalidateSchema,\n} from 'graphql'\nimport { LRUCache } from '@contember/utilities'\nimport { createHash } from 'node:crypto'\nimport { Request, Response } from 'koa'\nimport { logger } from '@contember/logger'\nimport { ForbiddenError } from '@contember/graphql-utils'\nimport { UserError } from '@contember/engine-content-api'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from '@contember/database'\n\nexport interface GraphQLListener<Context> {\n\tonStart?: (ctx: {}) => Omit<GraphQLListener<Context>, 'onStart'> | void\n\tonExecute?: (ctx: {\n\t\tcontext: Context\n\t\tdocument: DocumentNode\n\t\toperation: OperationTypeNode\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute'> | void\n\tonResponse?: (ctx: {\n\t\tresponse: any\n\t\tcontext: Context\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse'> | void\n\tonShutdown?: (ctx: {\n\t\tresponse: any\n\t}) => Omit<GraphQLListener<Context>, 'onStart' | 'onExecute' | 'onResponse' | 'onShutdown'> | void\n}\n\ninterface FactoryArgs<Context> {\n\tschema: GraphQLSchema\n\tlisteners: GraphQLListener<Context>[]\n\tgetMemoryBudget?: (context: Context) => RequestMemoryBudget | undefined\n}\n\nexport type GraphQLQueryHandler<Context> = (\n\targs: { request: Request; response: Response; createContext: ({}: { operation: OperationTypeNode; queryHash: string }) => Context },\n) => any\n\nconst memoryBudgetErrorCode = 'RESOURCE_EXHAUSTED'\n\nconst hitCacheMaxAgeSeconds = 10 * 60\nconst documentCacheMaxAgeSeconds = hitCacheMaxAgeSeconds * 10\nconst pruneIntervalSeconds = documentCacheMaxAgeSeconds / 2\nconst documentCacheMax = 100\nconst hitCacheMax = documentCacheMax * 2\n\nexport const createGraphQLQueryHandler = <Context>({\n\tschema,\n\tlisteners,\n\tgetMemoryBudget,\n}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {\n\tlet schemaValidated = false\n\tconst hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })\n\tconst documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })\n\tlet lastPrune = Date.now()\n\n\treturn async ({ request, response, createContext }) => {\n\t\tconst now = Date.now()\n\t\tif ((now - lastPrune) > pruneIntervalSeconds * 1000) {\n\t\t\tdocumentCache.purgeStale()\n\t\t\tlastPrune = now\n\t\t}\n\t\tconst listenersQueue = [...listeners]\n\n\t\tlistenersQueue.forEach(it => {\n\t\t\tit.onStart && listenersQueue.push(it.onStart({}) || {})\n\t\t})\n\n\t\tconst respond = (code: number, data: any) => {\n\t\t\tresponse.status = code\n\t\t\tresponse.body = JSON.stringify(data)\n\t\t\tresponse.set('Content-type', 'application/json')\n\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onShutdown && listenersQueue.push(it.onShutdown({ response: data }) || {})\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tif (!schemaValidated) {\n\t\t\t\tconst validationResult = validateSchema(schema)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, {\n\t\t\t\t\t\terrors: validationResult,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tschemaValidated = true\n\t\t\t}\n\t\t\tconst resolvedRequest = request.method === 'POST' ? (request.body as any) : request.query\n\t\t\tif (!resolvedRequest.query) {\n\t\t\t\treturn respond(400, {\n\t\t\t\t\terrors: [{ message: 'Missing request query' }],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst queryHash = createHash('md5').update(resolvedRequest.query).digest('hex')\n\t\t\tlet doc = documentCache.get(queryHash)\n\t\t\tif (!doc) {\n\t\t\t\tdoc = parse(resolvedRequest.query)\n\t\t\t\tconst validationResult = validate(schema, doc)\n\t\t\t\tif (validationResult.length) {\n\t\t\t\t\treturn respond(400, { errors: validationResult })\n\t\t\t\t}\n\t\t\t\tif (hitCache.get(queryHash)) {\n\t\t\t\t\tdocumentCache.set(queryHash, doc)\n\t\t\t\t}\n\t\t\t\thitCache.set(queryHash, true)\n\t\t\t}\n\t\t\tconst document = doc\n\t\t\tconst operationName = resolvedRequest.operationName ?? null\n\t\t\tconst operation = resolveOperationType(document, operationName)\n\n\t\t\tconst context = createContext({ operation, queryHash })\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onExecute && listenersQueue.push(it.onExecute({ context, document, operation }) || {})\n\t\t\t})\n\t\t\tconst executionResult = await execute({\n\t\t\t\tschema,\n\t\t\t\tdocument,\n\t\t\t\toperationName: operationName,\n\t\t\t\tvariableValues: resolvedRequest.variables,\n\t\t\t\tcontextValue: context,\n\t\t\t})\n\t\t\t// GraphQL turns a budget failure inside a nullable resolver into partial data; reject the whole response instead.\n\t\t\t// A mutation reports it in its own result, because sibling mutations may already be committed.\n\t\t\tconst response = operation === 'query' && getMemoryBudget?.(context)?.exceeded\n\t\t\t\t? { data: null, errors: withMemoryBudgetError(executionResult.errors) }\n\t\t\t\t: executionResult\n\t\t\tlistenersQueue.forEach(it => {\n\t\t\t\tit.onResponse && listenersQueue.push(it.onResponse({ context, response }) || {})\n\t\t\t})\n\t\t\tif (response.errors && response.errors.length > 0) {\n\t\t\t\tconst [code, errors] = processErrors(response.errors)\n\t\t\t\trespond(code && !response.data ? code : 200, { ...response, errors })\n\t\t\t} else {\n\t\t\t\trespond(200, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQLError) {\n\t\t\t\treturn respond(e instanceof ForbiddenError ? 403 : 400, { errors: [e] })\n\t\t\t}\n\t\t\tlogger.error(e)\n\t\t\treturn respond(500, { errors: [{ message: 'Internal error' }] })\n\t\t}\n\t}\n}\n\nexport const extractOriginalError = (e: Error): Error => {\n\tif (e instanceof GraphQLError && e.originalError) {\n\t\treturn extractOriginalError(e.originalError)\n\t}\n\tif ('errors' in e && Array.isArray((e as any).errors) && (e as any).errors.length === 1) {\n\t\treturn extractOriginalError((e as any).errors[0])\n\t}\n\treturn e\n}\n\nconst withMemoryBudgetError = (errors: readonly GraphQLError[] = []): readonly GraphQLError[] => {\n\tif (errors.some(it => extractOriginalError(it) instanceof RequestMemoryBudgetExceededError)) {\n\t\treturn errors\n\t}\n\t// The resolver that hit the budget did not report it (its error was swallowed); the response still must not pass as valid.\n\tconst originalError = new RequestMemoryBudgetExceededError()\n\treturn [...errors, new GraphQLError(originalError.message, { originalError })]\n}\n\nconst processErrors = (errors: readonly any[]): [number | null, any[]] => {\n\tconst resultErrors = []\n\tlet has400 = false\n\tlet has403 = false\n\tlet has500 = false\n\tlet hasExhaustedMemoryBudget = false\n\tfor (const error of errors) {\n\t\tconst originalError = extractOriginalError(error)\n\t\tif (originalError instanceof GraphQLError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas400 = true\n\t\t} else if (originalError instanceof ForbiddenError) {\n\t\t\tresultErrors.push(error)\n\t\t\thas403 = true\n\t\t} else if (originalError instanceof RequestMemoryBudgetExceededError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path, extensions: { code: memoryBudgetErrorCode } })\n\t\t\thasExhaustedMemoryBudget = true\n\t\t} else if (originalError instanceof UserError) {\n\t\t\tresultErrors.push({ message: error.message, locations: error.locations, path: error.path })\n\t\t\thas400 = true\n\t\t} else {\n\t\t\tlogger.error(originalError || error)\n\t\t\tresultErrors.push({ message: 'Internal server error', locations: undefined, path: undefined })\n\t\t\thas500 = true\n\t\t}\n\t}\n\treturn [has500 ? 500 : hasExhaustedMemoryBudget ? 422 : has400 ? 400 : has403 ? 403 : null, resultErrors]\n}\n\nconst resolveOperationType = (document: DocumentNode, operationName: string | null): OperationTypeNode => {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === Kind.OPERATION_DEFINITION) {\n\t\t\tif (operationName === null || definition.name?.value === operationName) {\n\t\t\t\treturn definition.operation\n\t\t\t}\n\t\t}\n\t}\n\tthrow new GraphQLError('Must provide an operation.')\n}\n"],"names":["response"],"mappings":";;;;;;;AA8CA,MAAM,wBAAwB;AAE9B,MAAM,wBAAwB,KAAK;AACnC,MAAM,6BAA6B,wBAAwB;AAC3D,MAAM,uBAAuB,6BAA6B;AAC1D,MAAM,mBAAmB;AACzB,MAAM,cAAc,mBAAmB;AAEhC,MAAM,4BAA4B,CAAU;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AACD,MAA0D;AACzD,MAAI,kBAAkB;AACtB,Q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GAAyB;AACvI,iCAA2B;AAAA,IAC5B,WAAW,yBAAyB,WAAW;AAC9C,mBAAa,KAAK,EAAE,SAAS,MAAM,SAAS,WAAW,MAAM,WAAW,MAAM,MAAM,KAAA,CAAM;AAC1F,eAAS;AAAA,IACV,OAAO;AACN,aAAO,MAAM,iBAAiB,KAAK;AACnC,mBAAa,KAAK,EAAE,SAAS,yBAAyB,WAAW,QAAW,MAAM,QAAW;AAC7F,eAAS;AAAA,IACV;AAAA,EACD;AACA,SAAO,CAAC,SAAS,MAAM,2BAA2B,MAAM,SAAS,MAAM,SAAS,MAAM,MAAM,YAAY;AACzG;AAEA,MAAM,uBAAuB,CAAC,UAAwB,kBAAoD;AACzG,aAAW,cAAc,SAAS,aAAa;AAC9C,QAAI,WAAW,SAAS,KAAK,sBAAsB;AAClD,UAAI,kBAAkB,QAAQ,WAAW,MAAM,UAAU,eAAe;AACvE,eAAO,WAAW;AAAA,MACnB;AAAA,IACD;AAAA,EACD;AACA,QAAM,IAAI,aAAa,4BAA4B;AACpD;"}
|
|
@@ -7,7 +7,7 @@ require("@contember/engine-content-api");
|
|
|
7
7
|
require("ipaddr.js");
|
|
8
8
|
require("@contember/engine-tenant-api");
|
|
9
9
|
require("graphql");
|
|
10
|
-
require("
|
|
10
|
+
require("@contember/utilities");
|
|
11
11
|
require("node:crypto");
|
|
12
12
|
require("@contember/logger");
|
|
13
13
|
require("@contember/graphql-utils");
|
|
@@ -5,7 +5,7 @@ import "@contember/engine-content-api";
|
|
|
5
5
|
import "ipaddr.js";
|
|
6
6
|
import "@contember/engine-tenant-api";
|
|
7
7
|
import "graphql";
|
|
8
|
-
import "
|
|
8
|
+
import "@contember/utilities";
|
|
9
9
|
import "node:crypto";
|
|
10
10
|
import "@contember/logger";
|
|
11
11
|
import "@contember/graphql-utils";
|
|
@@ -9,7 +9,7 @@ require("@contember/engine-content-api");
|
|
|
9
9
|
const Authorizator = require("../common/Authorizator.cjs");
|
|
10
10
|
require("@contember/engine-tenant-api");
|
|
11
11
|
require("graphql");
|
|
12
|
-
require("
|
|
12
|
+
require("@contember/utilities");
|
|
13
13
|
const crypto = require("node:crypto");
|
|
14
14
|
require("@contember/logger");
|
|
15
15
|
require("@contember/graphql-utils");
|
|
@@ -80,7 +80,8 @@ class ProjectGroupContainerFactory {
|
|
|
80
80
|
decrypt: cryptoWrapper.decrypt.bind(cryptoWrapper),
|
|
81
81
|
encrypt: cryptoWrapper.encrypt.bind(cryptoWrapper),
|
|
82
82
|
encryptionEnabled: cryptoWrapper.enabled
|
|
83
|
-
}
|
|
83
|
+
},
|
|
84
|
+
dataSigner: cryptoWrapper.enabled ? (purpose, value) => cryptoWrapper.sign(purpose, value) : null
|
|
84
85
|
});
|
|
85
86
|
}
|
|
86
87
|
).addService("tenantDatabase", ({ tenantContainer }) => tenantContainer.databaseContext).addService("tenantReadDatabase", ({ tenantContainer }) => tenantContainer.readDatabaseContext).addService("identityFetcher", ({ tenantContainer: { identityFetcher } }) => identityFetcher).addService("systemContainer", ({ identityFetcher }) => this.systemContainerFactory.create({ identityFetcher })).addService("schemaProvider", ({ systemContainer }) => systemContainer.schemaProvider).addService("projectContainerFactory", ({ schemaProvider, logger }) => this.projectContainerFactoryFactory.create(schemaProvider, logger)).addService("tenantProjectManager", ({ tenantContainer }) => tenantContainer.projectManager).addService("tenantProjectMemberManager", ({ tenantContainer }) => tenantContainer.projectMemberManager).addService("projectContainerResolver", ({ projectContainerFactory, tenantProjectManager, tenantReadDatabase }) => new ProjectContainerResolver.ProjectContainerResolver(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProjectGroupContainer.cjs","sources":["../../../../../packages/engine-http/src/projectGroup/ProjectGroupContainer.ts"],"sourcesContent":["import { Builder } from '@contember/dic'\nimport { Connection } from '@contember/database'\nimport {\n\tProjectInitializer as ProjectInitializerInterface,\n\tProjectSchemaResolver as ProjectSchemaResolverInterface,\n\tTenantContainer,\n\tTenantContainerFactory,\n} from '@contember/engine-tenant-api'\nimport { TenantConfig } from '../config/config.js'\nimport {\n\tProjectContainerFactoryFactory,\n\tProjectContainerResolver,\n\tProjectInitializer,\n\tProjectInitializerProxy,\n\tProjectSchemaResolver,\n\tProjectSchemaResolverProxy,\n} from '../project/index.js'\nimport { SystemContainer, SystemContainerFactory } from '@contember/engine-system-api'\nimport { ProjectConfigResolver } from '../config/projectConfigResolver.js'\nimport { createSecretKey } from 'node:crypto'\nimport { Logger } from '@contember/logger'\nimport { TenantGraphQLHandler, TenantGraphQLHandlerFactory } from '../tenant/index.js'\nimport { SystemGraphQLHandler, SystemGraphQLHandlerFactory } from '../system/index.js'\nimport { Authenticator } from '../common/index.js'\nimport { ProjectMembershipFetcher, ProjectMembershipResolver } from '../content/index.js'\nimport { Providers } from '../providers.js'\nimport { CryptoWrapper } from '../utils/CryptoWrapper.js'\n\n/**\n * Normalizes a token list that may be provided either as an array (JSON config)\n * or as a comma/whitespace-separated string (env-based config) into an array of\n * non-empty tokens.\n */\nconst normalizeTokenList = (value: string | readonly string[] | undefined): readonly string[] | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst items = (Array.isArray(value) ? value : (value as string).split(/[\\s,]+/))\n\t\t.map(it => it.trim())\n\t\t.filter(it => it.length > 0)\n\treturn items.length > 0 ? items : undefined\n}\n\nexport interface ProjectGroupContainer {\n\tslug: string | undefined\n\n\tlogger: Logger\n\tauthenticator: Authenticator\n\tprojectMembershipResolver: ProjectMembershipResolver\n\n\tprojectContainerResolver: ProjectContainerResolver\n\tprojectSchemaResolver: ProjectSchemaResolverInterface\n\tprojectInitializer: ProjectInitializerInterface\n\n\ttenantContainer: TenantContainer\n\ttenantGraphQLHandler: TenantGraphQLHandler\n\n\tsystemContainer: SystemContainer\n\tsystemGraphQLHandler: SystemGraphQLHandler\n}\n\ninterface ProjectGroupContainerFactoryArgs {\n\tconfig: TenantConfig\n\tslug: string | undefined\n}\n\nexport class ProjectGroupContainerFactory {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly providers: Providers,\n\t\tprivate readonly systemContainerFactory: SystemContainerFactory,\n\t\tprivate readonly tenantContainerFactory: TenantContainerFactory,\n\t\tprivate readonly projectContainerFactoryFactory: ProjectContainerFactoryFactory,\n\t\tprivate readonly projectConfigResolver: ProjectConfigResolver,\n\t\tprivate readonly tenantGraphQLHandlerFactory: TenantGraphQLHandlerFactory,\n\t\tprivate readonly systemGraphQLHandlerFactory: SystemGraphQLHandlerFactory,\n\t\tprivate readonly logger: Logger,\n\t\t/** A03: configured trusted geo-country header name, or undefined when off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {}\n\n\tpublic create({ config, slug }: ProjectGroupContainerFactoryArgs): ProjectGroupContainer {\n\t\treturn new Builder({})\n\t\t\t.addService('slug', () => slug)\n\t\t\t.addService('logger', ({ slug }) => this.logger.child({ projectGroup: slug }))\n\t\t\t.addService('providers', () => this.providers)\n\t\t\t.addService('tenantDbCredentials', () => config.db)\n\t\t\t.addService(\n\t\t\t\t'tenantConnection',\n\t\t\t\t({ tenantDbCredentials, logger }): Connection.ConnectionType => Connection.create(tenantDbCredentials, err => logger.error(err)),\n\t\t\t)\n\t\t\t.addService('tenantReadConnection', ({ tenantDbCredentials, logger, tenantConnection }) => {\n\t\t\t\tif (!tenantDbCredentials.read) {\n\t\t\t\t\treturn tenantConnection\n\t\t\t\t}\n\t\t\t\treturn Connection.create(\n\t\t\t\t\t{\n\t\t\t\t\t\t...tenantDbCredentials,\n\t\t\t\t\t\t...tenantDbCredentials.read,\n\t\t\t\t\t\tpool: {\n\t\t\t\t\t\t\t...tenantDbCredentials.pool,\n\t\t\t\t\t\t\t...tenantDbCredentials.read.pool,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\terr => logger.error(err),\n\t\t\t\t\t{ retryStaleConnection: true },\n\t\t\t\t)\n\t\t\t})\n\t\t\t.addService('projectSchemaResolver', () => new ProjectSchemaResolverProxy())\n\t\t\t.addService('projectInitializer', () => new ProjectInitializerProxy())\n\t\t\t.addService(\n\t\t\t\t'tenantContainer',\n\t\t\t\t({ tenantConnection, tenantReadConnection, tenantDbCredentials, projectSchemaResolver, projectInitializer, logger }) => {\n\t\t\t\t\tconst encryptionKey = config.secrets.encryptionKey\n\t\t\t\t\t\t? createSecretKey(Buffer.from(config.secrets.encryptionKey, 'hex'))\n\t\t\t\t\t\t: undefined\n\n\t\t\t\t\tconst cryptoWrapper = new CryptoWrapper(encryptionKey)\n\t\t\t\t\treturn this.tenantContainerFactory.create({\n\t\t\t\t\t\tconnection: tenantConnection,\n\t\t\t\t\t\treadConnection: tenantReadConnection,\n\t\t\t\t\t\tdbCredentials: tenantDbCredentials,\n\t\t\t\t\t\tmailOptions: config.mailer,\n\t\t\t\t\t\ttenantCredentials: {\n\t\t\t\t\t\t\t...config.credentials,\n\t\t\t\t\t\t\trootTokens: normalizeTokenList(config.credentials.rootTokens),\n\t\t\t\t\t\t\trootTokenHashes: normalizeTokenList(config.credentials.rootTokenHashes),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprojectInitializer,\n\t\t\t\t\t\tprojectSchemaResolver,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\tcryptoProviders: {\n\t\t\t\t\t\t\tdecrypt: cryptoWrapper.decrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencrypt: cryptoWrapper.encrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencryptionEnabled: cryptoWrapper.enabled,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t)\n\t\t\t.addService('tenantDatabase', ({ tenantContainer }) => tenantContainer.databaseContext)\n\t\t\t.addService('tenantReadDatabase', ({ tenantContainer }) => tenantContainer.readDatabaseContext)\n\t\t\t.addService('identityFetcher', ({ tenantContainer: { identityFetcher } }) => identityFetcher)\n\t\t\t.addService('systemContainer', ({ identityFetcher }) => this.systemContainerFactory.create({ identityFetcher }))\n\t\t\t.addService('schemaProvider', ({ systemContainer }) => systemContainer.schemaProvider)\n\t\t\t.addService('projectContainerFactory', ({ schemaProvider, logger }) => this.projectContainerFactoryFactory.create(schemaProvider, logger))\n\t\t\t.addService('tenantProjectManager', ({ tenantContainer }) => tenantContainer.projectManager)\n\t\t\t.addService('tenantProjectMemberManager', ({ tenantContainer }) => tenantContainer.projectMemberManager)\n\t\t\t.addService('projectContainerResolver', ({ projectContainerFactory, tenantProjectManager, tenantReadDatabase }) =>\n\t\t\t\tnew ProjectContainerResolver(\n\t\t\t\t\tprojectContainerFactory,\n\t\t\t\t\tthis.projectConfigResolver,\n\t\t\t\t\ttenantProjectManager,\n\t\t\t\t\ttenantReadDatabase,\n\t\t\t\t\tconfig,\n\t\t\t\t))\n\t\t\t.setupService('projectSchemaResolver', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setResolver(new ProjectSchemaResolver(projectContainerResolver))\n\t\t\t})\n\t\t\t.setupService('projectInitializer', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setInitializer(new ProjectInitializer(projectContainerResolver))\n\t\t\t})\n\t\t\t.addService('tenantGraphQLHandler', ({ tenantContainer }) => this.tenantGraphQLHandlerFactory.create(tenantContainer.resolvers))\n\t\t\t.addService('systemGraphQLHandler', ({ systemContainer }) => this.systemGraphQLHandlerFactory.create(systemContainer.systemResolversFactory))\n\t\t\t.addService(\n\t\t\t\t'authenticator',\n\t\t\t\t({ tenantDatabase, tenantReadDatabase, tenantContainer }) =>\n\t\t\t\t\tnew Authenticator(tenantDatabase, tenantReadDatabase, tenantContainer.apiKeyManager, this.geoCountryHeader),\n\t\t\t)\n\t\t\t.addService(\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t({ tenantProjectMemberManager, tenantReadDatabase }) =>\n\t\t\t\t\tnew ProjectMembershipResolver(this.debug, new ProjectMembershipFetcher(tenantProjectMemberManager, tenantReadDatabase)),\n\t\t\t)\n\t\t\t.build()\n\t\t\t.pick(\n\t\t\t\t'projectContainerResolver',\n\t\t\t\t'projectSchemaResolver',\n\t\t\t\t'projectInitializer',\n\t\t\t\t'systemContainer',\n\t\t\t\t'systemGraphQLHandler',\n\t\t\t\t'tenantContainer',\n\t\t\t\t'authenticator',\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t'tenantGraphQLHandler',\n\t\t\t\t'slug',\n\t\t\t\t'logger',\n\t\t\t)\n\t}\n}\n"],"names":["Builder","slug","Connection","ProjectSchemaResolverProxy","ProjectInitializerProxy","createSecretKey","CryptoWrapper","ProjectContainerResolver","ProjectSchemaResolver","ProjectInitializer","Authenticator","ProjectMembershipResolver","ProjectMembershipFetcher"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiCA,MAAM,qBAAqB,CAAC,UAAiF;AAC5G,MAAI,UAAU,QAAW;AACxB,WAAO;AAAA,EACR;AACA,QAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,QAAS,MAAiB,MAAM,QAAQ,GAC5E,IAAI,CAAA,OAAM,GAAG,MAAM,EACnB,OAAO,CAAA,OAAM,GAAG,SAAS,CAAC;AAC5B,SAAO,MAAM,SAAS,IAAI,QAAQ;AACnC;AAyBO,MAAM,6BAA6B;AAAA,EACzC,YACkB,OACA,WACA,wBACA,wBACA,gCACA,uBACA,6BACA,6BACA,QAEA,kBAChB;AAXgB,SAAA,QAAA;AACA,SAAA,YAAA;AACA,SAAA,yBAAA;AACA,SAAA,yBAAA;AACA,SAAA,iCAAA;AACA,SAAA,wBAAA;AACA,SAAA,8BAAA;AACA,SAAA,8BAAA;AACA,SAAA,SAAA;AAEA,SAAA,mBAAA;AAAA,EACf;AAAA,EAEI,OAAO,EAAE,QAAQ,QAAiE;AACxF,WAAO,IAAIA,IAAAA,QAAQ,CAAA,CAAE,EACnB,WAAW,QAAQ,MAAM,IAAI,EAC7B,WAAW,UAAU,CAAC,EAAE,MAAAC,YAAW,KAAK,OAAO,MAAM,EAAE,cAAcA,MAAAA,CAAM,CAAC,EAC5E,WAAW,aAAa,MAAM,KAAK,SAAS,EAC5C,WAAW,uBAAuB,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A4B,OAAO,gBAAgB,sBAAsB,CAAC,EAC3I;AAAA,MACA;AAAA,MACA,CAAC,EAAE,gBAAgB,oBAAoB,gBAAA,MACtC,IAAIC,aAAAA,cAAc,gBAAgB,oBAAoB,gBAAgB,eAAe,KAAK,gBAAgB;AAAA,IAAA,EAE3G;AAAA,MACA;AAAA,MACA,CAAC,EAAE,4BAA4B,mBAAA,MAC9B,IAAIC,0BAAAA,0BAA0B,KAAK,OAAO,IAAIC,yBAAAA,yBAAyB,4BAA4B,kBAAkB,CAAC;AAAA,IAAA,EAEvH,QACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEH;AACD;;"}
|
|
1
|
+
{"version":3,"file":"ProjectGroupContainer.cjs","sources":["../../../../../packages/engine-http/src/projectGroup/ProjectGroupContainer.ts"],"sourcesContent":["import { Builder } from '@contember/dic'\nimport { Connection } from '@contember/database'\nimport {\n\tProjectInitializer as ProjectInitializerInterface,\n\tProjectSchemaResolver as ProjectSchemaResolverInterface,\n\tTenantContainer,\n\tTenantContainerFactory,\n} from '@contember/engine-tenant-api'\nimport { TenantConfig } from '../config/config.js'\nimport {\n\tProjectContainerFactoryFactory,\n\tProjectContainerResolver,\n\tProjectInitializer,\n\tProjectInitializerProxy,\n\tProjectSchemaResolver,\n\tProjectSchemaResolverProxy,\n} from '../project/index.js'\nimport { SystemContainer, SystemContainerFactory } from '@contember/engine-system-api'\nimport { ProjectConfigResolver } from '../config/projectConfigResolver.js'\nimport { createSecretKey } from 'node:crypto'\nimport { Logger } from '@contember/logger'\nimport { TenantGraphQLHandler, TenantGraphQLHandlerFactory } from '../tenant/index.js'\nimport { SystemGraphQLHandler, SystemGraphQLHandlerFactory } from '../system/index.js'\nimport { Authenticator } from '../common/index.js'\nimport { ProjectMembershipFetcher, ProjectMembershipResolver } from '../content/index.js'\nimport { Providers } from '../providers.js'\nimport { CryptoWrapper } from '../utils/CryptoWrapper.js'\n\n/**\n * Normalizes a token list that may be provided either as an array (JSON config)\n * or as a comma/whitespace-separated string (env-based config) into an array of\n * non-empty tokens.\n */\nconst normalizeTokenList = (value: string | readonly string[] | undefined): readonly string[] | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst items = (Array.isArray(value) ? value : (value as string).split(/[\\s,]+/))\n\t\t.map(it => it.trim())\n\t\t.filter(it => it.length > 0)\n\treturn items.length > 0 ? items : undefined\n}\n\nexport interface ProjectGroupContainer {\n\tslug: string | undefined\n\n\tlogger: Logger\n\tauthenticator: Authenticator\n\tprojectMembershipResolver: ProjectMembershipResolver\n\n\tprojectContainerResolver: ProjectContainerResolver\n\tprojectSchemaResolver: ProjectSchemaResolverInterface\n\tprojectInitializer: ProjectInitializerInterface\n\n\ttenantContainer: TenantContainer\n\ttenantGraphQLHandler: TenantGraphQLHandler\n\n\tsystemContainer: SystemContainer\n\tsystemGraphQLHandler: SystemGraphQLHandler\n}\n\ninterface ProjectGroupContainerFactoryArgs {\n\tconfig: TenantConfig\n\tslug: string | undefined\n}\n\nexport class ProjectGroupContainerFactory {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly providers: Providers,\n\t\tprivate readonly systemContainerFactory: SystemContainerFactory,\n\t\tprivate readonly tenantContainerFactory: TenantContainerFactory,\n\t\tprivate readonly projectContainerFactoryFactory: ProjectContainerFactoryFactory,\n\t\tprivate readonly projectConfigResolver: ProjectConfigResolver,\n\t\tprivate readonly tenantGraphQLHandlerFactory: TenantGraphQLHandlerFactory,\n\t\tprivate readonly systemGraphQLHandlerFactory: SystemGraphQLHandlerFactory,\n\t\tprivate readonly logger: Logger,\n\t\t/** A03: configured trusted geo-country header name, or undefined when off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {}\n\n\tpublic create({ config, slug }: ProjectGroupContainerFactoryArgs): ProjectGroupContainer {\n\t\treturn new Builder({})\n\t\t\t.addService('slug', () => slug)\n\t\t\t.addService('logger', ({ slug }) => this.logger.child({ projectGroup: slug }))\n\t\t\t.addService('providers', () => this.providers)\n\t\t\t.addService('tenantDbCredentials', () => config.db)\n\t\t\t.addService(\n\t\t\t\t'tenantConnection',\n\t\t\t\t({ tenantDbCredentials, logger }): Connection.ConnectionType => Connection.create(tenantDbCredentials, err => logger.error(err)),\n\t\t\t)\n\t\t\t.addService('tenantReadConnection', ({ tenantDbCredentials, logger, tenantConnection }) => {\n\t\t\t\tif (!tenantDbCredentials.read) {\n\t\t\t\t\treturn tenantConnection\n\t\t\t\t}\n\t\t\t\treturn Connection.create(\n\t\t\t\t\t{\n\t\t\t\t\t\t...tenantDbCredentials,\n\t\t\t\t\t\t...tenantDbCredentials.read,\n\t\t\t\t\t\tpool: {\n\t\t\t\t\t\t\t...tenantDbCredentials.pool,\n\t\t\t\t\t\t\t...tenantDbCredentials.read.pool,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\terr => logger.error(err),\n\t\t\t\t\t{ retryStaleConnection: true },\n\t\t\t\t)\n\t\t\t})\n\t\t\t.addService('projectSchemaResolver', () => new ProjectSchemaResolverProxy())\n\t\t\t.addService('projectInitializer', () => new ProjectInitializerProxy())\n\t\t\t.addService(\n\t\t\t\t'tenantContainer',\n\t\t\t\t({ tenantConnection, tenantReadConnection, tenantDbCredentials, projectSchemaResolver, projectInitializer, logger }) => {\n\t\t\t\t\tconst encryptionKey = config.secrets.encryptionKey\n\t\t\t\t\t\t? createSecretKey(Buffer.from(config.secrets.encryptionKey, 'hex'))\n\t\t\t\t\t\t: undefined\n\n\t\t\t\t\tconst cryptoWrapper = new CryptoWrapper(encryptionKey)\n\t\t\t\t\treturn this.tenantContainerFactory.create({\n\t\t\t\t\t\tconnection: tenantConnection,\n\t\t\t\t\t\treadConnection: tenantReadConnection,\n\t\t\t\t\t\tdbCredentials: tenantDbCredentials,\n\t\t\t\t\t\tmailOptions: config.mailer,\n\t\t\t\t\t\ttenantCredentials: {\n\t\t\t\t\t\t\t...config.credentials,\n\t\t\t\t\t\t\trootTokens: normalizeTokenList(config.credentials.rootTokens),\n\t\t\t\t\t\t\trootTokenHashes: normalizeTokenList(config.credentials.rootTokenHashes),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprojectInitializer,\n\t\t\t\t\t\tprojectSchemaResolver,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\tcryptoProviders: {\n\t\t\t\t\t\t\tdecrypt: cryptoWrapper.decrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencrypt: cryptoWrapper.encrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencryptionEnabled: cryptoWrapper.enabled,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdataSigner: cryptoWrapper.enabled ? (purpose, value) => cryptoWrapper.sign(purpose, value) : null,\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t)\n\t\t\t.addService('tenantDatabase', ({ tenantContainer }) => tenantContainer.databaseContext)\n\t\t\t.addService('tenantReadDatabase', ({ tenantContainer }) => tenantContainer.readDatabaseContext)\n\t\t\t.addService('identityFetcher', ({ tenantContainer: { identityFetcher } }) => identityFetcher)\n\t\t\t.addService('systemContainer', ({ identityFetcher }) => this.systemContainerFactory.create({ identityFetcher }))\n\t\t\t.addService('schemaProvider', ({ systemContainer }) => systemContainer.schemaProvider)\n\t\t\t.addService('projectContainerFactory', ({ schemaProvider, logger }) => this.projectContainerFactoryFactory.create(schemaProvider, logger))\n\t\t\t.addService('tenantProjectManager', ({ tenantContainer }) => tenantContainer.projectManager)\n\t\t\t.addService('tenantProjectMemberManager', ({ tenantContainer }) => tenantContainer.projectMemberManager)\n\t\t\t.addService('projectContainerResolver', ({ projectContainerFactory, tenantProjectManager, tenantReadDatabase }) =>\n\t\t\t\tnew ProjectContainerResolver(\n\t\t\t\t\tprojectContainerFactory,\n\t\t\t\t\tthis.projectConfigResolver,\n\t\t\t\t\ttenantProjectManager,\n\t\t\t\t\ttenantReadDatabase,\n\t\t\t\t\tconfig,\n\t\t\t\t))\n\t\t\t.setupService('projectSchemaResolver', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setResolver(new ProjectSchemaResolver(projectContainerResolver))\n\t\t\t})\n\t\t\t.setupService('projectInitializer', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setInitializer(new ProjectInitializer(projectContainerResolver))\n\t\t\t})\n\t\t\t.addService('tenantGraphQLHandler', ({ tenantContainer }) => this.tenantGraphQLHandlerFactory.create(tenantContainer.resolvers))\n\t\t\t.addService('systemGraphQLHandler', ({ systemContainer }) => this.systemGraphQLHandlerFactory.create(systemContainer.systemResolversFactory))\n\t\t\t.addService(\n\t\t\t\t'authenticator',\n\t\t\t\t({ tenantDatabase, tenantReadDatabase, tenantContainer }) =>\n\t\t\t\t\tnew Authenticator(tenantDatabase, tenantReadDatabase, tenantContainer.apiKeyManager, this.geoCountryHeader),\n\t\t\t)\n\t\t\t.addService(\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t({ tenantProjectMemberManager, tenantReadDatabase }) =>\n\t\t\t\t\tnew ProjectMembershipResolver(this.debug, new ProjectMembershipFetcher(tenantProjectMemberManager, tenantReadDatabase)),\n\t\t\t)\n\t\t\t.build()\n\t\t\t.pick(\n\t\t\t\t'projectContainerResolver',\n\t\t\t\t'projectSchemaResolver',\n\t\t\t\t'projectInitializer',\n\t\t\t\t'systemContainer',\n\t\t\t\t'systemGraphQLHandler',\n\t\t\t\t'tenantContainer',\n\t\t\t\t'authenticator',\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t'tenantGraphQLHandler',\n\t\t\t\t'slug',\n\t\t\t\t'logger',\n\t\t\t)\n\t}\n}\n"],"names":["Builder","slug","Connection","ProjectSchemaResolverProxy","ProjectInitializerProxy","createSecretKey","CryptoWrapper","ProjectContainerResolver","ProjectSchemaResolver","ProjectInitializer","Authenticator","ProjectMembershipResolver","ProjectMembershipFetcher"],"mappings":";;;;;;;;;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yB,4BAA4B,kBAAkB,CAAC;AAAA,IAAA,EAEvH,QACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEH;AACD;;"}
|
|
@@ -7,7 +7,7 @@ import "@contember/engine-content-api";
|
|
|
7
7
|
import { Authenticator } from "../common/Authorizator.js";
|
|
8
8
|
import "@contember/engine-tenant-api";
|
|
9
9
|
import "graphql";
|
|
10
|
-
import "
|
|
10
|
+
import "@contember/utilities";
|
|
11
11
|
import { createSecretKey } from "node:crypto";
|
|
12
12
|
import "@contember/logger";
|
|
13
13
|
import "@contember/graphql-utils";
|
|
@@ -78,7 +78,8 @@ class ProjectGroupContainerFactory {
|
|
|
78
78
|
decrypt: cryptoWrapper.decrypt.bind(cryptoWrapper),
|
|
79
79
|
encrypt: cryptoWrapper.encrypt.bind(cryptoWrapper),
|
|
80
80
|
encryptionEnabled: cryptoWrapper.enabled
|
|
81
|
-
}
|
|
81
|
+
},
|
|
82
|
+
dataSigner: cryptoWrapper.enabled ? (purpose, value) => cryptoWrapper.sign(purpose, value) : null
|
|
82
83
|
});
|
|
83
84
|
}
|
|
84
85
|
).addService("tenantDatabase", ({ tenantContainer }) => tenantContainer.databaseContext).addService("tenantReadDatabase", ({ tenantContainer }) => tenantContainer.readDatabaseContext).addService("identityFetcher", ({ tenantContainer: { identityFetcher } }) => identityFetcher).addService("systemContainer", ({ identityFetcher }) => this.systemContainerFactory.create({ identityFetcher })).addService("schemaProvider", ({ systemContainer }) => systemContainer.schemaProvider).addService("projectContainerFactory", ({ schemaProvider, logger }) => this.projectContainerFactoryFactory.create(schemaProvider, logger)).addService("tenantProjectManager", ({ tenantContainer }) => tenantContainer.projectManager).addService("tenantProjectMemberManager", ({ tenantContainer }) => tenantContainer.projectMemberManager).addService("projectContainerResolver", ({ projectContainerFactory, tenantProjectManager, tenantReadDatabase }) => new ProjectContainerResolver(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProjectGroupContainer.js","sources":["../../../../../packages/engine-http/src/projectGroup/ProjectGroupContainer.ts"],"sourcesContent":["import { Builder } from '@contember/dic'\nimport { Connection } from '@contember/database'\nimport {\n\tProjectInitializer as ProjectInitializerInterface,\n\tProjectSchemaResolver as ProjectSchemaResolverInterface,\n\tTenantContainer,\n\tTenantContainerFactory,\n} from '@contember/engine-tenant-api'\nimport { TenantConfig } from '../config/config.js'\nimport {\n\tProjectContainerFactoryFactory,\n\tProjectContainerResolver,\n\tProjectInitializer,\n\tProjectInitializerProxy,\n\tProjectSchemaResolver,\n\tProjectSchemaResolverProxy,\n} from '../project/index.js'\nimport { SystemContainer, SystemContainerFactory } from '@contember/engine-system-api'\nimport { ProjectConfigResolver } from '../config/projectConfigResolver.js'\nimport { createSecretKey } from 'node:crypto'\nimport { Logger } from '@contember/logger'\nimport { TenantGraphQLHandler, TenantGraphQLHandlerFactory } from '../tenant/index.js'\nimport { SystemGraphQLHandler, SystemGraphQLHandlerFactory } from '../system/index.js'\nimport { Authenticator } from '../common/index.js'\nimport { ProjectMembershipFetcher, ProjectMembershipResolver } from '../content/index.js'\nimport { Providers } from '../providers.js'\nimport { CryptoWrapper } from '../utils/CryptoWrapper.js'\n\n/**\n * Normalizes a token list that may be provided either as an array (JSON config)\n * or as a comma/whitespace-separated string (env-based config) into an array of\n * non-empty tokens.\n */\nconst normalizeTokenList = (value: string | readonly string[] | undefined): readonly string[] | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst items = (Array.isArray(value) ? value : (value as string).split(/[\\s,]+/))\n\t\t.map(it => it.trim())\n\t\t.filter(it => it.length > 0)\n\treturn items.length > 0 ? items : undefined\n}\n\nexport interface ProjectGroupContainer {\n\tslug: string | undefined\n\n\tlogger: Logger\n\tauthenticator: Authenticator\n\tprojectMembershipResolver: ProjectMembershipResolver\n\n\tprojectContainerResolver: ProjectContainerResolver\n\tprojectSchemaResolver: ProjectSchemaResolverInterface\n\tprojectInitializer: ProjectInitializerInterface\n\n\ttenantContainer: TenantContainer\n\ttenantGraphQLHandler: TenantGraphQLHandler\n\n\tsystemContainer: SystemContainer\n\tsystemGraphQLHandler: SystemGraphQLHandler\n}\n\ninterface ProjectGroupContainerFactoryArgs {\n\tconfig: TenantConfig\n\tslug: string | undefined\n}\n\nexport class ProjectGroupContainerFactory {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly providers: Providers,\n\t\tprivate readonly systemContainerFactory: SystemContainerFactory,\n\t\tprivate readonly tenantContainerFactory: TenantContainerFactory,\n\t\tprivate readonly projectContainerFactoryFactory: ProjectContainerFactoryFactory,\n\t\tprivate readonly projectConfigResolver: ProjectConfigResolver,\n\t\tprivate readonly tenantGraphQLHandlerFactory: TenantGraphQLHandlerFactory,\n\t\tprivate readonly systemGraphQLHandlerFactory: SystemGraphQLHandlerFactory,\n\t\tprivate readonly logger: Logger,\n\t\t/** A03: configured trusted geo-country header name, or undefined when off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {}\n\n\tpublic create({ config, slug }: ProjectGroupContainerFactoryArgs): ProjectGroupContainer {\n\t\treturn new Builder({})\n\t\t\t.addService('slug', () => slug)\n\t\t\t.addService('logger', ({ slug }) => this.logger.child({ projectGroup: slug }))\n\t\t\t.addService('providers', () => this.providers)\n\t\t\t.addService('tenantDbCredentials', () => config.db)\n\t\t\t.addService(\n\t\t\t\t'tenantConnection',\n\t\t\t\t({ tenantDbCredentials, logger }): Connection.ConnectionType => Connection.create(tenantDbCredentials, err => logger.error(err)),\n\t\t\t)\n\t\t\t.addService('tenantReadConnection', ({ tenantDbCredentials, logger, tenantConnection }) => {\n\t\t\t\tif (!tenantDbCredentials.read) {\n\t\t\t\t\treturn tenantConnection\n\t\t\t\t}\n\t\t\t\treturn Connection.create(\n\t\t\t\t\t{\n\t\t\t\t\t\t...tenantDbCredentials,\n\t\t\t\t\t\t...tenantDbCredentials.read,\n\t\t\t\t\t\tpool: {\n\t\t\t\t\t\t\t...tenantDbCredentials.pool,\n\t\t\t\t\t\t\t...tenantDbCredentials.read.pool,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\terr => logger.error(err),\n\t\t\t\t\t{ retryStaleConnection: true },\n\t\t\t\t)\n\t\t\t})\n\t\t\t.addService('projectSchemaResolver', () => new ProjectSchemaResolverProxy())\n\t\t\t.addService('projectInitializer', () => new ProjectInitializerProxy())\n\t\t\t.addService(\n\t\t\t\t'tenantContainer',\n\t\t\t\t({ tenantConnection, tenantReadConnection, tenantDbCredentials, projectSchemaResolver, projectInitializer, logger }) => {\n\t\t\t\t\tconst encryptionKey = config.secrets.encryptionKey\n\t\t\t\t\t\t? createSecretKey(Buffer.from(config.secrets.encryptionKey, 'hex'))\n\t\t\t\t\t\t: undefined\n\n\t\t\t\t\tconst cryptoWrapper = new CryptoWrapper(encryptionKey)\n\t\t\t\t\treturn this.tenantContainerFactory.create({\n\t\t\t\t\t\tconnection: tenantConnection,\n\t\t\t\t\t\treadConnection: tenantReadConnection,\n\t\t\t\t\t\tdbCredentials: tenantDbCredentials,\n\t\t\t\t\t\tmailOptions: config.mailer,\n\t\t\t\t\t\ttenantCredentials: {\n\t\t\t\t\t\t\t...config.credentials,\n\t\t\t\t\t\t\trootTokens: normalizeTokenList(config.credentials.rootTokens),\n\t\t\t\t\t\t\trootTokenHashes: normalizeTokenList(config.credentials.rootTokenHashes),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprojectInitializer,\n\t\t\t\t\t\tprojectSchemaResolver,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\tcryptoProviders: {\n\t\t\t\t\t\t\tdecrypt: cryptoWrapper.decrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencrypt: cryptoWrapper.encrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencryptionEnabled: cryptoWrapper.enabled,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t)\n\t\t\t.addService('tenantDatabase', ({ tenantContainer }) => tenantContainer.databaseContext)\n\t\t\t.addService('tenantReadDatabase', ({ tenantContainer }) => tenantContainer.readDatabaseContext)\n\t\t\t.addService('identityFetcher', ({ tenantContainer: { identityFetcher } }) => identityFetcher)\n\t\t\t.addService('systemContainer', ({ identityFetcher }) => this.systemContainerFactory.create({ identityFetcher }))\n\t\t\t.addService('schemaProvider', ({ systemContainer }) => systemContainer.schemaProvider)\n\t\t\t.addService('projectContainerFactory', ({ schemaProvider, logger }) => this.projectContainerFactoryFactory.create(schemaProvider, logger))\n\t\t\t.addService('tenantProjectManager', ({ tenantContainer }) => tenantContainer.projectManager)\n\t\t\t.addService('tenantProjectMemberManager', ({ tenantContainer }) => tenantContainer.projectMemberManager)\n\t\t\t.addService('projectContainerResolver', ({ projectContainerFactory, tenantProjectManager, tenantReadDatabase }) =>\n\t\t\t\tnew ProjectContainerResolver(\n\t\t\t\t\tprojectContainerFactory,\n\t\t\t\t\tthis.projectConfigResolver,\n\t\t\t\t\ttenantProjectManager,\n\t\t\t\t\ttenantReadDatabase,\n\t\t\t\t\tconfig,\n\t\t\t\t))\n\t\t\t.setupService('projectSchemaResolver', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setResolver(new ProjectSchemaResolver(projectContainerResolver))\n\t\t\t})\n\t\t\t.setupService('projectInitializer', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setInitializer(new ProjectInitializer(projectContainerResolver))\n\t\t\t})\n\t\t\t.addService('tenantGraphQLHandler', ({ tenantContainer }) => this.tenantGraphQLHandlerFactory.create(tenantContainer.resolvers))\n\t\t\t.addService('systemGraphQLHandler', ({ systemContainer }) => this.systemGraphQLHandlerFactory.create(systemContainer.systemResolversFactory))\n\t\t\t.addService(\n\t\t\t\t'authenticator',\n\t\t\t\t({ tenantDatabase, tenantReadDatabase, tenantContainer }) =>\n\t\t\t\t\tnew Authenticator(tenantDatabase, tenantReadDatabase, tenantContainer.apiKeyManager, this.geoCountryHeader),\n\t\t\t)\n\t\t\t.addService(\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t({ tenantProjectMemberManager, tenantReadDatabase }) =>\n\t\t\t\t\tnew ProjectMembershipResolver(this.debug, new ProjectMembershipFetcher(tenantProjectMemberManager, tenantReadDatabase)),\n\t\t\t)\n\t\t\t.build()\n\t\t\t.pick(\n\t\t\t\t'projectContainerResolver',\n\t\t\t\t'projectSchemaResolver',\n\t\t\t\t'projectInitializer',\n\t\t\t\t'systemContainer',\n\t\t\t\t'systemGraphQLHandler',\n\t\t\t\t'tenantContainer',\n\t\t\t\t'authenticator',\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t'tenantGraphQLHandler',\n\t\t\t\t'slug',\n\t\t\t\t'logger',\n\t\t\t)\n\t}\n}\n"],"names":["slug"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,MAAM,qBAAqB,CAAC,UAAiF;AAC5G,MAAI,UAAU,QAAW;AACxB,WAAO;AAAA,EACR;AACA,QAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,QAAS,MAAiB,MAAM,QAAQ,GAC5E,IAAI,CAAA,OAAM,GAAG,MAAM,EACnB,OAAO,CAAA,OAAM,GAAG,SAAS,CAAC;AAC5B,SAAO,MAAM,SAAS,IAAI,QAAQ;AACnC;AAyBO,MAAM,6BAA6B;AAAA,EACzC,YACkB,OACA,WACA,wBACA,wBACA,gCACA,uBACA,6BACA,6BACA,QAEA,kBAChB;AAXgB,SAAA,QAAA;AACA,SAAA,YAAA;AACA,SAAA,yBAAA;AACA,SAAA,yBAAA;AACA,SAAA,iCAAA;AACA,SAAA,wBAAA;AACA,SAAA,8BAAA;AACA,SAAA,8BAAA;AACA,SAAA,SAAA;AAEA,SAAA,mBAAA;AAAA,EACf;AAAA,EAEI,OAAO,EAAE,QAAQ,QAAiE;AACxF,WAAO,IAAI,QAAQ,CAAA,CAAE,EACnB,WAAW,QAAQ,MAAM,IA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B,OAAO,gBAAgB,SAAS,CAAC,EAC9H,WAAW,wBAAwB,CAAC,EAAE,sBAAsB,KAAK,4BAA4B,OAAO,gBAAgB,sBAAsB,CAAC,EAC3I;AAAA,MACA;AAAA,MACA,CAAC,EAAE,gBAAgB,oBAAoB,gBAAA,MACtC,IAAI,cAAc,gBAAgB,oBAAoB,gBAAgB,eAAe,KAAK,gBAAgB;AAAA,IAAA,EAE3G;AAAA,MACA;AAAA,MACA,CAAC,EAAE,4BAA4B,mBAAA,MAC9B,IAAI,0BAA0B,KAAK,OAAO,IAAI,yBAAyB,4BAA4B,kBAAkB,CAAC;AAAA,IAAA,EAEvH,QACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEH;AACD;"}
|
|
1
|
+
{"version":3,"file":"ProjectGroupContainer.js","sources":["../../../../../packages/engine-http/src/projectGroup/ProjectGroupContainer.ts"],"sourcesContent":["import { Builder } from '@contember/dic'\nimport { Connection } from '@contember/database'\nimport {\n\tProjectInitializer as ProjectInitializerInterface,\n\tProjectSchemaResolver as ProjectSchemaResolverInterface,\n\tTenantContainer,\n\tTenantContainerFactory,\n} from '@contember/engine-tenant-api'\nimport { TenantConfig } from '../config/config.js'\nimport {\n\tProjectContainerFactoryFactory,\n\tProjectContainerResolver,\n\tProjectInitializer,\n\tProjectInitializerProxy,\n\tProjectSchemaResolver,\n\tProjectSchemaResolverProxy,\n} from '../project/index.js'\nimport { SystemContainer, SystemContainerFactory } from '@contember/engine-system-api'\nimport { ProjectConfigResolver } from '../config/projectConfigResolver.js'\nimport { createSecretKey } from 'node:crypto'\nimport { Logger } from '@contember/logger'\nimport { TenantGraphQLHandler, TenantGraphQLHandlerFactory } from '../tenant/index.js'\nimport { SystemGraphQLHandler, SystemGraphQLHandlerFactory } from '../system/index.js'\nimport { Authenticator } from '../common/index.js'\nimport { ProjectMembershipFetcher, ProjectMembershipResolver } from '../content/index.js'\nimport { Providers } from '../providers.js'\nimport { CryptoWrapper } from '../utils/CryptoWrapper.js'\n\n/**\n * Normalizes a token list that may be provided either as an array (JSON config)\n * or as a comma/whitespace-separated string (env-based config) into an array of\n * non-empty tokens.\n */\nconst normalizeTokenList = (value: string | readonly string[] | undefined): readonly string[] | undefined => {\n\tif (value === undefined) {\n\t\treturn undefined\n\t}\n\tconst items = (Array.isArray(value) ? value : (value as string).split(/[\\s,]+/))\n\t\t.map(it => it.trim())\n\t\t.filter(it => it.length > 0)\n\treturn items.length > 0 ? items : undefined\n}\n\nexport interface ProjectGroupContainer {\n\tslug: string | undefined\n\n\tlogger: Logger\n\tauthenticator: Authenticator\n\tprojectMembershipResolver: ProjectMembershipResolver\n\n\tprojectContainerResolver: ProjectContainerResolver\n\tprojectSchemaResolver: ProjectSchemaResolverInterface\n\tprojectInitializer: ProjectInitializerInterface\n\n\ttenantContainer: TenantContainer\n\ttenantGraphQLHandler: TenantGraphQLHandler\n\n\tsystemContainer: SystemContainer\n\tsystemGraphQLHandler: SystemGraphQLHandler\n}\n\ninterface ProjectGroupContainerFactoryArgs {\n\tconfig: TenantConfig\n\tslug: string | undefined\n}\n\nexport class ProjectGroupContainerFactory {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly providers: Providers,\n\t\tprivate readonly systemContainerFactory: SystemContainerFactory,\n\t\tprivate readonly tenantContainerFactory: TenantContainerFactory,\n\t\tprivate readonly projectContainerFactoryFactory: ProjectContainerFactoryFactory,\n\t\tprivate readonly projectConfigResolver: ProjectConfigResolver,\n\t\tprivate readonly tenantGraphQLHandlerFactory: TenantGraphQLHandlerFactory,\n\t\tprivate readonly systemGraphQLHandlerFactory: SystemGraphQLHandlerFactory,\n\t\tprivate readonly logger: Logger,\n\t\t/** A03: configured trusted geo-country header name, or undefined when off. */\n\t\tprivate readonly geoCountryHeader?: string,\n\t) {}\n\n\tpublic create({ config, slug }: ProjectGroupContainerFactoryArgs): ProjectGroupContainer {\n\t\treturn new Builder({})\n\t\t\t.addService('slug', () => slug)\n\t\t\t.addService('logger', ({ slug }) => this.logger.child({ projectGroup: slug }))\n\t\t\t.addService('providers', () => this.providers)\n\t\t\t.addService('tenantDbCredentials', () => config.db)\n\t\t\t.addService(\n\t\t\t\t'tenantConnection',\n\t\t\t\t({ tenantDbCredentials, logger }): Connection.ConnectionType => Connection.create(tenantDbCredentials, err => logger.error(err)),\n\t\t\t)\n\t\t\t.addService('tenantReadConnection', ({ tenantDbCredentials, logger, tenantConnection }) => {\n\t\t\t\tif (!tenantDbCredentials.read) {\n\t\t\t\t\treturn tenantConnection\n\t\t\t\t}\n\t\t\t\treturn Connection.create(\n\t\t\t\t\t{\n\t\t\t\t\t\t...tenantDbCredentials,\n\t\t\t\t\t\t...tenantDbCredentials.read,\n\t\t\t\t\t\tpool: {\n\t\t\t\t\t\t\t...tenantDbCredentials.pool,\n\t\t\t\t\t\t\t...tenantDbCredentials.read.pool,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\terr => logger.error(err),\n\t\t\t\t\t{ retryStaleConnection: true },\n\t\t\t\t)\n\t\t\t})\n\t\t\t.addService('projectSchemaResolver', () => new ProjectSchemaResolverProxy())\n\t\t\t.addService('projectInitializer', () => new ProjectInitializerProxy())\n\t\t\t.addService(\n\t\t\t\t'tenantContainer',\n\t\t\t\t({ tenantConnection, tenantReadConnection, tenantDbCredentials, projectSchemaResolver, projectInitializer, logger }) => {\n\t\t\t\t\tconst encryptionKey = config.secrets.encryptionKey\n\t\t\t\t\t\t? createSecretKey(Buffer.from(config.secrets.encryptionKey, 'hex'))\n\t\t\t\t\t\t: undefined\n\n\t\t\t\t\tconst cryptoWrapper = new CryptoWrapper(encryptionKey)\n\t\t\t\t\treturn this.tenantContainerFactory.create({\n\t\t\t\t\t\tconnection: tenantConnection,\n\t\t\t\t\t\treadConnection: tenantReadConnection,\n\t\t\t\t\t\tdbCredentials: tenantDbCredentials,\n\t\t\t\t\t\tmailOptions: config.mailer,\n\t\t\t\t\t\ttenantCredentials: {\n\t\t\t\t\t\t\t...config.credentials,\n\t\t\t\t\t\t\trootTokens: normalizeTokenList(config.credentials.rootTokens),\n\t\t\t\t\t\t\trootTokenHashes: normalizeTokenList(config.credentials.rootTokenHashes),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprojectInitializer,\n\t\t\t\t\t\tprojectSchemaResolver,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\tcryptoProviders: {\n\t\t\t\t\t\t\tdecrypt: cryptoWrapper.decrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencrypt: cryptoWrapper.encrypt.bind(cryptoWrapper),\n\t\t\t\t\t\t\tencryptionEnabled: cryptoWrapper.enabled,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdataSigner: cryptoWrapper.enabled ? (purpose, value) => cryptoWrapper.sign(purpose, value) : null,\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t)\n\t\t\t.addService('tenantDatabase', ({ tenantContainer }) => tenantContainer.databaseContext)\n\t\t\t.addService('tenantReadDatabase', ({ tenantContainer }) => tenantContainer.readDatabaseContext)\n\t\t\t.addService('identityFetcher', ({ tenantContainer: { identityFetcher } }) => identityFetcher)\n\t\t\t.addService('systemContainer', ({ identityFetcher }) => this.systemContainerFactory.create({ identityFetcher }))\n\t\t\t.addService('schemaProvider', ({ systemContainer }) => systemContainer.schemaProvider)\n\t\t\t.addService('projectContainerFactory', ({ schemaProvider, logger }) => this.projectContainerFactoryFactory.create(schemaProvider, logger))\n\t\t\t.addService('tenantProjectManager', ({ tenantContainer }) => tenantContainer.projectManager)\n\t\t\t.addService('tenantProjectMemberManager', ({ tenantContainer }) => tenantContainer.projectMemberManager)\n\t\t\t.addService('projectContainerResolver', ({ projectContainerFactory, tenantProjectManager, tenantReadDatabase }) =>\n\t\t\t\tnew ProjectContainerResolver(\n\t\t\t\t\tprojectContainerFactory,\n\t\t\t\t\tthis.projectConfigResolver,\n\t\t\t\t\ttenantProjectManager,\n\t\t\t\t\ttenantReadDatabase,\n\t\t\t\t\tconfig,\n\t\t\t\t))\n\t\t\t.setupService('projectSchemaResolver', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setResolver(new ProjectSchemaResolver(projectContainerResolver))\n\t\t\t})\n\t\t\t.setupService('projectInitializer', (it, { projectContainerResolver }) => {\n\t\t\t\tit.setInitializer(new ProjectInitializer(projectContainerResolver))\n\t\t\t})\n\t\t\t.addService('tenantGraphQLHandler', ({ tenantContainer }) => this.tenantGraphQLHandlerFactory.create(tenantContainer.resolvers))\n\t\t\t.addService('systemGraphQLHandler', ({ systemContainer }) => this.systemGraphQLHandlerFactory.create(systemContainer.systemResolversFactory))\n\t\t\t.addService(\n\t\t\t\t'authenticator',\n\t\t\t\t({ tenantDatabase, tenantReadDatabase, tenantContainer }) =>\n\t\t\t\t\tnew Authenticator(tenantDatabase, tenantReadDatabase, tenantContainer.apiKeyManager, this.geoCountryHeader),\n\t\t\t)\n\t\t\t.addService(\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t({ tenantProjectMemberManager, tenantReadDatabase }) =>\n\t\t\t\t\tnew ProjectMembershipResolver(this.debug, new ProjectMembershipFetcher(tenantProjectMemberManager, tenantReadDatabase)),\n\t\t\t)\n\t\t\t.build()\n\t\t\t.pick(\n\t\t\t\t'projectContainerResolver',\n\t\t\t\t'projectSchemaResolver',\n\t\t\t\t'projectInitializer',\n\t\t\t\t'systemContainer',\n\t\t\t\t'systemGraphQLHandler',\n\t\t\t\t'tenantContainer',\n\t\t\t\t'authenticator',\n\t\t\t\t'projectMembershipResolver',\n\t\t\t\t'tenantGraphQLHandler',\n\t\t\t\t'slug',\n\t\t\t\t'logger',\n\t\t\t)\n\t}\n}\n"],"names":["slug"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,MAAM,qBAAqB,CAAC,UAAiF;AAC5G,MAAI,UAAU,QAAW;AACxB,WAAO;AAAA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
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const
|
|
3
|
+
const utilities = require("@contember/utilities");
|
|
4
4
|
const bcrypt = require("bcryptjs");
|
|
5
5
|
const crypto = require("node:crypto");
|
|
6
6
|
const createProviders = () => ({
|
|
7
|
-
uuid: ({ version = 4 } = {}) => version === 4 ?
|
|
7
|
+
uuid: ({ version = 4 } = {}) => version === 4 ? utilities.generateUuidV4() : utilities.generateUuidV7(),
|
|
8
8
|
now: () => /* @__PURE__ */ new Date(),
|
|
9
9
|
bcrypt: async (value) => await bcrypt.hash(value, 10),
|
|
10
10
|
bcryptCompare: (data, hash) => bcrypt.compare(data, hash),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.cjs","sources":["../../../../packages/engine-http/src/providers.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"providers.cjs","sources":["../../../../packages/engine-http/src/providers.ts"],"sourcesContent":["import { generateUuidV4, generateUuidV7 } from '@contember/utilities'\nimport bcrypt from 'bcryptjs'\nimport crypto, { BinaryLike } from 'node:crypto'\n\nexport const createProviders = () => ({\n\tuuid: ({ version = 4 }: { version?: 4 | 7 } = {}) => version === 4 ? generateUuidV4() : generateUuidV7(),\n\tnow: () => new Date(),\n\tbcrypt: async (value: string) => await bcrypt.hash(value, 10),\n\tbcryptCompare: (data: any, hash: string) => bcrypt.compare(data, hash),\n\trandomBytes: async (bytes: number) =>\n\t\tawait new Promise<Buffer>((resolve, reject) => {\n\t\t\tcrypto.randomBytes(bytes, (error, buffer) => {\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error)\n\t\t\t\t} else {\n\t\t\t\t\tresolve(buffer)\n\t\t\t\t}\n\t\t\t})\n\t\t}),\n\thash: (value: BinaryLike, algo: string): Buffer => (\n\t\tcrypto.createHash(algo).update(value).digest()\n\t),\n})\n\nexport type Providers = ReturnType<typeof createProviders>\n"],"names":["generateUuidV4","generateUuidV7"],"mappings":";;;;;AAIO,MAAM,kBAAkB,OAAO;AAAA,EACrC,MAAM,CAAC,EAAE,UAAU,EAAA,IAA2B,OAAO,YAAY,IAAIA,yBAAA,IAAmBC,yBAAA;AAAA,EACxF,KAAK,MAAM,oBAAI,KAAA;AAAA,EACf,QAAQ,OAAO,UAAkB,MAAM,OAAO,KAAK,OAAO,EAAE;AAAA,EAC5D,eAAe,CAAC,MAAW,SAAiB,OAAO,QAAQ,MAAM,IAAI;AAAA,EACrE,aAAa,OAAO,UACnB,MAAM,IAAI,QAAgB,CAAC,SAAS,WAAW;AAC9C,WAAO,YAAY,OAAO,CAAC,OAAO,WAAW;AAC5C,UAAI,OAAO;AACV,eAAO,KAAK;AAAA,MACb,OAAO;AACN,gBAAQ,MAAM;AAAA,MACf;AAAA,IACD,CAAC;AAAA,EACF,CAAC;AAAA,EACF,MAAM,CAAC,OAAmB,SACzB,OAAO,WAAW,IAAI,EAAE,OAAO,KAAK,EAAE,OAAA;AAExC;;"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { generateUuidV4, generateUuidV7 } from "@contember/utilities";
|
|
2
2
|
import bcrypt from "bcryptjs";
|
|
3
3
|
import crypto__default from "node:crypto";
|
|
4
4
|
const createProviders = () => ({
|
|
5
|
-
uuid: ({ version = 4 } = {}) => version === 4 ?
|
|
5
|
+
uuid: ({ version = 4 } = {}) => version === 4 ? generateUuidV4() : generateUuidV7(),
|
|
6
6
|
now: () => /* @__PURE__ */ new Date(),
|
|
7
7
|
bcrypt: async (value) => await bcrypt.hash(value, 10),
|
|
8
8
|
bcryptCompare: (data, hash) => bcrypt.compare(data, hash),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers.js","sources":["../../../../packages/engine-http/src/providers.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"providers.js","sources":["../../../../packages/engine-http/src/providers.ts"],"sourcesContent":["import { generateUuidV4, generateUuidV7 } from '@contember/utilities'\nimport bcrypt from 'bcryptjs'\nimport crypto, { BinaryLike } from 'node:crypto'\n\nexport const createProviders = () => ({\n\tuuid: ({ version = 4 }: { version?: 4 | 7 } = {}) => version === 4 ? generateUuidV4() : generateUuidV7(),\n\tnow: () => new Date(),\n\tbcrypt: async (value: string) => await bcrypt.hash(value, 10),\n\tbcryptCompare: (data: any, hash: string) => bcrypt.compare(data, hash),\n\trandomBytes: async (bytes: number) =>\n\t\tawait new Promise<Buffer>((resolve, reject) => {\n\t\t\tcrypto.randomBytes(bytes, (error, buffer) => {\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error)\n\t\t\t\t} else {\n\t\t\t\t\tresolve(buffer)\n\t\t\t\t}\n\t\t\t})\n\t\t}),\n\thash: (value: BinaryLike, algo: string): Buffer => (\n\t\tcrypto.createHash(algo).update(value).digest()\n\t),\n})\n\nexport type Providers = ReturnType<typeof createProviders>\n"],"names":["crypto"],"mappings":";;;AAIO,MAAM,kBAAkB,OAAO;AAAA,EACrC,MAAM,CAAC,EAAE,UAAU,EAAA,IAA2B,OAAO,YAAY,IAAI,eAAA,IAAmB,eAAA;AAAA,EACxF,KAAK,MAAM,oBAAI,KAAA;AAAA,EACf,QAAQ,OAAO,UAAkB,MAAM,OAAO,KAAK,OAAO,EAAE;AAAA,EAC5D,eAAe,CAAC,MAAW,SAAiB,OAAO,QAAQ,MAAM,IAAI;AAAA,EACrE,aAAa,OAAO,UACnB,MAAM,IAAI,QAAgB,CAAC,SAAS,WAAW;AAC9CA,oBAAO,YAAY,OAAO,CAAC,OAAO,WAAW;AAC5C,UAAI,OAAO;AACV,eAAO,KAAK;AAAA,MACb,OAAO;AACN,gBAAQ,MAAM;AAAA,MACf;AAAA,IACD,CAAC;AAAA,EACF,CAAC;AAAA,EACF,MAAM,CAAC,OAAmB,SACzBA,gBAAO,WAAW,IAAI,EAAE,OAAO,KAAK,EAAE,OAAA;AAExC;"}
|
|
@@ -5,10 +5,10 @@ require("ipaddr.js");
|
|
|
5
5
|
require("@contember/engine-tenant-api");
|
|
6
6
|
const CommandStream = require("./CommandStream.cjs");
|
|
7
7
|
const ImportExecutor = require("./ImportExecutor.cjs");
|
|
8
|
-
const
|
|
8
|
+
const zlib = require("node:zlib");
|
|
9
9
|
const node_stream = require("node:stream");
|
|
10
10
|
const readImportCommands = (body, isGzip) => {
|
|
11
|
-
return CommandStream.fromBuffer(isGzip ? node_stream.pipeline(body,
|
|
11
|
+
return CommandStream.fromBuffer(isGzip ? node_stream.pipeline(body, zlib.createGunzip(), () => {
|
|
12
12
|
}) : body);
|
|
13
13
|
};
|
|
14
14
|
class ImportApiMiddlewareFactory {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ImportApiMiddlewareFactory.cjs","sources":["../../../../../packages/engine-http/src/transfer/ImportApiMiddlewareFactory.ts"],"sourcesContent":["import { HttpController } from '../application/index.js'\nimport { HttpErrorResponse } from '../common/index.js'\nimport { fromBuffer } from './CommandStream.js'\nimport { ImportError, ImportExecutor } from './ImportExecutor.js'\nimport { createGunzip } from 'node:zlib'\nimport { pipeline, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { Command } from './Command.js'\n\nexport const readImportCommands = (body: Readable, isGzip: boolean): AsyncIterable<Command> => {\n\t// pipe() would not pass on an aborted request, and the import would wait for the rest of the body forever;\n\t// pipeline() destroys the gunzip with the error, which rejects the read. The callback only satisfies the API.\n\treturn fromBuffer(isGzip ? pipeline(body, createGunzip(), () => {}) : body)\n}\n\nexport class ImportApiMiddlewareFactory {\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly importExecutor: ImportExecutor,\n\t) {\n\t}\n\n\tcreate(): HttpController {\n\t\treturn async ctx => {\n\t\t\tconst { projectGroup, authResult, koa } = ctx\n\t\t\tconst { request, response } = koa\n\t\t\tif (!authResult) {\n\t\t\t\treturn new HttpErrorResponse(401, 'Authentication required')\n\t\t\t}\n\n\t\t\tif (request.headers['content-type'] !== 'application/x-ndjson') {\n\t\t\t\tthrow new HttpErrorResponse(400, `Unsupported content type`)\n\t\t\t}\n\n\t\t\tif (request.headers['content-encoding'] !== undefined && request.headers['content-encoding'] !== 'gzip') {\n\t\t\t\tthrow new HttpErrorResponse(415, `Unsupported content encoding`)\n\t\t\t}\n\n\t\t\tresponse.headers['Content-Type'] = 'application/json'\n\n\t\t\ttry {\n\t\t\t\tconst isGzip = request.headers['content-encoding'] === 'gzip'\n\t\t\t\tconst commands = readImportCommands(request.req, isGzip)\n\t\t\t\tawait this.importExecutor.import(projectGroup, authResult, commands)\n\t\t\t\tresponse.status = 200\n\t\t\t\tresponse.body = { ok: true }\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof ImportError) {\n\t\t\t\t\tresponse.status = 400\n\t\t\t\t\tresponse.body = { ok: false, error: e.message }\n\t\t\t\t} else {\n\t\t\t\t\tthrow e\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"],"names":["fromBuffer","pipeline","createGunzip","HttpErrorResponse","ImportError"],"mappings":";;;;;;;;;AASO,MAAM,qBAAqB,CAAC,MAAgB,WAA4C;AAG9F,SAAOA,cAAAA,WAAW,SAASC,YAAAA,SAAS,MAAMC,
|
|
1
|
+
{"version":3,"file":"ImportApiMiddlewareFactory.cjs","sources":["../../../../../packages/engine-http/src/transfer/ImportApiMiddlewareFactory.ts"],"sourcesContent":["import { HttpController } from '../application/index.js'\nimport { HttpErrorResponse } from '../common/index.js'\nimport { fromBuffer } from './CommandStream.js'\nimport { ImportError, ImportExecutor } from './ImportExecutor.js'\nimport { createGunzip } from 'node:zlib'\nimport { pipeline, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { Command } from './Command.js'\n\nexport const readImportCommands = (body: Readable, isGzip: boolean): AsyncIterable<Command> => {\n\t// pipe() would not pass on an aborted request, and the import would wait for the rest of the body forever;\n\t// pipeline() destroys the gunzip with the error, which rejects the read. The callback only satisfies the API.\n\treturn fromBuffer(isGzip ? pipeline(body, createGunzip(), () => {}) : body)\n}\n\nexport class ImportApiMiddlewareFactory {\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly importExecutor: ImportExecutor,\n\t) {\n\t}\n\n\tcreate(): HttpController {\n\t\treturn async ctx => {\n\t\t\tconst { projectGroup, authResult, koa } = ctx\n\t\t\tconst { request, response } = koa\n\t\t\tif (!authResult) {\n\t\t\t\treturn new HttpErrorResponse(401, 'Authentication required')\n\t\t\t}\n\n\t\t\tif (request.headers['content-type'] !== 'application/x-ndjson') {\n\t\t\t\tthrow new HttpErrorResponse(400, `Unsupported content type`)\n\t\t\t}\n\n\t\t\tif (request.headers['content-encoding'] !== undefined && request.headers['content-encoding'] !== 'gzip') {\n\t\t\t\tthrow new HttpErrorResponse(415, `Unsupported content encoding`)\n\t\t\t}\n\n\t\t\tresponse.headers['Content-Type'] = 'application/json'\n\n\t\t\ttry {\n\t\t\t\tconst isGzip = request.headers['content-encoding'] === 'gzip'\n\t\t\t\tconst commands = readImportCommands(request.req, isGzip)\n\t\t\t\tawait this.importExecutor.import(projectGroup, authResult, commands)\n\t\t\t\tresponse.status = 200\n\t\t\t\tresponse.body = { ok: true }\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof ImportError) {\n\t\t\t\t\tresponse.status = 400\n\t\t\t\t\tresponse.body = { ok: false, error: e.message }\n\t\t\t\t} else {\n\t\t\t\t\tthrow e\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"],"names":["fromBuffer","pipeline","createGunzip","HttpErrorResponse","ImportError"],"mappings":";;;;;;;;;AASO,MAAM,qBAAqB,CAAC,MAAgB,WAA4C;AAG9F,SAAOA,cAAAA,WAAW,SAASC,YAAAA,SAAS,MAAMC,KAAAA,aAAA,GAAgB,MAAM;AAAA,EAAC,CAAC,IAAI,IAAI;AAC3E;AAEO,MAAM,2BAA2B;AAAA,EACvC,YACkB,sBACA,gBAChB;AAFgB,SAAA,uBAAA;AACA,SAAA,iBAAA;AAAA,EAElB;AAAA,EAEA,SAAyB;AACxB,WAAO,OAAM,QAAO;AACnB,YAAM,EAAE,cAAc,YAAY,IAAA,IAAQ;AAC1C,YAAM,EAAE,SAAS,SAAA,IAAa;AAC9B,UAAI,CAAC,YAAY;AAChB,eAAO,IAAIC,aAAAA,kBAAkB,KAAK,yBAAyB;AAAA,MAC5D;AAEA,UAAI,QAAQ,QAAQ,cAAc,MAAM,wBAAwB;AAC/D,cAAM,IAAIA,aAAAA,kBAAkB,KAAK,0BAA0B;AAAA,MAC5D;AAEA,UAAI,QAAQ,QAAQ,kBAAkB,MAAM,UAAa,QAAQ,QAAQ,kBAAkB,MAAM,QAAQ;AACxG,cAAM,IAAIA,aAAAA,kBAAkB,KAAK,8BAA8B;AAAA,MAChE;AAEA,eAAS,QAAQ,cAAc,IAAI;AAEnC,UAAI;AACH,cAAM,SAAS,QAAQ,QAAQ,kBAAkB,MAAM;AACvD,cAAM,WAAW,mBAAmB,QAAQ,KAAK,MAAM;AACvD,cAAM,KAAK,eAAe,OAAO,cAAc,YAAY,QAAQ;AACnE,iBAAS,SAAS;AAClB,iBAAS,OAAO,EAAE,IAAI,KAAA;AAAA,MACvB,SAAS,GAAG;AACX,YAAI,aAAaC,eAAAA,aAAa;AAC7B,mBAAS,SAAS;AAClB,mBAAS,OAAO,EAAE,IAAI,OAAO,OAAO,EAAE,QAAA;AAAA,QACvC,OAAO;AACN,gBAAM;AAAA,QACP;AAAA,MACD;AAAA,IACD;AAAA,EACD;AACD;;;"}
|
|
@@ -4,6 +4,7 @@ const Database = require("@contember/database");
|
|
|
4
4
|
const schema = require("@contember/schema");
|
|
5
5
|
const Typesafe = require("@contember/typesafe");
|
|
6
6
|
const engineSystemApi = require("@contember/engine-system-api");
|
|
7
|
+
const engineContentApi = require("@contember/engine-content-api");
|
|
7
8
|
const HttpResponse = require("../common/HttpResponse.cjs");
|
|
8
9
|
require("ipaddr.js");
|
|
9
10
|
require("@contember/engine-tenant-api");
|
|
@@ -65,6 +66,13 @@ const listType = (arrayType) => {
|
|
|
65
66
|
return arrayType(input, path);
|
|
66
67
|
};
|
|
67
68
|
};
|
|
69
|
+
const calendarDate = (input, path = []) => {
|
|
70
|
+
const value = Typesafe__namespace.string(input, path);
|
|
71
|
+
if (engineContentApi.isImpossibleCalendarDate(value)) {
|
|
72
|
+
throw new Typesafe.ParseError(path, `${JSON.stringify(value)} is not a valid date`);
|
|
73
|
+
}
|
|
74
|
+
return value;
|
|
75
|
+
};
|
|
68
76
|
class CommandIterator {
|
|
69
77
|
constructor(commandName, commandArgs, commandIterator) {
|
|
70
78
|
this.commandName = commandName;
|
|
@@ -131,6 +139,7 @@ class ImportExecutor {
|
|
|
131
139
|
await this.requireImportAccess(groupContainer, contentSchema.schema, authResult, options.project, "content");
|
|
132
140
|
const contentDatabaseClient = projectContainer.connection.createClient(stage.schema, {});
|
|
133
141
|
const mapping = this.contentSchemaTransferMappingFactory.createContentSchemaMapping(contentSchema.schema);
|
|
142
|
+
this.requireMappedTables(mapping, options.tables, `content schema of project ${options.project}`);
|
|
134
143
|
return await contentDatabaseClient.transaction(async (db) => {
|
|
135
144
|
await this.disableTimeouts(db);
|
|
136
145
|
await this.disableTriggers(db, options.tables);
|
|
@@ -158,6 +167,7 @@ class ImportExecutor {
|
|
|
158
167
|
await this.requireImportAccess(groupContainer, schema2, authResult, options.project, "system");
|
|
159
168
|
const systemDatabaseContext = projectContainer.systemDatabaseContext;
|
|
160
169
|
const mapping = this.systemSchemaTransferMappingFactory.build();
|
|
170
|
+
this.requireMappedTables(mapping, options.tables, `system schema of project ${options.project}`);
|
|
161
171
|
return await systemDatabaseContext.client.transaction(async (db) => {
|
|
162
172
|
await this.disableTimeouts(db);
|
|
163
173
|
await this.truncateTables(db, options.tables);
|
|
@@ -171,6 +181,9 @@ class ImportExecutor {
|
|
|
171
181
|
}
|
|
172
182
|
async importSequence(db, mapping, it) {
|
|
173
183
|
const [options] = it.commandArgs;
|
|
184
|
+
if (!Object.hasOwn(mapping.tables, options.table) || !Object.hasOwn(mapping.tables[options.table].columns, options.column)) {
|
|
185
|
+
throw new ImportError(`Unknown column ${options.table}.${options.column}`);
|
|
186
|
+
}
|
|
174
187
|
await db.query(
|
|
175
188
|
"SELECT setval(pg_get_serial_sequence(?, ?), ?)",
|
|
176
189
|
[`${db.schema}.${options.table}`, options.column, options.value]
|
|
@@ -189,7 +202,13 @@ class ImportExecutor {
|
|
|
189
202
|
insertContext.rows.push(insertContext.rowParser(values));
|
|
190
203
|
} catch (e) {
|
|
191
204
|
if (e instanceof Typesafe.ParseError) {
|
|
192
|
-
|
|
205
|
+
const rowNumber = insertContext.insertedRowCount + insertContext.rows.length + 1;
|
|
206
|
+
const [columnIndex, ...valuePath] = e.path;
|
|
207
|
+
const columnName = columnIndex !== void 0 ? options.columns[Number(columnIndex)] : void 0;
|
|
208
|
+
const elementLocation = valuePath.length > 0 ? `, element /${valuePath.map(String).join("/")}` : "";
|
|
209
|
+
const location = columnName !== void 0 ? `table ${options.table}, column ${columnName}${elementLocation}` : `table ${options.table}`;
|
|
210
|
+
const reason = columnName !== void 0 ? e.reason : e.message;
|
|
211
|
+
throw new ImportError(`Invalid row #${rowNumber} ${JSON.stringify(values)} for ${location}: ${reason}`);
|
|
193
212
|
} else {
|
|
194
213
|
throw e;
|
|
195
214
|
}
|
|
@@ -237,6 +256,14 @@ class ImportExecutor {
|
|
|
237
256
|
throw new HttpResponse.HttpErrorResponse(403, `You are not allowed to import ${kind} in ${projectSlug}`);
|
|
238
257
|
}
|
|
239
258
|
}
|
|
259
|
+
/** The tables an import truncates must come from the same mapping an export of this schema lists. */
|
|
260
|
+
requireMappedTables(mapping, tableNames, target) {
|
|
261
|
+
for (const tableName of tableNames) {
|
|
262
|
+
if (!Object.hasOwn(mapping.tables, tableName)) {
|
|
263
|
+
throw new ImportError(`Table ${tableName} is not part of the ${target}`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
240
267
|
async fetchStageBySlug(systemDatabaseContext, projectSlug, stageSlug) {
|
|
241
268
|
const stage = await systemDatabaseContext.queryHandler.fetch(new engineSystemApi.StageBySlugQuery(stageSlug));
|
|
242
269
|
if (stage === null) {
|
|
@@ -280,13 +307,13 @@ class ImportExecutor {
|
|
|
280
307
|
return await db.query(sql, parameters);
|
|
281
308
|
}
|
|
282
309
|
async buildInsertContext(db, mapping, schema2, tableName, columnNames) {
|
|
283
|
-
const tableMapping = mapping.tables[tableName];
|
|
310
|
+
const tableMapping = Object.hasOwn(mapping.tables, tableName) ? mapping.tables[tableName] : void 0;
|
|
284
311
|
const columns = [];
|
|
285
312
|
if (tableMapping === void 0) {
|
|
286
313
|
throw new ImportError(`Unknown table ${tableName}`);
|
|
287
314
|
}
|
|
288
315
|
for (const columnName of columnNames) {
|
|
289
|
-
const column = tableMapping.columns[columnName];
|
|
316
|
+
const column = Object.hasOwn(tableMapping.columns, columnName) ? tableMapping.columns[columnName] : void 0;
|
|
290
317
|
if (column === void 0) {
|
|
291
318
|
throw new ImportError(`Unknown column ${tableName}.${columnName}`);
|
|
292
319
|
}
|
|
@@ -325,13 +352,14 @@ class ImportExecutor {
|
|
|
325
352
|
case schema.Model.ColumnType.Uuid:
|
|
326
353
|
case schema.Model.ColumnType.String:
|
|
327
354
|
case schema.Model.ColumnType.Enum:
|
|
328
|
-
case schema.Model.ColumnType.DateTime:
|
|
329
355
|
case schema.Model.ColumnType.Time:
|
|
330
|
-
case schema.Model.ColumnType.Date:
|
|
331
356
|
case schema.Model.ColumnType.Json:
|
|
332
357
|
// Numeric is transferred as a string to avoid JS float precision loss.
|
|
333
358
|
case schema.Model.ColumnType.Numeric:
|
|
334
359
|
return column.list ? listType(Typesafe__namespace.array(Typesafe__namespace.string)) : Typesafe__namespace.string;
|
|
360
|
+
case schema.Model.ColumnType.Date:
|
|
361
|
+
case schema.Model.ColumnType.DateTime:
|
|
362
|
+
return column.list ? listType(Typesafe__namespace.array(calendarDate)) : calendarDate;
|
|
335
363
|
case schema.Model.ColumnType.Int:
|
|
336
364
|
case schema.Model.ColumnType.Double:
|
|
337
365
|
return column.list ? listType(Typesafe__namespace.array(Typesafe__namespace.number)) : Typesafe__namespace.number;
|