@contember/engine-http 2.2.0-alpha.18 → 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 +0 -1
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +1 -2
- package/dist/development/src/application/application.cjs +8 -9
- package/dist/development/src/application/application.cjs.map +1 -1
- package/dist/development/src/application/application.js +8 -9
- 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/config/configSchema.cjs +8 -1
- package/dist/development/src/config/configSchema.cjs.map +1 -1
- package/dist/development/src/config/configSchema.js +8 -1
- package/dist/development/src/config/configSchema.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 +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.js +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 +18 -3
- package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.js +18 -3
- package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/development/src/utils/sentry.cjs +31 -49
- package/dist/development/src/utils/sentry.cjs.map +1 -1
- package/dist/development/src/utils/sentry.js +32 -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 +0 -1
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +1 -2
- package/dist/production/src/application/application.cjs +8 -9
- package/dist/production/src/application/application.cjs.map +1 -1
- package/dist/production/src/application/application.js +8 -9
- 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/config/configSchema.cjs +8 -1
- package/dist/production/src/config/configSchema.cjs.map +1 -1
- package/dist/production/src/config/configSchema.js +8 -1
- package/dist/production/src/config/configSchema.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 +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.js +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 +18 -3
- package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.js +18 -3
- package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/production/src/utils/sentry.cjs +31 -49
- package/dist/production/src/utils/sentry.cjs.map +1 -1
- package/dist/production/src/utils/sentry.js +32 -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/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +1 -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/requestBody.d.ts +45 -0
- package/dist/types/application/requestBody.d.ts.map +1 -0
- package/dist/types/config/configSchema.d.ts +3 -3
- package/dist/types/config/configSchema.d.ts.map +1 -1
- package/dist/types/graphql/execution.d.ts.map +1 -1
- package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +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/application/application.ts +8 -9
- package/src/application/compression.ts +118 -0
- package/src/application/cors.ts +61 -0
- package/src/application/requestBody.ts +295 -0
- package/src/config/configSchema.ts +8 -1
- package/src/graphql/execution.ts +3 -9
- package/src/providers.ts +2 -2
- package/src/transfer/ImportExecutor.ts +21 -3
- package/src/tsconfig.json +3 -1
- 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/requestBody.test.ts +333 -0
- package/tests/cases/unit/sentryLoggerHandler.test.ts +74 -20
- package/tests/cases/unit/serverConfig.test.ts +19 -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,14 +1,21 @@
|
|
|
1
|
-
import * as Sentry from '@sentry/node';
|
|
2
1
|
import { LogEntry, LoggerHandler, LogLevel } from '@contember/logger';
|
|
2
|
+
import { SentryClient } from '@contember/sentry-client';
|
|
3
3
|
export declare class SentryLoggerHandler implements LoggerHandler {
|
|
4
4
|
private readonly logLevel;
|
|
5
|
-
|
|
5
|
+
private readonly client;
|
|
6
|
+
constructor(logLevel: LogLevel, client: SentryClient);
|
|
6
7
|
getMinLevel(): number;
|
|
7
8
|
handle(entry: LogEntry): void;
|
|
8
9
|
close(): void;
|
|
9
10
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
export interface SentryLoggerHandlerOptions {
|
|
12
|
+
/** Reported as the SDK version; the client is released together with the server, so this is the server version. */
|
|
13
|
+
readonly version?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Reports logged errors (warn and up) and uncaught exceptions and unhandled rejections of the process.
|
|
17
|
+
* Release, environment and server name come from SENTRY_RELEASE, SENTRY_ENVIRONMENT and SENTRY_NAME (default: the host name). Nothing instruments outgoing requests, whose
|
|
18
|
+
* URLs may carry a webhook credential.
|
|
19
|
+
*/
|
|
20
|
+
export declare const createSentryLoggerHandler: (dsn?: string, options?: SentryLoggerHandlerOptions) => null | LoggerHandler;
|
|
14
21
|
//# sourceMappingURL=sentry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sentry.d.ts","sourceRoot":"","sources":["../../../src/utils/sentry.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"sentry.d.ts","sourceRoot":"","sources":["../../../src/utils/sentry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,QAAQ,EAA2B,MAAM,mBAAmB,CAAA;AAC9F,OAAO,EAA8C,YAAY,EAAiB,MAAM,0BAA0B,CAAA;AAalH,qBAAa,mBAAoB,YAAW,aAAa;IAEvD,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAFxB,YACkB,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,YAAY,EAErC;IAED,WAAW,IAAI,MAAM,CAEpB;IAED,MAAM,CAAC,KAAK,EAAE,QAAQ,QAgBrB;IAED,KAAK,IAAI,IAAI,CACZ;CACD;AAED,MAAM,WAAW,0BAA0B;IAC1C,mHAAmH;IACnH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CACzB;AAED;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,SAAU,MAAM,YAAW,0BAA0B,KAAQ,IAAI,GAAG,aAoBzG,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serverStartup.d.ts","sourceRoot":"","sources":["../../../src/utils/serverStartup.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAC5E,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAA;AAC1C,OAAO,EAAyC,MAAM,EAAuC,MAAM,mBAAmB,CAAA;AAEtH,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAG5C,eAAO,MAAM,gBAAgB,QAAa,OAAO,CAAC,MAAM,CAIvD,CAAA;AAED,eAAO,MAAM,WAAW,QAAO,OAAiD,CAAA;AAEhF,eAAO,MAAM,cAAc,yBAA0B;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,UAAU,MAAM,SAOzG,CAAA;AAED,eAAO,MAAM,mBAAmB,GAAU,CAAC,SAAS,YAAY,mCAC9B;IAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IAAC,kBAAkB,EAAE,IAAI,CAAC,CAAC,CAAC,CAAA;CAAE;;;;;EAenF,CAAA;AAED,eAAO,MAAM,mBAAmB,QAAO,
|
|
1
|
+
{"version":3,"file":"serverStartup.d.ts","sourceRoot":"","sources":["../../../src/utils/serverStartup.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAC5E,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAA;AAC1C,OAAO,EAAyC,MAAM,EAAuC,MAAM,mBAAmB,CAAA;AAEtH,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAG5C,eAAO,MAAM,gBAAgB,QAAa,OAAO,CAAC,MAAM,CAIvD,CAAA;AAED,eAAO,MAAM,WAAW,QAAO,OAAiD,CAAA;AAEhF,eAAO,MAAM,cAAc,yBAA0B;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,UAAU,MAAM,SAOzG,CAAA;AAED,eAAO,MAAM,mBAAmB,GAAU,CAAC,SAAS,YAAY,mCAC9B;IAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IAAC,kBAAkB,EAAE,IAAI,CAAC,CAAC,CAAC,CAAA;CAAE;;;;;EAenF,CAAA;AAED,eAAO,MAAM,mBAAmB,QAAO,MAuCtC,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@contember/engine-http",
|
|
3
|
-
"version": "2.2.0-alpha.
|
|
3
|
+
"version": "2.2.0-alpha.19",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"main": "./dist/production/index.js",
|
|
6
6
|
"typings": "./dist/types/index.d.ts",
|
|
@@ -26,40 +26,34 @@
|
|
|
26
26
|
}
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@contember/config-loader": "2.2.0-alpha.
|
|
30
|
-
"@contember/database": "2.2.0-alpha.
|
|
31
|
-
"@contember/database-migrations": "2.2.0-alpha.
|
|
32
|
-
"@contember/dic": "2.2.0-alpha.
|
|
33
|
-
"@contember/engine-common": "2.2.0-alpha.
|
|
34
|
-
"@contember/engine-content-api": "2.2.0-alpha.
|
|
35
|
-
"@contember/engine-system-api": "2.2.0-alpha.
|
|
36
|
-
"@contember/engine-tenant-api": "2.2.0-alpha.
|
|
37
|
-
"@contember/graphql-utils": "2.2.0-alpha.
|
|
38
|
-
"@contember/logger": "2.2.0-alpha.
|
|
39
|
-
"@contember/schema": "2.2.0-alpha.
|
|
40
|
-
"@contember/schema-migrations": "2.2.0-alpha.
|
|
41
|
-
"@contember/schema-utils": "2.2.0-alpha.
|
|
42
|
-
"@contember/
|
|
43
|
-
"@contember/
|
|
29
|
+
"@contember/config-loader": "2.2.0-alpha.19",
|
|
30
|
+
"@contember/database": "2.2.0-alpha.19",
|
|
31
|
+
"@contember/database-migrations": "2.2.0-alpha.19",
|
|
32
|
+
"@contember/dic": "2.2.0-alpha.19",
|
|
33
|
+
"@contember/engine-common": "2.2.0-alpha.19",
|
|
34
|
+
"@contember/engine-content-api": "2.2.0-alpha.19",
|
|
35
|
+
"@contember/engine-system-api": "2.2.0-alpha.19",
|
|
36
|
+
"@contember/engine-tenant-api": "2.2.0-alpha.19",
|
|
37
|
+
"@contember/graphql-utils": "2.2.0-alpha.19",
|
|
38
|
+
"@contember/logger": "2.2.0-alpha.19",
|
|
39
|
+
"@contember/schema": "2.2.0-alpha.19",
|
|
40
|
+
"@contember/schema-migrations": "2.2.0-alpha.19",
|
|
41
|
+
"@contember/schema-utils": "2.2.0-alpha.19",
|
|
42
|
+
"@contember/sentry-client": "2.2.0-alpha.19",
|
|
43
|
+
"@contember/telemetry": "2.2.0-alpha.19",
|
|
44
|
+
"@contember/typesafe": "2.2.0-alpha.19",
|
|
45
|
+
"@contember/utilities": "2.2.0-alpha.19",
|
|
44
46
|
"@graphql-tools/merge": "^9.1.7",
|
|
45
47
|
"@graphql-tools/schema": "^10.0.31",
|
|
46
|
-
"@koa/cors": "^5.0.0",
|
|
47
|
-
"@sentry/node": "^7.120.4",
|
|
48
48
|
"bcryptjs": "^3.0.3",
|
|
49
49
|
"ipaddr.js": "^2.3.0",
|
|
50
50
|
"koa": "^2.16.4",
|
|
51
|
-
"koa-bodyparser": "^4.4.1",
|
|
52
|
-
"koa-compress": "^5.2.0",
|
|
53
|
-
"lru-cache": "^11.2.6",
|
|
54
51
|
"path-to-regexp": "^8.3.0",
|
|
55
52
|
"prom-client": "^12.0.0",
|
|
56
|
-
"uuid": "^13.0.0",
|
|
57
53
|
"ws": "^8.19.0"
|
|
58
54
|
},
|
|
59
55
|
"devDependencies": {
|
|
60
56
|
"@types/koa": "^2.15.0",
|
|
61
|
-
"@types/koa-bodyparser": "^4.3.13",
|
|
62
|
-
"@types/koa__cors": "^5.0.1",
|
|
63
57
|
"@types/node": "^24.12.0",
|
|
64
58
|
"@types/ws": "^8.18.1",
|
|
65
59
|
"graphql": "^16.13.1"
|
|
@@ -6,10 +6,10 @@ import * as http from 'node:http'
|
|
|
6
6
|
import { IncomingMessage, Server, ServerResponse } from 'node:http'
|
|
7
7
|
import { WebSocket, WebSocketServer } from 'ws'
|
|
8
8
|
import { FingerCrossedLoggerHandler, Logger } from '@contember/logger'
|
|
9
|
-
import koaCompress from 'koa-compress'
|
|
10
|
-
import bodyParser from 'koa-bodyparser'
|
|
11
9
|
import { ServerConfig } from '../config/config.js'
|
|
12
|
-
import
|
|
10
|
+
import { createCompressionMiddleware } from './compression.js'
|
|
11
|
+
import { createCorsMiddleware } from './cors.js'
|
|
12
|
+
import { createRequestBodyMiddleware, defaultFormBodyLimit, defaultJsonBodyLimit } from './requestBody.js'
|
|
13
13
|
import stream, { Duplex, Readable } from 'node:stream'
|
|
14
14
|
import { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'
|
|
15
15
|
import { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'
|
|
@@ -108,13 +108,12 @@ export class Application {
|
|
|
108
108
|
for (const middleware of this.middlewares) {
|
|
109
109
|
koa.use(middleware)
|
|
110
110
|
}
|
|
111
|
-
koa.use(
|
|
112
|
-
|
|
111
|
+
koa.use(createCompressionMiddleware())
|
|
112
|
+
koa.use(createRequestBodyMiddleware({
|
|
113
|
+
json: this.serverConfig.http?.requestBodySize ?? defaultJsonBodyLimit,
|
|
114
|
+
form: defaultFormBodyLimit,
|
|
113
115
|
}))
|
|
114
|
-
koa.use(
|
|
115
|
-
jsonLimit: this.serverConfig.http?.requestBodySize || '1mb',
|
|
116
|
-
}))
|
|
117
|
-
koa.use(corsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))
|
|
116
|
+
koa.use(createCorsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))
|
|
118
117
|
const versionMatch = this.version?.match(/^(0\.\d+|\d+)/)
|
|
119
118
|
const versionSimplified = versionMatch?.[1] ?? 'unknown'
|
|
120
119
|
koa.use(async ctx => {
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Stream, Transform } from 'node:stream'
|
|
2
|
+
import * as zlib from 'node:zlib'
|
|
3
|
+
import type * as Koa from 'koa'
|
|
4
|
+
|
|
5
|
+
declare module 'koa' {
|
|
6
|
+
interface DefaultContext {
|
|
7
|
+
/** `true` compresses a response whose type is not compressible by default, `false` never compresses it. */
|
|
8
|
+
compress?: boolean
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type Encoding = 'zstd' | 'gzip' | 'deflate'
|
|
13
|
+
|
|
14
|
+
const compressors: Readonly<Record<Encoding, () => Transform>> = {
|
|
15
|
+
zstd: () => zlib.createZstdCompress(),
|
|
16
|
+
gzip: () => zlib.createGzip(),
|
|
17
|
+
deflate: () => zlib.createDeflate(),
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// zstd needs Node 22.15 or 23.8; a tie in quality goes to the first listed. Brotli stays off, as it was.
|
|
21
|
+
const offeredEncodings: readonly Encoding[] = typeof zlib.createZstdCompress === 'function' ? ['zstd', 'gzip', 'deflate'] : ['gzip', 'deflate']
|
|
22
|
+
|
|
23
|
+
type AcceptedEncoding = { readonly name: string; readonly quality: number }
|
|
24
|
+
|
|
25
|
+
const parseAcceptEncoding = (header: string): AcceptedEncoding[] =>
|
|
26
|
+
header.split(',').flatMap(item => {
|
|
27
|
+
const match = /^\s*([^\s;]+)\s*(?:;(.*))?$/.exec(item.trim())
|
|
28
|
+
if (!match) {
|
|
29
|
+
return []
|
|
30
|
+
}
|
|
31
|
+
const qualityParameter = (match[2] ?? '').split(';').map(it => it.trim().split('=')).find(([name]) => name === 'q')
|
|
32
|
+
const quality = qualityParameter ? Number.parseFloat(qualityParameter[1]) : 1
|
|
33
|
+
return [{ name: match[1].toLowerCase(), quality: Number.isNaN(quality) ? 0 : quality }]
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The best encoding the client accepts (RFC 9110 §12.5.3), or `undefined` for identity. An exact entry outranks `*`,
|
|
38
|
+
* and identity, unless listed, is acceptable at the lowest quality given. No header means identity, a bare `*` gzip.
|
|
39
|
+
*/
|
|
40
|
+
export const negotiateEncoding = (header: string): Encoding | undefined => {
|
|
41
|
+
if (header === '') {
|
|
42
|
+
return undefined
|
|
43
|
+
}
|
|
44
|
+
if (header === '*') {
|
|
45
|
+
return 'gzip'
|
|
46
|
+
}
|
|
47
|
+
const accepted = parseAcceptEncoding(header)
|
|
48
|
+
const quality = (name: string): number | undefined => {
|
|
49
|
+
const exact = accepted.filter(it => it.name === name)
|
|
50
|
+
const matching = exact.length > 0 ? exact : accepted.filter(it => it.name === '*')
|
|
51
|
+
return matching.length > 0 ? Math.max(...matching.map(it => it.quality)) : undefined
|
|
52
|
+
}
|
|
53
|
+
const identityQuality = quality('identity') ?? Math.min(1, ...accepted.map(it => it.quality || 1))
|
|
54
|
+
let best: { encoding: Encoding | undefined; quality: number } = { encoding: undefined, quality: identityQuality > 0 ? identityQuality : 0 }
|
|
55
|
+
for (const encoding of offeredEncodings) {
|
|
56
|
+
const encodingQuality = quality(encoding) ?? 0
|
|
57
|
+
// identity is the last preference, so an encoding wins a tie with it
|
|
58
|
+
if (encodingQuality > 0 && (encodingQuality > best.quality || (encodingQuality === best.quality && best.encoding === undefined))) {
|
|
59
|
+
best = { encoding, quality: encodingQuality }
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return best.encoding
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const compressibleTypes: ReadonlySet<string> = new Set(['application/json', 'application/javascript', 'application/xml', 'application/wasm'])
|
|
66
|
+
|
|
67
|
+
/** The media types the engine serves as text: JSON, HTML, plain text, scripts, styles, SVG. */
|
|
68
|
+
export const isCompressibleType = (type: string): boolean => {
|
|
69
|
+
const normalized = type.toLowerCase()
|
|
70
|
+
return compressibleTypes.has(normalized) || /^text\/|\+(?:json|text|xml)$/.test(normalized)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const threshold = 1024
|
|
74
|
+
const emptyBodyStatuses: ReadonlySet<number> = new Set([204, 205, 304])
|
|
75
|
+
const noTransform = /(?:^|,)\s*?no-transform\s*?(?:,|$)/
|
|
76
|
+
|
|
77
|
+
const shouldCompress = (ctx: Koa.Context): boolean => {
|
|
78
|
+
const response = ctx.response
|
|
79
|
+
if (
|
|
80
|
+
!ctx.body
|
|
81
|
+
|| ctx.res.headersSent
|
|
82
|
+
|| !ctx.writable
|
|
83
|
+
|| ctx.compress === false
|
|
84
|
+
|| ctx.method === 'HEAD'
|
|
85
|
+
|| emptyBodyStatuses.has(response.status)
|
|
86
|
+
|| response.get('Content-Encoding')
|
|
87
|
+
|| !(ctx.compress === true || isCompressibleType(response.type))
|
|
88
|
+
|| noTransform.test(response.get('Cache-Control'))
|
|
89
|
+
) {
|
|
90
|
+
return false
|
|
91
|
+
}
|
|
92
|
+
// a stream has no known length and is always compressed
|
|
93
|
+
return response.length === undefined || response.length >= threshold
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Compresses responses of 1 KiB and more, or of unknown length, with zstd, gzip or deflate, as the client accepts. */
|
|
97
|
+
export const createCompressionMiddleware = (): Koa.Middleware => async (ctx, next) => {
|
|
98
|
+
ctx.vary('Accept-Encoding')
|
|
99
|
+
await next()
|
|
100
|
+
|
|
101
|
+
if (!shouldCompress(ctx)) {
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
const encoding = negotiateEncoding(ctx.get('Accept-Encoding'))
|
|
105
|
+
if (encoding === undefined) {
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
const body: unknown = ctx.body
|
|
109
|
+
const compressed = compressors[encoding]()
|
|
110
|
+
ctx.set('Content-Encoding', encoding)
|
|
111
|
+
ctx.res.removeHeader('Content-Length')
|
|
112
|
+
ctx.body = compressed
|
|
113
|
+
if (body instanceof Stream) {
|
|
114
|
+
body.pipe(compressed)
|
|
115
|
+
} else {
|
|
116
|
+
compressed.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body))
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { KoaMiddleware } from './types.js'
|
|
2
|
+
|
|
3
|
+
const allowMethods = 'GET,HEAD,PUT,POST,DELETE,PATCH'
|
|
4
|
+
|
|
5
|
+
const appendVary = (current: string, field: string): string => {
|
|
6
|
+
const fields = current.split(',').map(it => it.trim().toLowerCase())
|
|
7
|
+
if (fields.includes('*') || fields.includes(field.toLowerCase())) {
|
|
8
|
+
return current
|
|
9
|
+
}
|
|
10
|
+
return current.trim() ? `${current}, ${field}` : field
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Permissive CORS for any origin without credentials. Preflights (OPTIONS with
|
|
15
|
+
* Access-Control-Request-Method) are answered with 204 and echo the requested headers.
|
|
16
|
+
* The CORS headers survive an error thrown by the downstream handler.
|
|
17
|
+
*/
|
|
18
|
+
export const createCorsMiddleware = ({ exposeHeaders }: { exposeHeaders: readonly string[] }): KoaMiddleware<unknown> => {
|
|
19
|
+
const exposeHeadersValue = exposeHeaders.join(',')
|
|
20
|
+
|
|
21
|
+
return async (ctx, next) => {
|
|
22
|
+
ctx.vary('Origin')
|
|
23
|
+
|
|
24
|
+
if (ctx.method === 'OPTIONS') {
|
|
25
|
+
if (!ctx.get('Access-Control-Request-Method')) {
|
|
26
|
+
return await next()
|
|
27
|
+
}
|
|
28
|
+
ctx.set('Access-Control-Allow-Origin', '*')
|
|
29
|
+
ctx.set('Access-Control-Allow-Methods', allowMethods)
|
|
30
|
+
const requestHeaders = ctx.get('Access-Control-Request-Headers')
|
|
31
|
+
if (requestHeaders) {
|
|
32
|
+
ctx.set('Access-Control-Allow-Headers', requestHeaders)
|
|
33
|
+
}
|
|
34
|
+
ctx.status = 204
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const corsHeaders: Record<string, string> = { 'Access-Control-Allow-Origin': '*' }
|
|
39
|
+
if (exposeHeadersValue) {
|
|
40
|
+
corsHeaders['Access-Control-Expose-Headers'] = exposeHeadersValue
|
|
41
|
+
}
|
|
42
|
+
ctx.set(corsHeaders)
|
|
43
|
+
try {
|
|
44
|
+
return await next()
|
|
45
|
+
} catch (error) {
|
|
46
|
+
// Koa's error handler resets the response headers and applies `error.headers` instead.
|
|
47
|
+
if (typeof error === 'object' && error !== null) {
|
|
48
|
+
const errorHeaders: unknown = Reflect.get(error, 'headers')
|
|
49
|
+
const headers: Record<string, unknown> = typeof errorHeaders === 'object' && errorHeaders !== null ? { ...errorHeaders } : {}
|
|
50
|
+
const vary = headers.vary ?? headers.Vary
|
|
51
|
+
delete headers.Vary
|
|
52
|
+
Reflect.set(error, 'headers', {
|
|
53
|
+
...headers,
|
|
54
|
+
...corsHeaders,
|
|
55
|
+
vary: appendVary(typeof vary === 'string' ? vary : '', 'Origin'),
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
throw error
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { IncomingMessage } from 'node:http'
|
|
2
|
+
import { Readable, Transform } from 'node:stream'
|
|
3
|
+
import { createBrotliDecompress, createUnzip } from 'node:zlib'
|
|
4
|
+
import { KoaContext, KoaMiddleware } from './types.js'
|
|
5
|
+
|
|
6
|
+
declare module 'koa' {
|
|
7
|
+
interface Request {
|
|
8
|
+
/** The parsed JSON or form body; `{}` for any other content type. */
|
|
9
|
+
body?: unknown
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const byteUnits: Readonly<Record<string, number>> = {
|
|
14
|
+
b: 1,
|
|
15
|
+
kb: 1024,
|
|
16
|
+
mb: 1024 ** 2,
|
|
17
|
+
gb: 1024 ** 3,
|
|
18
|
+
tb: 1024 ** 4,
|
|
19
|
+
pb: 1024 ** 5,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** `1048576`, `512kb`, `1.5 MB`: binary units, as `requestBodySize` has always been read. `undefined` when invalid. */
|
|
23
|
+
export const parseByteSize = (value: string): number | undefined => {
|
|
24
|
+
const match = /^(\d+(?:\.\d+)?) *(b|kb|mb|gb|tb|pb)?$/i.exec(value.trim())
|
|
25
|
+
if (!match) {
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
const bytes = Math.floor(Number(match[1]) * byteUnits[(match[2] ?? 'b').toLowerCase()])
|
|
29
|
+
return Number.isSafeInteger(bytes) ? bytes : undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const jsonTypes: ReadonlySet<string> = new Set([
|
|
33
|
+
'application/json',
|
|
34
|
+
'application/json-patch+json',
|
|
35
|
+
'application/vnd.api+json',
|
|
36
|
+
'application/csp-report',
|
|
37
|
+
'application/scim+json',
|
|
38
|
+
])
|
|
39
|
+
const formType = 'application/x-www-form-urlencoded'
|
|
40
|
+
|
|
41
|
+
const mediaTypePattern = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/
|
|
42
|
+
const mediaTypeParameterPattern =
|
|
43
|
+
/; *[!#$%&'*+\-.0-9A-Z^_`a-z|~]+ *= *(?:"(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+\-.0-9A-Z^_`a-z|~]+) */y
|
|
44
|
+
|
|
45
|
+
/** The lower-cased `type/subtype` of a well-formed Content-Type header; a malformed one matches no parser. */
|
|
46
|
+
export const parseMediaType = (header: string): string | undefined => {
|
|
47
|
+
// clients commonly send a trailing `;`, e.g. `application/json;`
|
|
48
|
+
const value = header.replace(/;$/, '')
|
|
49
|
+
const separator = value.indexOf(';')
|
|
50
|
+
const match = mediaTypePattern.exec(separator === -1 ? value : value.slice(0, separator))
|
|
51
|
+
if (!match) {
|
|
52
|
+
return undefined
|
|
53
|
+
}
|
|
54
|
+
if (separator !== -1) {
|
|
55
|
+
mediaTypeParameterPattern.lastIndex = separator
|
|
56
|
+
while (mediaTypeParameterPattern.lastIndex < value.length) {
|
|
57
|
+
if (!mediaTypeParameterPattern.test(value)) {
|
|
58
|
+
return undefined
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return `${match[1]}/${match[2]}`.toLowerCase()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
type BodyReadFailure = { readonly status: 400 | 413 | 415 | 500; readonly message?: string }
|
|
66
|
+
|
|
67
|
+
class BodyReadError extends Error {
|
|
68
|
+
constructor(readonly failure: BodyReadFailure) {
|
|
69
|
+
super(failure.message ?? `HTTP ${failure.status}`)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const tooLarge: BodyReadFailure = { status: 413, message: 'request entity too large' }
|
|
74
|
+
const aborted: BodyReadFailure = { status: 400, message: 'request aborted' }
|
|
75
|
+
|
|
76
|
+
const createDecompressor = (encoding: string): Transform | undefined => {
|
|
77
|
+
switch (encoding) {
|
|
78
|
+
case 'identity':
|
|
79
|
+
return undefined
|
|
80
|
+
case 'gzip':
|
|
81
|
+
case 'deflate':
|
|
82
|
+
return createUnzip()
|
|
83
|
+
case 'br':
|
|
84
|
+
return createBrotliDecompress()
|
|
85
|
+
default:
|
|
86
|
+
throw new BodyReadError({ status: 415 })
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Compressed data can be a little larger than what it inflates to (stored blocks, headers), never by much. */
|
|
91
|
+
const compressedLimit = (limit: number): number => limit + Math.ceil(limit / 1024) + 1024
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Reads the body as UTF-8 text. `limit` caps the decompressed size, so a compressed body cannot expand past it, and the
|
|
95
|
+
* bytes received, so one cannot send endless input that inflates to nothing. On a failure the request is left paused
|
|
96
|
+
* and unread, as before.
|
|
97
|
+
*/
|
|
98
|
+
export const readRequestText = (request: IncomingMessage, limit: number): Promise<string> => {
|
|
99
|
+
const encoding = request.headers['content-encoding'] ?? 'identity'
|
|
100
|
+
const contentLength = request.headers['content-length'] !== undefined ? Number(request.headers['content-length']) : undefined
|
|
101
|
+
const wireLimit = encoding === 'identity' ? limit : compressedLimit(limit)
|
|
102
|
+
if (contentLength !== undefined && contentLength > wireLimit) {
|
|
103
|
+
return Promise.reject(new BodyReadError(tooLarge))
|
|
104
|
+
}
|
|
105
|
+
const declaredLength = encoding === 'identity' ? contentLength : undefined
|
|
106
|
+
// a consumed or closed request emits nothing more, so waiting for it would never settle
|
|
107
|
+
if (request.readableEnded) {
|
|
108
|
+
return Promise.reject(new BodyReadError({ status: 500, message: 'request body was already read' }))
|
|
109
|
+
}
|
|
110
|
+
if (request.destroyed || request.readableAborted || !request.readable) {
|
|
111
|
+
return Promise.reject(new BodyReadError(aborted))
|
|
112
|
+
}
|
|
113
|
+
let decompressor: Transform | undefined
|
|
114
|
+
try {
|
|
115
|
+
decompressor = createDecompressor(encoding)
|
|
116
|
+
} catch (error) {
|
|
117
|
+
return Promise.reject(error)
|
|
118
|
+
}
|
|
119
|
+
const source: Readable = decompressor ? request.pipe(decompressor) : request
|
|
120
|
+
|
|
121
|
+
return new Promise((resolve, reject) => {
|
|
122
|
+
const chunks: Buffer[] = []
|
|
123
|
+
let received = 0
|
|
124
|
+
let receivedCompressed = 0
|
|
125
|
+
let settled = false
|
|
126
|
+
|
|
127
|
+
const cleanup = () => {
|
|
128
|
+
source.off('data', onData)
|
|
129
|
+
source.off('end', onEnd)
|
|
130
|
+
source.off('error', onSourceError)
|
|
131
|
+
request.off('data', onCompressedData)
|
|
132
|
+
request.off('error', onAborted)
|
|
133
|
+
request.off('close', onClose)
|
|
134
|
+
}
|
|
135
|
+
const fail = (failure: BodyReadFailure) => {
|
|
136
|
+
if (settled) {
|
|
137
|
+
return
|
|
138
|
+
}
|
|
139
|
+
settled = true
|
|
140
|
+
cleanup()
|
|
141
|
+
if (decompressor) {
|
|
142
|
+
request.unpipe(decompressor)
|
|
143
|
+
decompressor.destroy()
|
|
144
|
+
}
|
|
145
|
+
source.pause()
|
|
146
|
+
reject(new BodyReadError(failure))
|
|
147
|
+
}
|
|
148
|
+
const onData = (chunk: Buffer) => {
|
|
149
|
+
received += chunk.length
|
|
150
|
+
if (received > limit) {
|
|
151
|
+
fail(tooLarge)
|
|
152
|
+
} else {
|
|
153
|
+
chunks.push(chunk)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const onCompressedData = (chunk: Buffer) => {
|
|
157
|
+
receivedCompressed += chunk.length
|
|
158
|
+
if (receivedCompressed > wireLimit) {
|
|
159
|
+
fail(tooLarge)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const onEnd = () => {
|
|
163
|
+
if (declaredLength !== undefined && received !== declaredLength) {
|
|
164
|
+
fail({ status: 400, message: 'request size did not match content length' })
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
settled = true
|
|
168
|
+
cleanup()
|
|
169
|
+
// strips a UTF-8 BOM and replaces invalid sequences, as the previous parser did
|
|
170
|
+
resolve(new TextDecoder().decode(Buffer.concat(chunks)))
|
|
171
|
+
}
|
|
172
|
+
const onSourceError = () => fail(decompressor === undefined ? aborted : { status: 400, message: 'request body could not be decompressed' })
|
|
173
|
+
const onAborted = () => fail(aborted)
|
|
174
|
+
const onClose = () => {
|
|
175
|
+
if (!request.complete) {
|
|
176
|
+
fail(aborted)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
source.on('data', onData)
|
|
181
|
+
source.on('end', onEnd)
|
|
182
|
+
source.on('error', onSourceError)
|
|
183
|
+
if (decompressor) {
|
|
184
|
+
request.on('data', onCompressedData)
|
|
185
|
+
}
|
|
186
|
+
request.on('error', onAborted)
|
|
187
|
+
request.on('close', onClose)
|
|
188
|
+
})
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const strictJsonStart = /^[ \t\n\r]*[[{]/
|
|
192
|
+
// any spelling of a `"__proto__":` key, escapes included; only then is the parsed value scanned
|
|
193
|
+
const suspectProtoKey =
|
|
194
|
+
/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/
|
|
195
|
+
|
|
196
|
+
const hasOwnProtoKey = (root: object): boolean => {
|
|
197
|
+
const pending: object[] = [root]
|
|
198
|
+
for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
|
|
199
|
+
if (Object.hasOwn(node, '__proto__')) {
|
|
200
|
+
return true
|
|
201
|
+
}
|
|
202
|
+
for (const value of Object.values(node)) {
|
|
203
|
+
if (typeof value === 'object' && value !== null) {
|
|
204
|
+
pending.push(value)
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return false
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
type JsonParseResult = { readonly ok: true; readonly value: unknown } | { readonly ok: false }
|
|
212
|
+
|
|
213
|
+
/** Only an object or an array, and no `__proto__` key anywhere (prototype poisoning). An empty body is `{}`. */
|
|
214
|
+
export const parseJsonBody = (text: string): JsonParseResult => {
|
|
215
|
+
if (text === '') {
|
|
216
|
+
return { ok: true, value: {} }
|
|
217
|
+
}
|
|
218
|
+
if (!strictJsonStart.test(text)) {
|
|
219
|
+
return { ok: false }
|
|
220
|
+
}
|
|
221
|
+
let value: unknown
|
|
222
|
+
try {
|
|
223
|
+
value = JSON.parse(text)
|
|
224
|
+
} catch {
|
|
225
|
+
return { ok: false }
|
|
226
|
+
}
|
|
227
|
+
if (typeof value === 'object' && value !== null && suspectProtoKey.test(text) && hasOwnProtoKey(value)) {
|
|
228
|
+
return { ok: false }
|
|
229
|
+
}
|
|
230
|
+
return { ok: true, value }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const maxFormParameters = 1000
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Flat `application/x-www-form-urlencoded`: a repeated key collects its values into an array. Only the first 1000
|
|
237
|
+
* pairs are read, and keys naming an `Object.prototype` member (`__proto__`, `constructor`, …) are dropped.
|
|
238
|
+
*/
|
|
239
|
+
export const parseFormBody = (text: string): Record<string, string | string[]> => {
|
|
240
|
+
const result: Record<string, string | string[]> = {}
|
|
241
|
+
let count = 0
|
|
242
|
+
for (const [key, value] of new URLSearchParams(text)) {
|
|
243
|
+
if (++count > maxFormParameters) {
|
|
244
|
+
break
|
|
245
|
+
}
|
|
246
|
+
if (key === '' || Object.hasOwn(Object.prototype, key)) {
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
249
|
+
const existing = result[key]
|
|
250
|
+
result[key] = existing === undefined ? value : [...(Array.isArray(existing) ? existing : [existing]), value]
|
|
251
|
+
}
|
|
252
|
+
return result
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export const defaultJsonBodyLimit = 1024 ** 2
|
|
256
|
+
export const defaultFormBodyLimit = 56 * 1024
|
|
257
|
+
|
|
258
|
+
/** Bytes after decompression. */
|
|
259
|
+
export interface RequestBodyLimits {
|
|
260
|
+
readonly json: number
|
|
261
|
+
readonly form: number
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const parseBody = async (ctx: KoaContext<unknown>, limits: RequestBodyLimits): Promise<unknown> => {
|
|
265
|
+
const type = parseMediaType(ctx.get('Content-Type'))
|
|
266
|
+
if (type !== undefined && jsonTypes.has(type)) {
|
|
267
|
+
const parsed = parseJsonBody(await readRequestText(ctx.req, limits.json))
|
|
268
|
+
return parsed.ok ? parsed.value : ctx.throw(400)
|
|
269
|
+
}
|
|
270
|
+
if (type === formType) {
|
|
271
|
+
return parseFormBody(await readRequestText(ctx.req, limits.form))
|
|
272
|
+
}
|
|
273
|
+
return {}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Parses JSON and form bodies into `ctx.request.body`, unless an earlier middleware set it. Other content types are not
|
|
278
|
+
* read, so a handler can still stream the request (the import API reads `application/x-ndjson` itself).
|
|
279
|
+
*/
|
|
280
|
+
export const createRequestBodyMiddleware = (limits: RequestBodyLimits): KoaMiddleware<unknown> => async (ctx, next) => {
|
|
281
|
+
if (ctx.request.body !== undefined) {
|
|
282
|
+
return await next()
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
ctx.request.body = await parseBody(ctx, limits)
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (error instanceof BodyReadError) {
|
|
288
|
+
const { status, message } = error.failure
|
|
289
|
+
// without a message the response carries the status text, e.g. `Unsupported Media Type`
|
|
290
|
+
return message === undefined ? ctx.throw(status) : ctx.throw(status, message)
|
|
291
|
+
}
|
|
292
|
+
throw error
|
|
293
|
+
}
|
|
294
|
+
await next()
|
|
295
|
+
}
|
|
@@ -4,6 +4,7 @@ import { validateRequestMemoryBudgetOptions } from '@contember/database'
|
|
|
4
4
|
import { upperCaseFirst } from '../utils/strings.js'
|
|
5
5
|
import ipaddr from 'ipaddr.js'
|
|
6
6
|
import { EgressError, EgressPolicy } from '@contember/engine-common'
|
|
7
|
+
import { parseByteSize } from '../application/requestBody.js'
|
|
7
8
|
|
|
8
9
|
const dbConfigRequired = {
|
|
9
10
|
host: Typesafe.string,
|
|
@@ -193,7 +194,13 @@ export const serverConfigSchema = Typesafe.partial({
|
|
|
193
194
|
const optionsError = validateRequestMemoryBudgetOptions({ warnBytes, maxBytes })
|
|
194
195
|
return optionsError ? Typesafe.fail(path, optionsError) : { warnBytes, maxBytes }
|
|
195
196
|
},
|
|
196
|
-
requestBodySize:
|
|
197
|
+
requestBodySize: (input: unknown, path: PropertyKey[] = []): number | undefined => {
|
|
198
|
+
const value = Typesafe.string(input, path)
|
|
199
|
+
if (value === '') {
|
|
200
|
+
return undefined
|
|
201
|
+
}
|
|
202
|
+
return parseByteSize(value) ?? Typesafe.fail(path, 'expected a size such as 1048576, 512kb or 10mb')
|
|
203
|
+
},
|
|
197
204
|
// Allows clients to opt in (via the X-Contember-Force-Ok request header) to receiving HTTP 200
|
|
198
205
|
// for GraphQL API responses, keeping error info in the JSON body. Defaults to enabled; set to
|
|
199
206
|
// false to forbid the header entirely. Accepts boolean-ish strings ('true'/'1'/'on'/...).
|
package/src/graphql/execution.ts
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
validate,
|
|
11
11
|
validateSchema,
|
|
12
12
|
} from 'graphql'
|
|
13
|
-
import { LRUCache } from '
|
|
13
|
+
import { LRUCache } from '@contember/utilities'
|
|
14
14
|
import { createHash } from 'node:crypto'
|
|
15
15
|
import { Request, Response } from 'koa'
|
|
16
16
|
import { logger } from '@contember/logger'
|
|
@@ -58,14 +58,8 @@ export const createGraphQLQueryHandler = <Context>({
|
|
|
58
58
|
getMemoryBudget,
|
|
59
59
|
}: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {
|
|
60
60
|
let schemaValidated = false
|
|
61
|
-
const hitCache = new LRUCache<string, true>({
|
|
62
|
-
|
|
63
|
-
ttl: hitCacheMaxAgeSeconds * 1000,
|
|
64
|
-
})
|
|
65
|
-
const documentCache = new LRUCache<string, DocumentNode>({
|
|
66
|
-
max: documentCacheMax,
|
|
67
|
-
ttl: documentCacheMaxAgeSeconds * 1000,
|
|
68
|
-
})
|
|
61
|
+
const hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })
|
|
62
|
+
const documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })
|
|
69
63
|
let lastPrune = Date.now()
|
|
70
64
|
|
|
71
65
|
return async ({ request, response, createContext }) => {
|