@contember/engine-http 2.1.0-alpha.2 → 2.1.0-alpha.20
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 +0 -2
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +0 -2
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/MasterContainer.cjs +1 -2
- package/dist/development/src/MasterContainer.cjs.map +1 -1
- package/dist/development/src/MasterContainer.js +1 -2
- package/dist/development/src/MasterContainer.js.map +1 -1
- package/dist/development/src/application/application.cjs +31 -13
- package/dist/development/src/application/application.cjs.map +1 -1
- package/dist/development/src/application/application.js +31 -13
- package/dist/development/src/application/application.js.map +1 -1
- package/dist/development/src/content/ProjectMembershipResolver.cjs +2 -2
- package/dist/development/src/content/ProjectMembershipResolver.cjs.map +1 -1
- package/dist/development/src/content/ProjectMembershipResolver.js +2 -2
- package/dist/development/src/content/ProjectMembershipResolver.js.map +1 -1
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs +13 -7
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.js +13 -7
- package/dist/development/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
- package/dist/development/src/utils/remoteAddress.cjs +58 -0
- package/dist/development/src/utils/remoteAddress.cjs.map +1 -0
- package/dist/development/src/utils/remoteAddress.js +58 -0
- package/dist/development/src/utils/remoteAddress.js.map +1 -0
- package/dist/production/index.cjs +0 -2
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +0 -2
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/MasterContainer.cjs +1 -2
- package/dist/production/src/MasterContainer.cjs.map +1 -1
- package/dist/production/src/MasterContainer.js +1 -2
- package/dist/production/src/MasterContainer.js.map +1 -1
- package/dist/production/src/application/application.cjs +31 -13
- package/dist/production/src/application/application.cjs.map +1 -1
- package/dist/production/src/application/application.js +31 -13
- package/dist/production/src/application/application.js.map +1 -1
- package/dist/production/src/content/ProjectMembershipResolver.cjs +2 -2
- package/dist/production/src/content/ProjectMembershipResolver.cjs.map +1 -1
- package/dist/production/src/content/ProjectMembershipResolver.js +2 -2
- package/dist/production/src/content/ProjectMembershipResolver.js.map +1 -1
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs +13 -7
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.js +13 -7
- package/dist/production/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
- package/dist/production/src/utils/remoteAddress.cjs +58 -0
- package/dist/production/src/utils/remoteAddress.cjs.map +1 -0
- package/dist/production/src/utils/remoteAddress.js +58 -0
- package/dist/production/src/utils/remoteAddress.js.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +1 -3
- package/dist/types/MasterContainer.d.ts.map +1 -1
- package/dist/types/application/application.d.ts +1 -0
- package/dist/types/application/application.d.ts.map +1 -1
- package/dist/types/tenant/TenantApiMiddlewareFactory.d.ts +0 -6
- package/dist/types/tenant/TenantApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/types/tenant/index.d.ts +0 -1
- package/dist/types/tenant/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/remoteAddress.d.ts +3 -0
- package/dist/types/utils/remoteAddress.d.ts.map +1 -0
- package/package.json +16 -15
- package/src/MasterContainer.ts +3 -5
- package/src/application/application.ts +32 -13
- package/src/content/ProjectMembershipResolver.ts +2 -2
- package/src/tenant/TenantApiMiddlewareFactory.ts +15 -10
- package/src/tenant/index.ts +0 -1
- package/src/utils/remoteAddress.ts +70 -0
- package/dist/development/src/tenant/TenantGraphQLContextFactory.cjs +0 -19
- package/dist/development/src/tenant/TenantGraphQLContextFactory.cjs.map +0 -1
- package/dist/development/src/tenant/TenantGraphQLContextFactory.js +0 -19
- package/dist/development/src/tenant/TenantGraphQLContextFactory.js.map +0 -1
- package/dist/production/src/tenant/TenantGraphQLContextFactory.cjs +0 -19
- package/dist/production/src/tenant/TenantGraphQLContextFactory.cjs.map +0 -1
- package/dist/production/src/tenant/TenantGraphQLContextFactory.js +0 -19
- package/dist/production/src/tenant/TenantGraphQLContextFactory.js.map +0 -1
- package/dist/types/tenant/TenantGraphQLContextFactory.d.ts +0 -12
- package/dist/types/tenant/TenantGraphQLContextFactory.d.ts.map +0 -1
- package/src/tenant/TenantGraphQLContextFactory.ts +0 -24
|
@@ -9,6 +9,9 @@ import bodyParser from "koa-bodyparser";
|
|
|
9
9
|
import corsMiddleware from "@koa/cors";
|
|
10
10
|
import { Readable } from "node:stream";
|
|
11
11
|
import { URL } from "node:url";
|
|
12
|
+
import { cpuUsage, memoryUsage } from "node:process";
|
|
13
|
+
import { performance } from "node:perf_hooks";
|
|
14
|
+
import { getClientIP } from "../utils/remoteAddress.js";
|
|
12
15
|
var __defProp = Object.defineProperty;
|
|
13
16
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
14
17
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
@@ -92,13 +95,14 @@ class Application {
|
|
|
92
95
|
let webSocketContext = null;
|
|
93
96
|
let requestLogger = this.logger;
|
|
94
97
|
const { timer, send: sendTimer } = this.createTimer();
|
|
98
|
+
const clientIp = getClientIP(req);
|
|
95
99
|
try {
|
|
96
100
|
const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
|
|
97
101
|
const matchedRequest = this.matchRequest(this.websocketRoutes, url);
|
|
98
102
|
if (!matchedRequest) {
|
|
99
103
|
throw new HttpErrorResponse(404, "Route not found");
|
|
100
104
|
}
|
|
101
|
-
requestLogger = this.createRequestLogger(req, void 0, matchedRequest.module);
|
|
105
|
+
requestLogger = this.createRequestLogger(req, void 0, matchedRequest.module, clientIp);
|
|
102
106
|
const groupContainer = await this.projectGroupResolver.resolveContainer({ request: req });
|
|
103
107
|
requestLogger = requestLogger.child({
|
|
104
108
|
projectGroup: groupContainer.slug
|
|
@@ -111,7 +115,7 @@ class Application {
|
|
|
111
115
|
const ws = await new Promise((resolve) => wss.handleUpgrade(req, socket, head, (ws2, request) => {
|
|
112
116
|
resolve(ws2);
|
|
113
117
|
}));
|
|
114
|
-
const wsEstablished =
|
|
118
|
+
const wsEstablished = performance.now();
|
|
115
119
|
webSocketContext = {
|
|
116
120
|
ws,
|
|
117
121
|
abortSignal,
|
|
@@ -119,6 +123,7 @@ class Application {
|
|
|
119
123
|
timer,
|
|
120
124
|
url,
|
|
121
125
|
request: req,
|
|
126
|
+
clientIp,
|
|
122
127
|
authResult,
|
|
123
128
|
params: matchedRequest.params,
|
|
124
129
|
projectGroup: groupContainer
|
|
@@ -127,13 +132,13 @@ class Application {
|
|
|
127
132
|
requestLogger.debug("Websocket connection established");
|
|
128
133
|
ws.on("error", (e) => {
|
|
129
134
|
requestLogger.error(e, {
|
|
130
|
-
websocketOpenMs:
|
|
135
|
+
websocketOpenMs: performance.now() - wsEstablished
|
|
131
136
|
});
|
|
132
137
|
});
|
|
133
138
|
return new Promise((resolve) => {
|
|
134
139
|
ws.on("close", () => {
|
|
135
140
|
requestLogger.debug("Websocket connection closed", {
|
|
136
|
-
websocketOpenMs:
|
|
141
|
+
websocketOpenMs: performance.now() - wsEstablished
|
|
137
142
|
});
|
|
138
143
|
resolve();
|
|
139
144
|
});
|
|
@@ -163,7 +168,8 @@ class Application {
|
|
|
163
168
|
}
|
|
164
169
|
}
|
|
165
170
|
let httpContext = null;
|
|
166
|
-
|
|
171
|
+
const clientIp = getClientIP(ctx.req);
|
|
172
|
+
let requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp);
|
|
167
173
|
const { timer, send: sendTimer } = this.createTimer();
|
|
168
174
|
try {
|
|
169
175
|
if (!matchedRequest) {
|
|
@@ -190,6 +196,7 @@ class Application {
|
|
|
190
196
|
koa: ctx,
|
|
191
197
|
body: ctx.request.body,
|
|
192
198
|
url: ctx.request.URL,
|
|
199
|
+
clientIp,
|
|
193
200
|
logger,
|
|
194
201
|
timer,
|
|
195
202
|
request: ctx.req,
|
|
@@ -227,6 +234,7 @@ class Application {
|
|
|
227
234
|
const response = await this.logger.scope(async (logger) => {
|
|
228
235
|
return await matchedRequest.controller({
|
|
229
236
|
koa: ctx,
|
|
237
|
+
clientIp: getClientIP(ctx.req),
|
|
230
238
|
body: ctx.request.body,
|
|
231
239
|
url: ctx.request.URL,
|
|
232
240
|
logger,
|
|
@@ -268,12 +276,13 @@ class Application {
|
|
|
268
276
|
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + (response.body ?? "")
|
|
269
277
|
);
|
|
270
278
|
}
|
|
271
|
-
createRequestLogger(request, body, module) {
|
|
279
|
+
createRequestLogger(request, body, module, remoteAddress) {
|
|
272
280
|
return this.logger.child({
|
|
273
281
|
method: request.method,
|
|
274
282
|
uri: request.url,
|
|
275
283
|
requestId: Math.random().toString().substring(2),
|
|
276
284
|
module,
|
|
285
|
+
remoteAddress,
|
|
277
286
|
[LoggerRequestBody]: body
|
|
278
287
|
}, {
|
|
279
288
|
handler: FingerCrossedLoggerHandler.factory()
|
|
@@ -281,10 +290,12 @@ class Application {
|
|
|
281
290
|
}
|
|
282
291
|
createTimer() {
|
|
283
292
|
const times = [];
|
|
284
|
-
const globalStart =
|
|
293
|
+
const globalStart = performance.now();
|
|
294
|
+
const cpuUsageStart = cpuUsage();
|
|
295
|
+
const memoryUsageStart = memoryUsage();
|
|
285
296
|
const timer = (name, cb) => {
|
|
286
|
-
const start =
|
|
287
|
-
const time = { label: name, start: start - globalStart };
|
|
297
|
+
const start = performance.now();
|
|
298
|
+
const time = { label: name, start: Math.round(start - globalStart) };
|
|
288
299
|
times.push(time);
|
|
289
300
|
const res = cb();
|
|
290
301
|
if (res instanceof Promise) {
|
|
@@ -293,7 +304,7 @@ class Application {
|
|
|
293
304
|
await res;
|
|
294
305
|
} catch {
|
|
295
306
|
} finally {
|
|
296
|
-
time.duration = (
|
|
307
|
+
time.duration = Math.round(performance.now() - start);
|
|
297
308
|
}
|
|
298
309
|
})();
|
|
299
310
|
}
|
|
@@ -304,15 +315,22 @@ class Application {
|
|
|
304
315
|
ctx.response.setHeader("server-timing", times.map((it) => `${it.label};desc="${it.label} T+${it.start}";dur=${it.duration ?? -1}`).join(", "));
|
|
305
316
|
}
|
|
306
317
|
const emit = () => {
|
|
307
|
-
const total =
|
|
318
|
+
const total = performance.now() - globalStart;
|
|
308
319
|
const timeLabel = total > 500 ? "TIME_SLOW" : "TIME_OK";
|
|
309
320
|
const shouldSuppress = this.suppressAccessLog === true || !ctx.req.url || this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url);
|
|
321
|
+
const cpuUsageEnd = cpuUsage();
|
|
322
|
+
const memoryUsageEnd = memoryUsage();
|
|
323
|
+
const cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1e3;
|
|
324
|
+
const memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed;
|
|
310
325
|
const level = shouldSuppress ? "debug" : "info";
|
|
311
326
|
ctx.logger.log(level, !ctx.response ? "Connection established" : ctx.response.statusCode < 400 ? `Request successful` : "Request failed", {
|
|
312
327
|
status: ctx.response?.statusCode,
|
|
313
328
|
timeLabel,
|
|
314
|
-
totalTimeMs: total,
|
|
315
|
-
events: times
|
|
329
|
+
totalTimeMs: Math.round(total),
|
|
330
|
+
events: times,
|
|
331
|
+
cpuUsageDiffMs,
|
|
332
|
+
memoryUsageDiff,
|
|
333
|
+
responseBodySize: ctx.body && typeof ctx.body === "string" ? ctx.body.length : void 0
|
|
316
334
|
});
|
|
317
335
|
};
|
|
318
336
|
if (ctx.body instanceof Readable) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"application.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { Key, pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\nimport { URL } from 'node:url'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\t wsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\tresolve(ws)\n\t\t\t}))\n\t\t\tconst wsEstablished = new Date().getTime()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: new Date().getTime() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: new Date().getTime() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n` +\n\t\t\tObject.keys(headers)\n\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t.join('\\r\\n') +\n\t\t\t'\\r\\n\\r\\n' +\n\t\t\t(response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = new Date().getTime()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = new Date().getTime()\n\t\t\tconst time: EventTime = { label: name, start: start - globalStart }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = new Date().getTime() - start\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = new Date().getTime() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url || (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: total,\n\t\t\t\t\tevents: times,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst keys: Key[] = []\n\tconst regexp: RegExp = pathToRegexp(mask, keys)\n\n\tconst match = function (url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["ws","match"],"mappings":";;;;;;;;;;;;;;AAkBO,MAAM,YAAY;AAAA,EAUxB,YACkB,sBACA,cACA,WACA,SACA,QAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AAblB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEjD,kBAAA,MAAA,mBAAA;AASD,UAAA,uBAAuB,aAAa,MAAM;AAC3C,SAAA,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAAA,EAAA;AAAA,EAG3H,cAAc,YAAgC;AACxC,SAAA,YAAY,KAAK,UAAU;AAAA,EAAA;AAAA,EAG1B,SAAS,QAAgB,MAAc,YAAkC;AAC/E,SAAK,OAAO,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EAAA;AAAA,EAGK,iBAAiB,QAAgB,MAAc,YAA0C;AAC/F,SAAK,eAAe,KAAK;AAAA,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SACoB;AACpB,QAAM,OAAc,CAAC;AACf,QAAA,SAAiB,aAAa,MAAM,IAAI;AAExC,QAAA,QAAQ,SAAU,KAA4B;AAC7CC,UAAAA,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACHA,aAAAA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IAAA;AAEjF,WAAA;AAAA,EACR;AAEA,SAAO,CAAW,YAAA;AACV,WAAA,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEa,MAAA,oBAAoB,OAAO,aAAa;"}
|
|
1
|
+
{"version":3,"file":"application.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { Key, pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware())\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\t wsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\tresolve(ws)\n\t\t\t}))\n\t\t\tconst wsEstablished = performance.now()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tclientIp,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: performance.now() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t}\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n` +\n\t\t\tObject.keys(headers)\n\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t.join('\\r\\n') +\n\t\t\t'\\r\\n\\r\\n' +\n\t\t\t(response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t[LoggerRequestBody]: body,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = performance.now()\n\t\t\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url || (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst keys: Key[] = []\n\tconst regexp: RegExp = pathToRegexp(mask, keys)\n\n\tconst match = function (url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["ws","match"],"mappings":";;;;;;;;;;;;;;;;;AAqBO,MAAM,YAAY;AAAA,EAUxB,YACkB,sBACA,cACA,WACA,SACA,QAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AAblB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEjD,kBAAA,MAAA,mBAAA;AASD,UAAA,uBAAuB,aAAa,MAAM;AAC3C,SAAA,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAAA,EAAA;AAAA,EAG3H,cAAc,YAAgC;AACxC,SAAA,YAAY,KAAK,UAAU;AAAA,EAAA;AAAA,EAG1B,SAAS,QAAgB,MAAc,YAAkC;AAC/E,SAAK,OAAO,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EAAA;AAAA,EAGK,iBAAiB,QAAgB,MAAc,YAA0C;AAC/F,SAAK,eAAe,KAAK;AAAA,MACxB;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EAAA;AAAA,EAGK,kBAAkB,QAAgB,MAAc,YAAuC;A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AAO,KAAK;AAAA,EAAA;AAAA,EAGd,aAAgB,QAAoB,KAAoC;AAC/E,eAAW,SAAS,QAAQ;AAC3B,YAAM,SAAS,MAAM,MAAM,EAAE,KAAK;AAClC,UAAI,WAAW,MAAM;AACpB,eAAO,EAAE,QAAQ,YAAY,MAAM,YAAY,QAAQ,MAAM,OAAO;AAAA,MAAA;AAAA,IACrE;AAEM,WAAA;AAAA,EAAA;AAET;AA0DA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,OAAc,CAAC;AACf,QAAA,SAAiB,aAAa,MAAM,IAAI;AAExC,QAAA,QAAQ,SAAU,KAA4B;AAC7CC,UAAAA,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACHA,aAAAA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IAAA;AAEjF,WAAA;AAAA,EACR;AAEA,SAAO,CAAW,YAAA;AACV,WAAA,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEa,MAAA,oBAAoB,OAAO,aAAa;"}
|
|
@@ -46,7 +46,7 @@ class ProjectMembershipResolver {
|
|
|
46
46
|
if (assumedMemberships.length === 0) {
|
|
47
47
|
throwNotAllowed();
|
|
48
48
|
}
|
|
49
|
-
const parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity);
|
|
49
|
+
const parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity, true);
|
|
50
50
|
if (parsedMemberships.errors.length > 0) {
|
|
51
51
|
throw new HttpResponse.HttpErrorResponse(
|
|
52
52
|
400,
|
|
@@ -62,7 +62,7 @@ class ProjectMembershipResolver {
|
|
|
62
62
|
return {
|
|
63
63
|
effective: [
|
|
64
64
|
// intentionally ignoring validation errors of stored memberships
|
|
65
|
-
...membershipResolver.resolve(acl, explicitMemberships, identity).memberships,
|
|
65
|
+
...membershipResolver.resolve(acl, explicitMemberships, identity, false).memberships,
|
|
66
66
|
...implicitRolesToAssign.map((it) => ({ role: it, variables: [] }))
|
|
67
67
|
],
|
|
68
68
|
fetched: explicitMemberships
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProjectMembershipResolver.cjs","sources":["../../../../../packages/engine-http/src/content/ProjectMembershipResolver.ts"],"sourcesContent":["import { MembershipMatcher } from '@contember/engine-tenant-api'\nimport * as Typesafe from '@contember/typesafe'\nimport { Acl } from '@contember/schema'\nimport { HttpErrorResponse } from '../common'\nimport { ProjectMembershipFetcher } from './ProjectMembershipFetcher'\nimport { MembershipResolver, ParsedMembership } from '@contember/schema-utils'\n\nconst assumeMembershipHeader = 'x-contember-assume-membership'\n\ninterface HttpRequest {\n\tbody?: unknown\n\tget(header: string): string\n}\n\nexport class ProjectMembershipResolver {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly projectMembershipFetcher: ProjectMembershipFetcher,\n\t) {\n\t}\n\n\tpublic async resolveMemberships({ request, acl, projectSlug, identity }: {\n\t\tacl: Acl.Schema\n\t\trequest: HttpRequest\n\t\tprojectSlug: string\n\t\tidentity: { identityId: string; personId?: string; roles?: readonly string[] }\n\t}): Promise<{ effective: readonly ParsedMembership[]; fetched: readonly Acl.Membership[] }> {\n\n\t\tconst explicitMemberships = await this.projectMembershipFetcher.fetchMemberships(projectSlug, {\n\t\t\tid: identity.identityId,\n\t\t\troles: identity.roles,\n\t\t})\n\n\t\tconst implicitRoles = Object.entries(acl.roles).filter(([, role]) => role.implicit).map(([name]) => name)\n\n\t\tconst throwNotAllowed = () => {\n\t\t\tconst errorMessage = this.debug\n\t\t\t\t? `You are not allowed to access project ${projectSlug}`\n\t\t\t\t: `Project ${projectSlug} NOT found`\n\t\t\tthrow new HttpErrorResponse(404, errorMessage)\n\t\t}\n\n\t\tif (explicitMemberships.length === 0 && implicitRoles.length === 0) {\n\t\t\tthrowNotAllowed()\n\t\t}\n\n\t\tconst membershipResolver = new MembershipResolver()\n\n\t\tconst assumedMemberships = this.readAssumedMemberships(request)\n\t\tif (assumedMemberships !== null) {\n\n\t\t\tif (assumedMemberships.length === 0) {\n\t\t\t\tthrowNotAllowed()\n\t\t\t}\n\n\t\t\tconst parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity)\n\t\t\tif (parsedMemberships.errors.length > 0) {\n\t\t\t\tthrow new HttpErrorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\t`Invalid memberships in ${assumeMembershipHeader} header:\\n` +\n\t\t\t\t\tparsedMemberships.errors.map(it => JSON.stringify(it)).join('\\n'),\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.verifyAssumedRoles(explicitMemberships, acl, assumedMemberships)\n\n\t\t\treturn { effective: parsedMemberships.memberships, fetched: explicitMemberships }\n\t\t}\n\n\n\t\tconst explicitProjectRoles = explicitMemberships.map(it => it.role)\n\t\tconst implicitRolesToAssign = implicitRoles.filter(it => !explicitProjectRoles.includes(it))\n\n\t\treturn {\n\t\t\teffective: [\n\t\t\t\t// intentionally ignoring validation errors of stored memberships\n\t\t\t\t...membershipResolver.resolve(acl, explicitMemberships, identity).memberships,\n\t\t\t\t...implicitRolesToAssign.map(it => ({ role: it, variables: [] })),\n\t\t\t],\n\t\t\tfetched: explicitMemberships,\n\t\t}\n\t}\n\n\tprivate readAssumedMemberships(req: HttpRequest): null | readonly Acl.Membership[] {\n\t\tconst value = this.readAssumeMembershipJson(req)\n\t\tif (value === null) {\n\t\t\treturn null\n\t\t}\n\t\ttry {\n\t\t\treturn assumeMembershipValueType(value).memberships\n\t\t} catch (e: any) {\n\t\t\tthrow new HttpErrorResponse(400, `Invalid format of \"assume membership\": ${e.message}`)\n\t\t}\n\t}\n\n\tprivate readAssumeMembershipJson(req: HttpRequest): unknown {\n\t\tif (typeof req.body === 'object' && req.body !== null && 'assumeMembership' in req.body) {\n\t\t\treturn (req.body as any).assumeMembership\n\t\t}\n\t\tconst value = req.get(assumeMembershipHeader).trim()\n\t\treturn value !== '' ? JSON.parse(value) : null\n\t}\n\n\tprivate verifyAssumedRoles(explicitMemberships: readonly Acl.Membership[], acl: Acl.Schema, assumedMemberships: readonly Acl.Membership[]) {\n\t\tconst membershipMatcher = new MembershipMatcher(explicitMemberships.map(it => ({\n\t\t\t...it,\n\t\t\tmatchRule: acl.roles[it.role].content?.assumeMembership ?? {},\n\t\t})))\n\n\t\tfor (const assumed of assumedMemberships) {\n\t\t\tif (!membershipMatcher.matches(assumed)) {\n\t\t\t\tthrow new HttpErrorResponse(403, `You are not allow to assume membership ${JSON.stringify(assumed)}`)\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst assumeMembershipValueType = Typesafe.object({\n\tmemberships: Typesafe.array(\n\t\tTypesafe.object({\n\t\t\trole: Typesafe.string,\n\t\t\tvariables: Typesafe.array(\n\t\t\t\tTypesafe.object({\n\t\t\t\t\tname: Typesafe.string,\n\t\t\t\t\tvalues: Typesafe.array(Typesafe.string),\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t),\n})\n"],"names":["HttpErrorResponse","MembershipResolver","MembershipMatcher","Typesafe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAOA,MAAM,yBAAyB;AAOxB,MAAM,0BAA0B;AAAA,EACtC,YACkB,OACA,0BAChB;AAFgB,SAAA,QAAA;AACA,SAAA,2BAAA;AAAA,EAAA;AAAA,EAIlB,MAAa,mBAAmB,EAAE,SAAS,KAAK,aAAa,YAK+B;AAE3F,UAAM,sBAAsB,MAAM,KAAK,yBAAyB,iBAAiB,aAAa;AAAA,MAC7F,IAAI,SAAS;AAAA,MACb,OAAO,SAAS;AAAA,IAAA,CAChB;AAEK,UAAA,gBAAgB,OAAO,QAAQ,IAAI,KAAK,EAAE,OAAO,CAAC,CAAA,EAAG,IAAI,MAAM,KAAK,QAAQ,EAAE,IAAI,CAAC,CAAC,IAAI,MAAM,IAAI;AAExG,UAAM,kBAAkB,MAAM;AAC7B,YAAM,eAAe,KAAK,QACvB,yCAAyC,WAAW,KACpD,WAAW,WAAW;AACnB,YAAA,IAAIA,aAAAA,kBAAkB,KAAK,YAAY;AAAA,IAC9C;AAEA,QAAI,oBAAoB,WAAW,KAAK,cAAc,WAAW,GAAG;AACnD,sBAAA;AAAA,IAAA;AAGX,UAAA,qBAAqB,IAAIC,+BAAmB;AAE5C,UAAA,qBAAqB,KAAK,uBAAuB,OAAO;AAC9D,QAAI,uBAAuB,MAAM;AAE5B,UAAA,mBAAmB,WAAW,GAAG;AACpB,wBAAA;AAAA,MAAA;AAGjB,YAAM,oBAAoB,mBAAmB,QAAQ,KAAK,oBAAoB,
|
|
1
|
+
{"version":3,"file":"ProjectMembershipResolver.cjs","sources":["../../../../../packages/engine-http/src/content/ProjectMembershipResolver.ts"],"sourcesContent":["import { MembershipMatcher } from '@contember/engine-tenant-api'\nimport * as Typesafe from '@contember/typesafe'\nimport { Acl } from '@contember/schema'\nimport { HttpErrorResponse } from '../common'\nimport { ProjectMembershipFetcher } from './ProjectMembershipFetcher'\nimport { MembershipResolver, ParsedMembership } from '@contember/schema-utils'\n\nconst assumeMembershipHeader = 'x-contember-assume-membership'\n\ninterface HttpRequest {\n\tbody?: unknown\n\tget(header: string): string\n}\n\nexport class ProjectMembershipResolver {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly projectMembershipFetcher: ProjectMembershipFetcher,\n\t) {\n\t}\n\n\tpublic async resolveMemberships({ request, acl, projectSlug, identity }: {\n\t\tacl: Acl.Schema\n\t\trequest: HttpRequest\n\t\tprojectSlug: string\n\t\tidentity: { identityId: string; personId?: string; roles?: readonly string[] }\n\t}): Promise<{ effective: readonly ParsedMembership[]; fetched: readonly Acl.Membership[] }> {\n\n\t\tconst explicitMemberships = await this.projectMembershipFetcher.fetchMemberships(projectSlug, {\n\t\t\tid: identity.identityId,\n\t\t\troles: identity.roles,\n\t\t})\n\n\t\tconst implicitRoles = Object.entries(acl.roles).filter(([, role]) => role.implicit).map(([name]) => name)\n\n\t\tconst throwNotAllowed = () => {\n\t\t\tconst errorMessage = this.debug\n\t\t\t\t? `You are not allowed to access project ${projectSlug}`\n\t\t\t\t: `Project ${projectSlug} NOT found`\n\t\t\tthrow new HttpErrorResponse(404, errorMessage)\n\t\t}\n\n\t\tif (explicitMemberships.length === 0 && implicitRoles.length === 0) {\n\t\t\tthrowNotAllowed()\n\t\t}\n\n\t\tconst membershipResolver = new MembershipResolver()\n\n\t\tconst assumedMemberships = this.readAssumedMemberships(request)\n\t\tif (assumedMemberships !== null) {\n\n\t\t\tif (assumedMemberships.length === 0) {\n\t\t\t\tthrowNotAllowed()\n\t\t\t}\n\n\t\t\tconst parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity, true)\n\t\t\tif (parsedMemberships.errors.length > 0) {\n\t\t\t\tthrow new HttpErrorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\t`Invalid memberships in ${assumeMembershipHeader} header:\\n` +\n\t\t\t\t\tparsedMemberships.errors.map(it => JSON.stringify(it)).join('\\n'),\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.verifyAssumedRoles(explicitMemberships, acl, assumedMemberships)\n\n\t\t\treturn { effective: parsedMemberships.memberships, fetched: explicitMemberships }\n\t\t}\n\n\n\t\tconst explicitProjectRoles = explicitMemberships.map(it => it.role)\n\t\tconst implicitRolesToAssign = implicitRoles.filter(it => !explicitProjectRoles.includes(it))\n\n\t\treturn {\n\t\t\teffective: [\n\t\t\t\t// intentionally ignoring validation errors of stored memberships\n\t\t\t\t...membershipResolver.resolve(acl, explicitMemberships, identity, false).memberships,\n\t\t\t\t...implicitRolesToAssign.map(it => ({ role: it, variables: [] })),\n\t\t\t],\n\t\t\tfetched: explicitMemberships,\n\t\t}\n\t}\n\n\tprivate readAssumedMemberships(req: HttpRequest): null | readonly Acl.Membership[] {\n\t\tconst value = this.readAssumeMembershipJson(req)\n\t\tif (value === null) {\n\t\t\treturn null\n\t\t}\n\t\ttry {\n\t\t\treturn assumeMembershipValueType(value).memberships\n\t\t} catch (e: any) {\n\t\t\tthrow new HttpErrorResponse(400, `Invalid format of \"assume membership\": ${e.message}`)\n\t\t}\n\t}\n\n\tprivate readAssumeMembershipJson(req: HttpRequest): unknown {\n\t\tif (typeof req.body === 'object' && req.body !== null && 'assumeMembership' in req.body) {\n\t\t\treturn (req.body as any).assumeMembership\n\t\t}\n\t\tconst value = req.get(assumeMembershipHeader).trim()\n\t\treturn value !== '' ? JSON.parse(value) : null\n\t}\n\n\tprivate verifyAssumedRoles(explicitMemberships: readonly Acl.Membership[], acl: Acl.Schema, assumedMemberships: readonly Acl.Membership[]) {\n\t\tconst membershipMatcher = new MembershipMatcher(explicitMemberships.map(it => ({\n\t\t\t...it,\n\t\t\tmatchRule: acl.roles[it.role].content?.assumeMembership ?? {},\n\t\t})))\n\n\t\tfor (const assumed of assumedMemberships) {\n\t\t\tif (!membershipMatcher.matches(assumed)) {\n\t\t\t\tthrow new HttpErrorResponse(403, `You are not allow to assume membership ${JSON.stringify(assumed)}`)\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst assumeMembershipValueType = Typesafe.object({\n\tmemberships: Typesafe.array(\n\t\tTypesafe.object({\n\t\t\trole: Typesafe.string,\n\t\t\tvariables: Typesafe.array(\n\t\t\t\tTypesafe.object({\n\t\t\t\t\tname: Typesafe.string,\n\t\t\t\t\tvalues: Typesafe.array(Typesafe.string),\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t),\n})\n"],"names":["HttpErrorResponse","MembershipResolver","MembershipMatcher","Typesafe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAOA,MAAM,yBAAyB;AAOxB,MAAM,0BAA0B;AAAA,EACtC,YACkB,OACA,0BAChB;AAFgB,SAAA,QAAA;AACA,SAAA,2BAAA;AAAA,EAAA;AAAA,EAIlB,MAAa,mBAAmB,EAAE,SAAS,KAAK,aAAa,YAK+B;AAE3F,UAAM,sBAAsB,MAAM,KAAK,yBAAyB,iBAAiB,aA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AO;AAAA,UACf,MAAMA,oBAAS;AAAA,UACf,QAAQA,oBAAS,MAAMA,oBAAS,MAAM;AAAA,QACtC,CAAA;AAAA,MAAA;AAAA,IAEF,CAAA;AAAA,EAAA;AAEH,CAAC;;"}
|
|
@@ -27,7 +27,7 @@ class ProjectMembershipResolver {
|
|
|
27
27
|
if (assumedMemberships.length === 0) {
|
|
28
28
|
throwNotAllowed();
|
|
29
29
|
}
|
|
30
|
-
const parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity);
|
|
30
|
+
const parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity, true);
|
|
31
31
|
if (parsedMemberships.errors.length > 0) {
|
|
32
32
|
throw new HttpErrorResponse(
|
|
33
33
|
400,
|
|
@@ -43,7 +43,7 @@ class ProjectMembershipResolver {
|
|
|
43
43
|
return {
|
|
44
44
|
effective: [
|
|
45
45
|
// intentionally ignoring validation errors of stored memberships
|
|
46
|
-
...membershipResolver.resolve(acl, explicitMemberships, identity).memberships,
|
|
46
|
+
...membershipResolver.resolve(acl, explicitMemberships, identity, false).memberships,
|
|
47
47
|
...implicitRolesToAssign.map((it) => ({ role: it, variables: [] }))
|
|
48
48
|
],
|
|
49
49
|
fetched: explicitMemberships
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProjectMembershipResolver.js","sources":["../../../../../packages/engine-http/src/content/ProjectMembershipResolver.ts"],"sourcesContent":["import { MembershipMatcher } from '@contember/engine-tenant-api'\nimport * as Typesafe from '@contember/typesafe'\nimport { Acl } from '@contember/schema'\nimport { HttpErrorResponse } from '../common'\nimport { ProjectMembershipFetcher } from './ProjectMembershipFetcher'\nimport { MembershipResolver, ParsedMembership } from '@contember/schema-utils'\n\nconst assumeMembershipHeader = 'x-contember-assume-membership'\n\ninterface HttpRequest {\n\tbody?: unknown\n\tget(header: string): string\n}\n\nexport class ProjectMembershipResolver {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly projectMembershipFetcher: ProjectMembershipFetcher,\n\t) {\n\t}\n\n\tpublic async resolveMemberships({ request, acl, projectSlug, identity }: {\n\t\tacl: Acl.Schema\n\t\trequest: HttpRequest\n\t\tprojectSlug: string\n\t\tidentity: { identityId: string; personId?: string; roles?: readonly string[] }\n\t}): Promise<{ effective: readonly ParsedMembership[]; fetched: readonly Acl.Membership[] }> {\n\n\t\tconst explicitMemberships = await this.projectMembershipFetcher.fetchMemberships(projectSlug, {\n\t\t\tid: identity.identityId,\n\t\t\troles: identity.roles,\n\t\t})\n\n\t\tconst implicitRoles = Object.entries(acl.roles).filter(([, role]) => role.implicit).map(([name]) => name)\n\n\t\tconst throwNotAllowed = () => {\n\t\t\tconst errorMessage = this.debug\n\t\t\t\t? `You are not allowed to access project ${projectSlug}`\n\t\t\t\t: `Project ${projectSlug} NOT found`\n\t\t\tthrow new HttpErrorResponse(404, errorMessage)\n\t\t}\n\n\t\tif (explicitMemberships.length === 0 && implicitRoles.length === 0) {\n\t\t\tthrowNotAllowed()\n\t\t}\n\n\t\tconst membershipResolver = new MembershipResolver()\n\n\t\tconst assumedMemberships = this.readAssumedMemberships(request)\n\t\tif (assumedMemberships !== null) {\n\n\t\t\tif (assumedMemberships.length === 0) {\n\t\t\t\tthrowNotAllowed()\n\t\t\t}\n\n\t\t\tconst parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity)\n\t\t\tif (parsedMemberships.errors.length > 0) {\n\t\t\t\tthrow new HttpErrorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\t`Invalid memberships in ${assumeMembershipHeader} header:\\n` +\n\t\t\t\t\tparsedMemberships.errors.map(it => JSON.stringify(it)).join('\\n'),\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.verifyAssumedRoles(explicitMemberships, acl, assumedMemberships)\n\n\t\t\treturn { effective: parsedMemberships.memberships, fetched: explicitMemberships }\n\t\t}\n\n\n\t\tconst explicitProjectRoles = explicitMemberships.map(it => it.role)\n\t\tconst implicitRolesToAssign = implicitRoles.filter(it => !explicitProjectRoles.includes(it))\n\n\t\treturn {\n\t\t\teffective: [\n\t\t\t\t// intentionally ignoring validation errors of stored memberships\n\t\t\t\t...membershipResolver.resolve(acl, explicitMemberships, identity).memberships,\n\t\t\t\t...implicitRolesToAssign.map(it => ({ role: it, variables: [] })),\n\t\t\t],\n\t\t\tfetched: explicitMemberships,\n\t\t}\n\t}\n\n\tprivate readAssumedMemberships(req: HttpRequest): null | readonly Acl.Membership[] {\n\t\tconst value = this.readAssumeMembershipJson(req)\n\t\tif (value === null) {\n\t\t\treturn null\n\t\t}\n\t\ttry {\n\t\t\treturn assumeMembershipValueType(value).memberships\n\t\t} catch (e: any) {\n\t\t\tthrow new HttpErrorResponse(400, `Invalid format of \"assume membership\": ${e.message}`)\n\t\t}\n\t}\n\n\tprivate readAssumeMembershipJson(req: HttpRequest): unknown {\n\t\tif (typeof req.body === 'object' && req.body !== null && 'assumeMembership' in req.body) {\n\t\t\treturn (req.body as any).assumeMembership\n\t\t}\n\t\tconst value = req.get(assumeMembershipHeader).trim()\n\t\treturn value !== '' ? JSON.parse(value) : null\n\t}\n\n\tprivate verifyAssumedRoles(explicitMemberships: readonly Acl.Membership[], acl: Acl.Schema, assumedMemberships: readonly Acl.Membership[]) {\n\t\tconst membershipMatcher = new MembershipMatcher(explicitMemberships.map(it => ({\n\t\t\t...it,\n\t\t\tmatchRule: acl.roles[it.role].content?.assumeMembership ?? {},\n\t\t})))\n\n\t\tfor (const assumed of assumedMemberships) {\n\t\t\tif (!membershipMatcher.matches(assumed)) {\n\t\t\t\tthrow new HttpErrorResponse(403, `You are not allow to assume membership ${JSON.stringify(assumed)}`)\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst assumeMembershipValueType = Typesafe.object({\n\tmemberships: Typesafe.array(\n\t\tTypesafe.object({\n\t\t\trole: Typesafe.string,\n\t\t\tvariables: Typesafe.array(\n\t\t\t\tTypesafe.object({\n\t\t\t\t\tname: Typesafe.string,\n\t\t\t\t\tvalues: Typesafe.array(Typesafe.string),\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t),\n})\n"],"names":[],"mappings":";;;;AAOA,MAAM,yBAAyB;AAOxB,MAAM,0BAA0B;AAAA,EACtC,YACkB,OACA,0BAChB;AAFgB,SAAA,QAAA;AACA,SAAA,2BAAA;AAAA,EAAA;AAAA,EAIlB,MAAa,mBAAmB,EAAE,SAAS,KAAK,aAAa,YAK+B;AAE3F,UAAM,sBAAsB,MAAM,KAAK,yBAAyB,iBAAiB,aAAa;AAAA,MAC7F,IAAI,SAAS;AAAA,MACb,OAAO,SAAS;AAAA,IAAA,CAChB;AAEK,UAAA,gBAAgB,OAAO,QAAQ,IAAI,KAAK,EAAE,OAAO,CAAC,CAAA,EAAG,IAAI,MAAM,KAAK,QAAQ,EAAE,IAAI,CAAC,CAAC,IAAI,MAAM,IAAI;AAExG,UAAM,kBAAkB,MAAM;AAC7B,YAAM,eAAe,KAAK,QACvB,yCAAyC,WAAW,KACpD,WAAW,WAAW;AACnB,YAAA,IAAI,kBAAkB,KAAK,YAAY;AAAA,IAC9C;AAEA,QAAI,oBAAoB,WAAW,KAAK,cAAc,WAAW,GAAG;AACnD,sBAAA;AAAA,IAAA;AAGX,UAAA,qBAAqB,IAAI,mBAAmB;AAE5C,UAAA,qBAAqB,KAAK,uBAAuB,OAAO;AAC9D,QAAI,uBAAuB,MAAM;AAE5B,UAAA,mBAAmB,WAAW,GAAG;AACpB,wBAAA;AAAA,MAAA;AAGjB,YAAM,oBAAoB,mBAAmB,QAAQ,KAAK,oBAAoB,
|
|
1
|
+
{"version":3,"file":"ProjectMembershipResolver.js","sources":["../../../../../packages/engine-http/src/content/ProjectMembershipResolver.ts"],"sourcesContent":["import { MembershipMatcher } from '@contember/engine-tenant-api'\nimport * as Typesafe from '@contember/typesafe'\nimport { Acl } from '@contember/schema'\nimport { HttpErrorResponse } from '../common'\nimport { ProjectMembershipFetcher } from './ProjectMembershipFetcher'\nimport { MembershipResolver, ParsedMembership } from '@contember/schema-utils'\n\nconst assumeMembershipHeader = 'x-contember-assume-membership'\n\ninterface HttpRequest {\n\tbody?: unknown\n\tget(header: string): string\n}\n\nexport class ProjectMembershipResolver {\n\tconstructor(\n\t\tprivate readonly debug: boolean,\n\t\tprivate readonly projectMembershipFetcher: ProjectMembershipFetcher,\n\t) {\n\t}\n\n\tpublic async resolveMemberships({ request, acl, projectSlug, identity }: {\n\t\tacl: Acl.Schema\n\t\trequest: HttpRequest\n\t\tprojectSlug: string\n\t\tidentity: { identityId: string; personId?: string; roles?: readonly string[] }\n\t}): Promise<{ effective: readonly ParsedMembership[]; fetched: readonly Acl.Membership[] }> {\n\n\t\tconst explicitMemberships = await this.projectMembershipFetcher.fetchMemberships(projectSlug, {\n\t\t\tid: identity.identityId,\n\t\t\troles: identity.roles,\n\t\t})\n\n\t\tconst implicitRoles = Object.entries(acl.roles).filter(([, role]) => role.implicit).map(([name]) => name)\n\n\t\tconst throwNotAllowed = () => {\n\t\t\tconst errorMessage = this.debug\n\t\t\t\t? `You are not allowed to access project ${projectSlug}`\n\t\t\t\t: `Project ${projectSlug} NOT found`\n\t\t\tthrow new HttpErrorResponse(404, errorMessage)\n\t\t}\n\n\t\tif (explicitMemberships.length === 0 && implicitRoles.length === 0) {\n\t\t\tthrowNotAllowed()\n\t\t}\n\n\t\tconst membershipResolver = new MembershipResolver()\n\n\t\tconst assumedMemberships = this.readAssumedMemberships(request)\n\t\tif (assumedMemberships !== null) {\n\n\t\t\tif (assumedMemberships.length === 0) {\n\t\t\t\tthrowNotAllowed()\n\t\t\t}\n\n\t\t\tconst parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity, true)\n\t\t\tif (parsedMemberships.errors.length > 0) {\n\t\t\t\tthrow new HttpErrorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\t`Invalid memberships in ${assumeMembershipHeader} header:\\n` +\n\t\t\t\t\tparsedMemberships.errors.map(it => JSON.stringify(it)).join('\\n'),\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.verifyAssumedRoles(explicitMemberships, acl, assumedMemberships)\n\n\t\t\treturn { effective: parsedMemberships.memberships, fetched: explicitMemberships }\n\t\t}\n\n\n\t\tconst explicitProjectRoles = explicitMemberships.map(it => it.role)\n\t\tconst implicitRolesToAssign = implicitRoles.filter(it => !explicitProjectRoles.includes(it))\n\n\t\treturn {\n\t\t\teffective: [\n\t\t\t\t// intentionally ignoring validation errors of stored memberships\n\t\t\t\t...membershipResolver.resolve(acl, explicitMemberships, identity, false).memberships,\n\t\t\t\t...implicitRolesToAssign.map(it => ({ role: it, variables: [] })),\n\t\t\t],\n\t\t\tfetched: explicitMemberships,\n\t\t}\n\t}\n\n\tprivate readAssumedMemberships(req: HttpRequest): null | readonly Acl.Membership[] {\n\t\tconst value = this.readAssumeMembershipJson(req)\n\t\tif (value === null) {\n\t\t\treturn null\n\t\t}\n\t\ttry {\n\t\t\treturn assumeMembershipValueType(value).memberships\n\t\t} catch (e: any) {\n\t\t\tthrow new HttpErrorResponse(400, `Invalid format of \"assume membership\": ${e.message}`)\n\t\t}\n\t}\n\n\tprivate readAssumeMembershipJson(req: HttpRequest): unknown {\n\t\tif (typeof req.body === 'object' && req.body !== null && 'assumeMembership' in req.body) {\n\t\t\treturn (req.body as any).assumeMembership\n\t\t}\n\t\tconst value = req.get(assumeMembershipHeader).trim()\n\t\treturn value !== '' ? JSON.parse(value) : null\n\t}\n\n\tprivate verifyAssumedRoles(explicitMemberships: readonly Acl.Membership[], acl: Acl.Schema, assumedMemberships: readonly Acl.Membership[]) {\n\t\tconst membershipMatcher = new MembershipMatcher(explicitMemberships.map(it => ({\n\t\t\t...it,\n\t\t\tmatchRule: acl.roles[it.role].content?.assumeMembership ?? {},\n\t\t})))\n\n\t\tfor (const assumed of assumedMemberships) {\n\t\t\tif (!membershipMatcher.matches(assumed)) {\n\t\t\t\tthrow new HttpErrorResponse(403, `You are not allow to assume membership ${JSON.stringify(assumed)}`)\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst assumeMembershipValueType = Typesafe.object({\n\tmemberships: Typesafe.array(\n\t\tTypesafe.object({\n\t\t\trole: Typesafe.string,\n\t\t\tvariables: Typesafe.array(\n\t\t\t\tTypesafe.object({\n\t\t\t\t\tname: Typesafe.string,\n\t\t\t\t\tvalues: Typesafe.array(Typesafe.string),\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t),\n})\n"],"names":[],"mappings":";;;;AAOA,MAAM,yBAAyB;AAOxB,MAAM,0BAA0B;AAAA,EACtC,YACkB,OACA,0BAChB;AAFgB,SAAA,QAAA;AACA,SAAA,2BAAA;AAAA,EAAA;AAAA,EAIlB,MAAa,mBAAmB,EAAE,SAAS,KAAK,aAAa,YAK+B;AAE3F,UAAM,sBAAsB,MAAM,KAAK,yBAAyB,iBAAiB,aAAa;AAAA,MAC7F,IAAI,SAAS;AAAA,MACb,OAAO,SAAS;AAAA,IAAA,CAChB;AAEK,UAAA,gBAAgB,OAAO,QAAQ,IAAI,KAAK,EAAE,OAAO,CAAC,CAAA,EAAG,IAAI,MAAM,KAAK,QAAQ,EAAE,IAAI,CAAC,CAAC,IAAI,MAAM,IAAI;AAExG,UAAM,kBAAkB,MAAM;AAC7B,YAAM,eAAe,KAAK,QACvB,yCAAyC,WAAW,KACpD,WAAW,WAAW;AACnB,YAAA,IAAI,kBAAkB,KAAK,YAAY;AAAA,IAC9C;AAEA,QAAI,oBAAoB,WAAW,KAAK,cAAc,WAAW,GAAG;AACnD,sBAAA;AAAA,IAAA;AAGX,UAAA,qBAAqB,IAAI,mBAAmB;AAE5C,UAAA,qBAAqB,KAAK,uBAAuB,OAAO;AAC9D,QAAI,uBAAuB,MAAM;AAE5B,UAAA,mBAAmB,WAAW,GAAG;AACpB,wBAAA;AAAA,MAAA;AAGjB,YAAM,oBAAoB,mBAAmB,QAAQ,KAAK,oBAAoB,UAAU,IAAI;AACxF,UAAA,kBAAkB,OAAO,SAAS,GAAG;AACxC,cAAM,IAAI;AAAA,UACT;AAAA,UACA,0BAA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AAAA,MAC9E,GAAG;AAAA,MACH,WAAW,IAAI,MAAM,GAAG,IAAI,EAAE,SAAS,oBAAoB,CAAA;AAAA,MAC1D,CAAC;AAEH,eAAW,WAAW,oBAAoB;AACzC,UAAI,CAAC,kBAAkB,QAAQ,OAAO,GAAG;AAClC,cAAA,IAAI,kBAAkB,KAAK,0CAA0C,KAAK,UAAU,OAAO,CAAC,EAAE;AAAA,MAAA;AAAA,IACrG;AAAA,EACD;AAEF;AAEA,MAAM,4BAA4B,SAAS,OAAO;AAAA,EACjD,aAAa,SAAS;AAAA,IACrB,SAAS,OAAO;AAAA,MACf,MAAM,SAAS;AAAA,MACf,WAAW,SAAS;AAAA,QACnB,SAAS,OAAO;AAAA,UACf,MAAM,SAAS;AAAA,UACf,QAAQ,SAAS,MAAM,SAAS,MAAM;AAAA,QACtC,CAAA;AAAA,MAAA;AAAA,IAEF,CAAA;AAAA,EAAA;AAEH,CAAC;"}
|
|
@@ -2,14 +2,9 @@
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const HttpResponse = require("../common/HttpResponse.cjs");
|
|
4
4
|
class TenantApiMiddlewareFactory {
|
|
5
|
-
constructor(debug, projectGroupResolver, tenantGraphQLContextFactory) {
|
|
6
|
-
this.debug = debug;
|
|
7
|
-
this.projectGroupResolver = projectGroupResolver;
|
|
8
|
-
this.tenantGraphQLContextFactory = tenantGraphQLContextFactory;
|
|
9
|
-
}
|
|
10
5
|
create() {
|
|
11
6
|
return async (ctx) => {
|
|
12
|
-
const { timer, projectGroup, authResult, logger, koa } = ctx;
|
|
7
|
+
const { timer, projectGroup, authResult, logger, koa, clientIp } = ctx;
|
|
13
8
|
if (!authResult) {
|
|
14
9
|
return new HttpResponse.HttpErrorResponse(401, "Authentication required");
|
|
15
10
|
}
|
|
@@ -23,7 +18,18 @@ class TenantApiMiddlewareFactory {
|
|
|
23
18
|
koa.state.graphql = {
|
|
24
19
|
operationName: operation
|
|
25
20
|
};
|
|
26
|
-
|
|
21
|
+
const resolverContextFactory = tenantContainer.resolverContextFactory;
|
|
22
|
+
const db = tenantContainer.databaseContext;
|
|
23
|
+
const context = resolverContextFactory.create(
|
|
24
|
+
authResult,
|
|
25
|
+
{ ip: clientIp, userAgent: koa.request.headers["user-agent"] },
|
|
26
|
+
db,
|
|
27
|
+
logger2
|
|
28
|
+
);
|
|
29
|
+
return {
|
|
30
|
+
...context,
|
|
31
|
+
identityId: authResult.identityId
|
|
32
|
+
};
|
|
27
33
|
}
|
|
28
34
|
}));
|
|
29
35
|
logger2.debug("Tenant query finished");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TenantApiMiddlewareFactory.cjs","sources":["../../../../../packages/engine-http/src/tenant/TenantApiMiddlewareFactory.ts"],"sourcesContent":["import { HttpController } from '../application'\nimport { HttpErrorResponse } from '../common'\nimport {
|
|
1
|
+
{"version":3,"file":"TenantApiMiddlewareFactory.cjs","sources":["../../../../../packages/engine-http/src/tenant/TenantApiMiddlewareFactory.ts"],"sourcesContent":["import { HttpController } from '../application'\nimport { HttpErrorResponse } from '../common'\nimport { GraphQLKoaState } from '../graphql'\n\nexport class TenantApiMiddlewareFactory {\n\n\n\tcreate(): HttpController {\n\t\treturn async ctx => {\n\t\t\tconst { timer, projectGroup, authResult, logger, koa, clientIp } = ctx\n\t\t\tif (!authResult) {\n\t\t\t\treturn new HttpErrorResponse(401, 'Authentication required')\n\t\t\t}\n\t\t\tconst tenantContainer = projectGroup.tenantContainer\n\t\t\tawait logger.scope(async logger => {\n\t\t\t\tlogger.debug('Tenant query processing started')\n\t\t\t\tawait timer('GraphQL', () => projectGroup.tenantGraphQLHandler({\n\t\t\t\t\trequest: koa.request,\n\t\t\t\t\tresponse: koa.response,\n\t\t\t\t\tcreateContext: ({ operation }) => {\n\t\t\t\t\t\t(koa.state as GraphQLKoaState).graphql = {\n\t\t\t\t\t\t\toperationName: operation,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst resolverContextFactory = tenantContainer.resolverContextFactory\n\t\t\t\t\t\tconst db = tenantContainer.databaseContext\n\t\t\t\t\t\tconst context = resolverContextFactory.create(\n\t\t\t\t\t\t\tauthResult,\n\t\t\t\t\t\t\t{ ip: clientIp, userAgent: koa.request.headers['user-agent'] },\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\tidentityId: authResult.identityId,\n\t\t\t\t\t\t}\n\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t\tlogger.debug('Tenant query finished')\n\t\t\t})\n\t\t}\n\t}\n}\n"],"names":["HttpErrorResponse","logger"],"mappings":";;;AAIO,MAAM,2BAA2B;AAAA,EAGvC,SAAyB;AACxB,WAAO,OAAM,QAAO;AACnB,YAAM,EAAE,OAAO,cAAc,YAAY,QAAQ,KAAK,aAAa;AACnE,UAAI,CAAC,YAAY;AACT,eAAA,IAAIA,aAAAA,kBAAkB,KAAK,yBAAyB;AAAA,MAAA;AAE5D,YAAM,kBAAkB,aAAa;AAC/B,YAAA,OAAO,MAAM,OAAMC,YAAU;AAClCA,gBAAO,MAAM,iCAAiC;AAC9C,cAAM,MAAM,WAAW,MAAM,aAAa,qBAAqB;AAAA,UAC9D,SAAS,IAAI;AAAA,UACb,UAAU,IAAI;AAAA,UACd,eAAe,CAAC,EAAE,gBAAgB;AAChC,gBAAI,MAA0B,UAAU;AAAA,cACxC,eAAe;AAAA,YAChB;AACA,kBAAM,yBAAyB,gBAAgB;AAC/C,kBAAM,KAAK,gBAAgB;AAC3B,kBAAM,UAAU,uBAAuB;AAAA,cACtC;AAAA,cACA,EAAE,IAAI,UAAU,WAAW,IAAI,QAAQ,QAAQ,YAAY,EAAE;AAAA,cAC7D;AAAA,cACAA;AAAAA,YACD;AAEO,mBAAA;AAAA,cACN,GAAG;AAAA,cACH,YAAY,WAAW;AAAA,YACxB;AAAA,UAAA;AAAA,QAED,CACA,CAAC;AACFA,gBAAO,MAAM,uBAAuB;AAAA,MAAA,CACpC;AAAA,IACF;AAAA,EAAA;AAEF;;"}
|
|
@@ -1,13 +1,8 @@
|
|
|
1
1
|
import { HttpErrorResponse } from "../common/HttpResponse.js";
|
|
2
2
|
class TenantApiMiddlewareFactory {
|
|
3
|
-
constructor(debug, projectGroupResolver, tenantGraphQLContextFactory) {
|
|
4
|
-
this.debug = debug;
|
|
5
|
-
this.projectGroupResolver = projectGroupResolver;
|
|
6
|
-
this.tenantGraphQLContextFactory = tenantGraphQLContextFactory;
|
|
7
|
-
}
|
|
8
3
|
create() {
|
|
9
4
|
return async (ctx) => {
|
|
10
|
-
const { timer, projectGroup, authResult, logger, koa } = ctx;
|
|
5
|
+
const { timer, projectGroup, authResult, logger, koa, clientIp } = ctx;
|
|
11
6
|
if (!authResult) {
|
|
12
7
|
return new HttpErrorResponse(401, "Authentication required");
|
|
13
8
|
}
|
|
@@ -21,7 +16,18 @@ class TenantApiMiddlewareFactory {
|
|
|
21
16
|
koa.state.graphql = {
|
|
22
17
|
operationName: operation
|
|
23
18
|
};
|
|
24
|
-
|
|
19
|
+
const resolverContextFactory = tenantContainer.resolverContextFactory;
|
|
20
|
+
const db = tenantContainer.databaseContext;
|
|
21
|
+
const context = resolverContextFactory.create(
|
|
22
|
+
authResult,
|
|
23
|
+
{ ip: clientIp, userAgent: koa.request.headers["user-agent"] },
|
|
24
|
+
db,
|
|
25
|
+
logger2
|
|
26
|
+
);
|
|
27
|
+
return {
|
|
28
|
+
...context,
|
|
29
|
+
identityId: authResult.identityId
|
|
30
|
+
};
|
|
25
31
|
}
|
|
26
32
|
}));
|
|
27
33
|
logger2.debug("Tenant query finished");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TenantApiMiddlewareFactory.js","sources":["../../../../../packages/engine-http/src/tenant/TenantApiMiddlewareFactory.ts"],"sourcesContent":["import { HttpController } from '../application'\nimport { HttpErrorResponse } from '../common'\nimport {
|
|
1
|
+
{"version":3,"file":"TenantApiMiddlewareFactory.js","sources":["../../../../../packages/engine-http/src/tenant/TenantApiMiddlewareFactory.ts"],"sourcesContent":["import { HttpController } from '../application'\nimport { HttpErrorResponse } from '../common'\nimport { GraphQLKoaState } from '../graphql'\n\nexport class TenantApiMiddlewareFactory {\n\n\n\tcreate(): HttpController {\n\t\treturn async ctx => {\n\t\t\tconst { timer, projectGroup, authResult, logger, koa, clientIp } = ctx\n\t\t\tif (!authResult) {\n\t\t\t\treturn new HttpErrorResponse(401, 'Authentication required')\n\t\t\t}\n\t\t\tconst tenantContainer = projectGroup.tenantContainer\n\t\t\tawait logger.scope(async logger => {\n\t\t\t\tlogger.debug('Tenant query processing started')\n\t\t\t\tawait timer('GraphQL', () => projectGroup.tenantGraphQLHandler({\n\t\t\t\t\trequest: koa.request,\n\t\t\t\t\tresponse: koa.response,\n\t\t\t\t\tcreateContext: ({ operation }) => {\n\t\t\t\t\t\t(koa.state as GraphQLKoaState).graphql = {\n\t\t\t\t\t\t\toperationName: operation,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst resolverContextFactory = tenantContainer.resolverContextFactory\n\t\t\t\t\t\tconst db = tenantContainer.databaseContext\n\t\t\t\t\t\tconst context = resolverContextFactory.create(\n\t\t\t\t\t\t\tauthResult,\n\t\t\t\t\t\t\t{ ip: clientIp, userAgent: koa.request.headers['user-agent'] },\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\tidentityId: authResult.identityId,\n\t\t\t\t\t\t}\n\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t\tlogger.debug('Tenant query finished')\n\t\t\t})\n\t\t}\n\t}\n}\n"],"names":["logger"],"mappings":";AAIO,MAAM,2BAA2B;AAAA,EAGvC,SAAyB;AACxB,WAAO,OAAM,QAAO;AACnB,YAAM,EAAE,OAAO,cAAc,YAAY,QAAQ,KAAK,aAAa;AACnE,UAAI,CAAC,YAAY;AACT,eAAA,IAAI,kBAAkB,KAAK,yBAAyB;AAAA,MAAA;AAE5D,YAAM,kBAAkB,aAAa;AAC/B,YAAA,OAAO,MAAM,OAAMA,YAAU;AAClCA,gBAAO,MAAM,iCAAiC;AAC9C,cAAM,MAAM,WAAW,MAAM,aAAa,qBAAqB;AAAA,UAC9D,SAAS,IAAI;AAAA,UACb,UAAU,IAAI;AAAA,UACd,eAAe,CAAC,EAAE,gBAAgB;AAChC,gBAAI,MAA0B,UAAU;AAAA,cACxC,eAAe;AAAA,YAChB;AACA,kBAAM,yBAAyB,gBAAgB;AAC/C,kBAAM,KAAK,gBAAgB;AAC3B,kBAAM,UAAU,uBAAuB;AAAA,cACtC;AAAA,cACA,EAAE,IAAI,UAAU,WAAW,IAAI,QAAQ,QAAQ,YAAY,EAAE;AAAA,cAC7D;AAAA,cACAA;AAAAA,YACD;AAEO,mBAAA;AAAA,cACN,GAAG;AAAA,cACH,YAAY,WAAW;AAAA,YACxB;AAAA,UAAA;AAAA,QAED,CACA,CAAC;AACFA,gBAAO,MAAM,uBAAuB;AAAA,MAAA,CACpC;AAAA,IACF;AAAA,EAAA;AAEF;"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const ipaddr = require("ipaddr.js");
|
|
4
|
+
function isPrivate(ip) {
|
|
5
|
+
let addr;
|
|
6
|
+
try {
|
|
7
|
+
addr = ipaddr.parse(ip);
|
|
8
|
+
} catch {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
const r = addr.range();
|
|
12
|
+
if (r === "ipv4Mapped") {
|
|
13
|
+
return addr.toIPv4Address().range() === "private";
|
|
14
|
+
}
|
|
15
|
+
return r === "private" || r === "uniqueLocal" || r === "linkLocal";
|
|
16
|
+
}
|
|
17
|
+
function isInCIDR(ip, cidrs) {
|
|
18
|
+
if (!cidrs || cidrs.length === 0) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
let addr;
|
|
22
|
+
try {
|
|
23
|
+
addr = ipaddr.parse(ip);
|
|
24
|
+
} catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
return cidrs.some((c) => {
|
|
28
|
+
try {
|
|
29
|
+
return addr.match(ipaddr.parseCIDR(c));
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
function getClientIP(req, trustedProxies) {
|
|
36
|
+
const remote = req.socket.remoteAddress || "";
|
|
37
|
+
if (!isPrivate(remote) && !isInCIDR(remote, [])) {
|
|
38
|
+
return remote;
|
|
39
|
+
}
|
|
40
|
+
const xffHeader = req.headers["x-forwarded-for"];
|
|
41
|
+
let xffList = [];
|
|
42
|
+
if (Array.isArray(xffHeader)) {
|
|
43
|
+
xffHeader.forEach(
|
|
44
|
+
(h) => xffList.push(...h.split(",").map((ip) => ip.trim()).filter(Boolean))
|
|
45
|
+
);
|
|
46
|
+
} else if (typeof xffHeader === "string") {
|
|
47
|
+
xffList = xffHeader.split(",").map((ip) => ip.trim()).filter(Boolean);
|
|
48
|
+
}
|
|
49
|
+
for (let i = xffList.length - 1; i >= 0; i--) {
|
|
50
|
+
const ip = xffList[i];
|
|
51
|
+
if (!isPrivate(ip) && !isInCIDR(ip, [])) {
|
|
52
|
+
return ip;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return remote;
|
|
56
|
+
}
|
|
57
|
+
exports.getClientIP = getClientIP;
|
|
58
|
+
//# sourceMappingURL=remoteAddress.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remoteAddress.cjs","sources":["../../../../../packages/engine-http/src/utils/remoteAddress.ts"],"sourcesContent":["import { IncomingMessage } from 'node:http'\nimport ipaddr from 'ipaddr.js'\n\n\nfunction isPrivate(ip: string): boolean {\n\tlet addr: ipaddr.IPv4 | ipaddr.IPv6\n\ttry {\n\t\taddr = ipaddr.parse(ip)\n\t} catch {\n\t\treturn false\n\t}\n\n\tconst r = addr.range()\n\tif (r === 'ipv4Mapped') {\n\t\treturn (addr as ipaddr.IPv6).toIPv4Address().range() === 'private'\n\t}\n\n\treturn r === 'private' // IPv4 RFC1918\n\t\t|| r === 'uniqueLocal' // IPv6 fc00::/7\n\t\t|| r === 'linkLocal' // IPv6 fe80::/10\n}\n\n\nfunction isInCIDR(ip: string, cidrs: string[]): boolean {\n\tif (!cidrs || cidrs.length === 0) {\n\t\treturn false\n\t}\n\n\tlet addr: ipaddr.IPv4 | ipaddr.IPv6\n\ttry {\n\t\taddr = ipaddr.parse(ip)\n\t} catch {\n\t\treturn false\n\t}\n\treturn cidrs.some(c => {\n\t\ttry {\n\t\t\treturn addr.match(ipaddr.parseCIDR(c))\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t})\n}\n\nexport function getClientIP(req: IncomingMessage, trustedProxies?: string[]): string {\n\tconst remote = req.socket.remoteAddress || ''\n\n\tif (!isPrivate(remote) && !isInCIDR(remote, trustedProxies || [])) {\n\t\treturn remote\n\t}\n\n\tconst xffHeader = req.headers['x-forwarded-for']\n\tlet xffList: string[] = []\n\n\tif (Array.isArray(xffHeader)) {\n\t\txffHeader.forEach(h =>\n\t\t\txffList.push(...h.split(',').map(ip => ip.trim()).filter(Boolean)),\n\t\t)\n\t} else if (typeof xffHeader === 'string') {\n\t\txffList = xffHeader.split(',').map(ip => ip.trim()).filter(Boolean)\n\t}\n\n\tfor (let i = xffList.length - 1; i >= 0; i--) {\n\t\tconst ip = xffList[i]\n\t\tif (!isPrivate(ip) && !isInCIDR(ip, trustedProxies || [])) {\n\t\t\treturn ip\n\t\t}\n\t}\n\n\treturn remote\n}\n"],"names":[],"mappings":";;;AAIA,SAAS,UAAU,IAAqB;AACnC,MAAA;AACA,MAAA;AACI,WAAA,OAAO,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E,KAAK,CAAC,SAAS,IAAsB,CAAA,CAAE,GAAG;AACnD,aAAA;AAAA,IAAA;AAAA,EACR;AAGM,SAAA;AACR;;"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import ipaddr from "ipaddr.js";
|
|
2
|
+
function isPrivate(ip) {
|
|
3
|
+
let addr;
|
|
4
|
+
try {
|
|
5
|
+
addr = ipaddr.parse(ip);
|
|
6
|
+
} catch {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
const r = addr.range();
|
|
10
|
+
if (r === "ipv4Mapped") {
|
|
11
|
+
return addr.toIPv4Address().range() === "private";
|
|
12
|
+
}
|
|
13
|
+
return r === "private" || r === "uniqueLocal" || r === "linkLocal";
|
|
14
|
+
}
|
|
15
|
+
function isInCIDR(ip, cidrs) {
|
|
16
|
+
if (!cidrs || cidrs.length === 0) {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
let addr;
|
|
20
|
+
try {
|
|
21
|
+
addr = ipaddr.parse(ip);
|
|
22
|
+
} catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return cidrs.some((c) => {
|
|
26
|
+
try {
|
|
27
|
+
return addr.match(ipaddr.parseCIDR(c));
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function getClientIP(req, trustedProxies) {
|
|
34
|
+
const remote = req.socket.remoteAddress || "";
|
|
35
|
+
if (!isPrivate(remote) && !isInCIDR(remote, [])) {
|
|
36
|
+
return remote;
|
|
37
|
+
}
|
|
38
|
+
const xffHeader = req.headers["x-forwarded-for"];
|
|
39
|
+
let xffList = [];
|
|
40
|
+
if (Array.isArray(xffHeader)) {
|
|
41
|
+
xffHeader.forEach(
|
|
42
|
+
(h) => xffList.push(...h.split(",").map((ip) => ip.trim()).filter(Boolean))
|
|
43
|
+
);
|
|
44
|
+
} else if (typeof xffHeader === "string") {
|
|
45
|
+
xffList = xffHeader.split(",").map((ip) => ip.trim()).filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
for (let i = xffList.length - 1; i >= 0; i--) {
|
|
48
|
+
const ip = xffList[i];
|
|
49
|
+
if (!isPrivate(ip) && !isInCIDR(ip, [])) {
|
|
50
|
+
return ip;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return remote;
|
|
54
|
+
}
|
|
55
|
+
export {
|
|
56
|
+
getClientIP
|
|
57
|
+
};
|
|
58
|
+
//# sourceMappingURL=remoteAddress.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remoteAddress.js","sources":["../../../../../packages/engine-http/src/utils/remoteAddress.ts"],"sourcesContent":["import { IncomingMessage } from 'node:http'\nimport ipaddr from 'ipaddr.js'\n\n\nfunction isPrivate(ip: string): boolean {\n\tlet addr: ipaddr.IPv4 | ipaddr.IPv6\n\ttry {\n\t\taddr = ipaddr.parse(ip)\n\t} catch {\n\t\treturn false\n\t}\n\n\tconst r = addr.range()\n\tif (r === 'ipv4Mapped') {\n\t\treturn (addr as ipaddr.IPv6).toIPv4Address().range() === 'private'\n\t}\n\n\treturn r === 'private' // IPv4 RFC1918\n\t\t|| r === 'uniqueLocal' // IPv6 fc00::/7\n\t\t|| r === 'linkLocal' // IPv6 fe80::/10\n}\n\n\nfunction isInCIDR(ip: string, cidrs: string[]): boolean {\n\tif (!cidrs || cidrs.length === 0) {\n\t\treturn false\n\t}\n\n\tlet addr: ipaddr.IPv4 | ipaddr.IPv6\n\ttry {\n\t\taddr = ipaddr.parse(ip)\n\t} catch {\n\t\treturn false\n\t}\n\treturn cidrs.some(c => {\n\t\ttry {\n\t\t\treturn addr.match(ipaddr.parseCIDR(c))\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t})\n}\n\nexport function getClientIP(req: IncomingMessage, trustedProxies?: string[]): string {\n\tconst remote = req.socket.remoteAddress || ''\n\n\tif (!isPrivate(remote) && !isInCIDR(remote, trustedProxies || [])) {\n\t\treturn remote\n\t}\n\n\tconst xffHeader = req.headers['x-forwarded-for']\n\tlet xffList: string[] = []\n\n\tif (Array.isArray(xffHeader)) {\n\t\txffHeader.forEach(h =>\n\t\t\txffList.push(...h.split(',').map(ip => ip.trim()).filter(Boolean)),\n\t\t)\n\t} else if (typeof xffHeader === 'string') {\n\t\txffList = xffHeader.split(',').map(ip => ip.trim()).filter(Boolean)\n\t}\n\n\tfor (let i = xffList.length - 1; i >= 0; i--) {\n\t\tconst ip = xffList[i]\n\t\tif (!isPrivate(ip) && !isInCIDR(ip, trustedProxies || [])) {\n\t\t\treturn ip\n\t\t}\n\t}\n\n\treturn remote\n}\n"],"names":[],"mappings":";AAIA,SAAS,UAAU,IAAqB;AACnC,MAAA;AACA,MAAA;AACI,WAAA,OAAO,MAAM,EAAE;AAAA,EAAA,QACf;AACA,WAAA;AAAA,EAAA;AAGF,QAAA,IAAI,KAAK,MAAM;AACrB,MAAI,MAAM,cAAc;AACvB,WAAQ,KAAqB,gBAAgB,MAAY,MAAA;AAAA,EAAA;AAG1D,SAAO,MAAM,aACT,MAAM,iBACN,MAAM;AACX;AAGA,SAAS,SAAS,IAAY,OAA0B;AACvD,MAAI,CAAC,SAAS,MAAM,WAAW,GAAG;AAC1B,WAAA;AAAA,EAAA;AAGJ,MAAA;AACA,MAAA;AACI,WAAA,OAAO,MAAM,EAAE;AAAA,EAAA,QACf;AACA,WAAA;AAAA,EAAA;AAED,SAAA,MAAM,KAAK,CAAK,MAAA;AAClB,QAAA;AACH,aAAO,KAAK,MAAM,OAAO,UAAU,CAAC,CAAC;AAAA,IAAA,QAC9B;AACA,aAAA;AAAA,IAAA;AAAA,EACR,CACA;AACF;AAEgB,SAAA,YAAY,KAAsB,gBAAmC;AAC9E,QAAA,SAAS,IAAI,OAAO,iBAAiB;AAEvC,MAAA,CAAC,UAAU,MAAM,KAAK,CAAC,SAAS,QAA0B,CAAA,CAAE,GAAG;AAC3D,WAAA;AAAA,EAAA;AAGF,QAA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