@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
package/src/providers.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { generateUuidV4, generateUuidV7 } from '@contember/utilities'
|
|
2
2
|
import bcrypt from 'bcryptjs'
|
|
3
3
|
import crypto, { BinaryLike } from 'node:crypto'
|
|
4
4
|
|
|
5
5
|
export const createProviders = () => ({
|
|
6
|
-
uuid: ({ version = 4 }: { version?: 4 | 7 } = {}) => version === 4 ?
|
|
6
|
+
uuid: ({ version = 4 }: { version?: 4 | 7 } = {}) => version === 4 ? generateUuidV4() : generateUuidV7(),
|
|
7
7
|
now: () => new Date(),
|
|
8
8
|
bcrypt: async (value: string) => await bcrypt.hash(value, 10),
|
|
9
9
|
bcryptCompare: (data: any, hash: string) => bcrypt.compare(data, hash),
|
|
@@ -4,6 +4,7 @@ import * as Typesafe from '@contember/typesafe'
|
|
|
4
4
|
import { ParseError } from '@contember/typesafe'
|
|
5
5
|
import { Command, CommandArgsMap, CommandName } from './Command.js'
|
|
6
6
|
import { DatabaseContext, StageBySlugQuery } from '@contember/engine-system-api'
|
|
7
|
+
import { isImpossibleCalendarDate } from '@contember/engine-content-api'
|
|
7
8
|
import { DbColumnSchema, TransferMapping, TransferTableMapping } from './TransferMapping.js'
|
|
8
9
|
import { ContentSchemaTransferMappingFactory } from './ContentSchemaTransferMappingFactory.js'
|
|
9
10
|
import { SystemSchemaTransferMappingFactory } from './SystemSchemaTransferMappingFactory.js'
|
|
@@ -66,6 +67,15 @@ const listType = <T extends Typesafe.Json>(arrayType: Typesafe.Type<T>): Typesaf
|
|
|
66
67
|
}
|
|
67
68
|
}
|
|
68
69
|
|
|
70
|
+
// PostgreSQL would fail the whole batch insert on an impossible date with a server error that names neither column nor row.
|
|
71
|
+
const calendarDate: Typesafe.Type<string> = (input: unknown, path: PropertyKey[] = []) => {
|
|
72
|
+
const value = Typesafe.string(input, path)
|
|
73
|
+
if (isImpossibleCalendarDate(value)) {
|
|
74
|
+
throw new ParseError(path, `${JSON.stringify(value)} is not a valid date`)
|
|
75
|
+
}
|
|
76
|
+
return value
|
|
77
|
+
}
|
|
78
|
+
|
|
69
79
|
type CommandProcessor<T extends CommandName> = (it: CommandIterator<T>) => Promise<CommandIterator | null>
|
|
70
80
|
type CommandProcessorMap<T extends CommandName> = { [N in CommandName]?: N extends T ? CommandProcessor<N> : undefined }
|
|
71
81
|
|
|
@@ -253,7 +263,14 @@ export class ImportExecutor {
|
|
|
253
263
|
insertContext.rows.push(insertContext.rowParser(values))
|
|
254
264
|
} catch (e) {
|
|
255
265
|
if (e instanceof ParseError) {
|
|
256
|
-
|
|
266
|
+
const rowNumber = insertContext.insertedRowCount + insertContext.rows.length + 1
|
|
267
|
+
// The row parser is a tuple over the insertBegin columns, so the first path segment is the column index.
|
|
268
|
+
const [columnIndex, ...valuePath] = e.path
|
|
269
|
+
const columnName = columnIndex !== undefined ? options.columns[Number(columnIndex)] : undefined
|
|
270
|
+
const elementLocation = valuePath.length > 0 ? `, element /${valuePath.map(String).join('/')}` : ''
|
|
271
|
+
const location = columnName !== undefined ? `table ${options.table}, column ${columnName}${elementLocation}` : `table ${options.table}`
|
|
272
|
+
const reason = columnName !== undefined ? e.reason : e.message
|
|
273
|
+
throw new ImportError(`Invalid row #${rowNumber} ${JSON.stringify(values)} for ${location}: ${reason}`)
|
|
257
274
|
} else {
|
|
258
275
|
throw e
|
|
259
276
|
}
|
|
@@ -443,13 +460,14 @@ export class ImportExecutor {
|
|
|
443
460
|
case Model.ColumnType.Uuid:
|
|
444
461
|
case Model.ColumnType.String:
|
|
445
462
|
case Model.ColumnType.Enum:
|
|
446
|
-
case Model.ColumnType.DateTime:
|
|
447
463
|
case Model.ColumnType.Time:
|
|
448
|
-
case Model.ColumnType.Date:
|
|
449
464
|
case Model.ColumnType.Json:
|
|
450
465
|
// Numeric is transferred as a string to avoid JS float precision loss.
|
|
451
466
|
case Model.ColumnType.Numeric:
|
|
452
467
|
return column.list ? listType(Typesafe.array(Typesafe.string)) : Typesafe.string
|
|
468
|
+
case Model.ColumnType.Date:
|
|
469
|
+
case Model.ColumnType.DateTime:
|
|
470
|
+
return column.list ? listType(Typesafe.array(calendarDate)) : calendarDate
|
|
453
471
|
case Model.ColumnType.Int:
|
|
454
472
|
case Model.ColumnType.Double:
|
|
455
473
|
return column.list ? listType(Typesafe.array(Typesafe.number)) : Typesafe.number
|
package/src/tsconfig.json
CHANGED
|
@@ -19,7 +19,9 @@
|
|
|
19
19
|
{ "path": "../../schema-migrations/src" },
|
|
20
20
|
{ "path": "../../schema-utils/src" },
|
|
21
21
|
{ "path": "../../schema-utils/src" },
|
|
22
|
+
{ "path": "../../sentry-client/src" },
|
|
22
23
|
{ "path": "../../telemetry/src" },
|
|
23
|
-
{ "path": "../../typesafe/src" }
|
|
24
|
+
{ "path": "../../typesafe/src" },
|
|
25
|
+
{ "path": "../../utilities/src" }
|
|
24
26
|
]
|
|
25
27
|
}
|
package/src/utils/sentry.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import * as Sentry from '@sentry/node'
|
|
2
1
|
import { LogEntry, LoggerHandler, LogLevel, LogLevelName, LogLevels } from '@contember/logger'
|
|
2
|
+
import { createSentryClient, installProcessHandlers, SentryClient, SeverityLevel } from '@contember/sentry-client'
|
|
3
3
|
import { LoggerRequestBody } from '../application/index.js'
|
|
4
4
|
|
|
5
|
-
const logLevelMapping: Record<LogLevelName,
|
|
5
|
+
const logLevelMapping: Record<LogLevelName, SeverityLevel> = {
|
|
6
6
|
crit: 'fatal',
|
|
7
7
|
error: 'error',
|
|
8
8
|
warn: 'warning',
|
|
@@ -10,9 +10,12 @@ const logLevelMapping: Record<LogLevelName, Sentry.SeverityLevel> = {
|
|
|
10
10
|
info: 'info',
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
const stringAttribute = (value: unknown): string | undefined => typeof value === 'string' ? value : undefined
|
|
14
|
+
|
|
13
15
|
export class SentryLoggerHandler implements LoggerHandler {
|
|
14
16
|
constructor(
|
|
15
17
|
private readonly logLevel: LogLevel,
|
|
18
|
+
private readonly client: SentryClient,
|
|
16
19
|
) {
|
|
17
20
|
}
|
|
18
21
|
|
|
@@ -24,31 +27,17 @@ export class SentryLoggerHandler implements LoggerHandler {
|
|
|
24
27
|
if (!entry.error || entry.level.value < this.logLevel.value) {
|
|
25
28
|
return
|
|
26
29
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const traceId = entry.loggerAttributes.traceId
|
|
39
|
-
const spanId = entry.loggerAttributes.spanId
|
|
40
|
-
return {
|
|
41
|
-
...event,
|
|
42
|
-
request: {
|
|
43
|
-
url: entry.loggerAttributes.url ?? entry.ownAttributes.url,
|
|
44
|
-
data: entry.loggerAttributes[LoggerRequestBody],
|
|
45
|
-
},
|
|
46
|
-
...(typeof traceId === 'string' && typeof spanId === 'string'
|
|
47
|
-
? { contexts: { ...event.contexts, trace: { trace_id: traceId, span_id: spanId } } }
|
|
48
|
-
: {}),
|
|
49
|
-
}
|
|
50
|
-
})
|
|
51
|
-
return scope
|
|
30
|
+
const attribute = (name: string): string | undefined => stringAttribute(entry.loggerAttributes[name] ?? entry.ownAttributes[name])
|
|
31
|
+
const traceId = stringAttribute(entry.loggerAttributes.traceId)
|
|
32
|
+
const spanId = stringAttribute(entry.loggerAttributes.spanId)
|
|
33
|
+
this.client.captureException(entry.error, {
|
|
34
|
+
level: logLevelMapping[entry.level.name],
|
|
35
|
+
tags: { project: attribute('project'), projectGroup: attribute('projectGroup'), module: attribute('module') },
|
|
36
|
+
user: { id: attribute('user') },
|
|
37
|
+
extra: { requestId: entry.loggerAttributes.requestId },
|
|
38
|
+
// the request logger sets `uri`, already masked by maskRequestUri
|
|
39
|
+
request: { url: attribute('uri'), data: entry.loggerAttributes[LoggerRequestBody] },
|
|
40
|
+
...(traceId !== undefined && spanId !== undefined ? { contexts: { trace: { trace_id: traceId, span_id: spanId } } } : {}),
|
|
52
41
|
})
|
|
53
42
|
}
|
|
54
43
|
|
|
@@ -56,20 +45,34 @@ export class SentryLoggerHandler implements LoggerHandler {
|
|
|
56
45
|
}
|
|
57
46
|
}
|
|
58
47
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
export const filterSentryIntegrations = (integrations: SentryIntegration[]): SentryIntegration[] =>
|
|
64
|
-
integrations.filter(integration => !['Console', 'Http', 'Undici'].includes(integration.name))
|
|
48
|
+
export interface SentryLoggerHandlerOptions {
|
|
49
|
+
/** Reported as the SDK version; the client is released together with the server, so this is the server version. */
|
|
50
|
+
readonly version?: string
|
|
51
|
+
}
|
|
65
52
|
|
|
66
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Reports logged errors (warn and up) and uncaught exceptions and unhandled rejections of the process.
|
|
55
|
+
* Release, environment and server name come from SENTRY_RELEASE, SENTRY_ENVIRONMENT and SENTRY_NAME (default: the host name). Nothing instruments outgoing requests, whose
|
|
56
|
+
* URLs may carry a webhook credential.
|
|
57
|
+
*/
|
|
58
|
+
export const createSentryLoggerHandler = (dsn?: string, options: SentryLoggerHandlerOptions = {}): null | LoggerHandler => {
|
|
67
59
|
if (!dsn) {
|
|
68
60
|
return null
|
|
69
61
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
62
|
+
let client: SentryClient
|
|
63
|
+
try {
|
|
64
|
+
client = createSentryClient({
|
|
65
|
+
dsn,
|
|
66
|
+
release: process.env.SENTRY_RELEASE || undefined,
|
|
67
|
+
environment: process.env.SENTRY_ENVIRONMENT || undefined,
|
|
68
|
+
serverName: process.env.SENTRY_NAME || undefined,
|
|
69
|
+
version: options.version,
|
|
70
|
+
})
|
|
71
|
+
} catch (error) {
|
|
72
|
+
// as before: an invalid DSN turns reporting off instead of keeping the server from starting
|
|
73
|
+
console.error(`${error instanceof Error ? error.message : String(error)}; errors are not reported to Sentry`)
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
installProcessHandlers(client)
|
|
77
|
+
return new SentryLoggerHandler(LogLevels.warn, client)
|
|
75
78
|
}
|
|
@@ -50,15 +50,17 @@ export const createDefaultLogger = (): Logger => {
|
|
|
50
50
|
formatters: {
|
|
51
51
|
pid: () => undefined,
|
|
52
52
|
loggerId: () => undefined,
|
|
53
|
-
uri: ({ attributes,
|
|
53
|
+
uri: ({ attributes, style }) => {
|
|
54
54
|
const color = attributes.status === undefined
|
|
55
|
-
?
|
|
55
|
+
? 'cyan'
|
|
56
56
|
: attributes.status < 300
|
|
57
|
-
?
|
|
58
|
-
:
|
|
57
|
+
? 'green'
|
|
58
|
+
: 'yellowBright'
|
|
59
59
|
const timeInfo = attributes.totalTimeMs !== undefined ? ` ${attributes.totalTimeMs}ms` : ''
|
|
60
60
|
const statusInfo = attributes.status !== undefined ? ` [${attributes.status}]` : ''
|
|
61
|
-
return {
|
|
61
|
+
return {
|
|
62
|
+
line: style(color, `${attributes.method}${statusInfo} ${attributes.uri}${timeInfo} ${style(['white', 'dim'], '#' + attributes.requestId)}`),
|
|
63
|
+
}
|
|
62
64
|
},
|
|
63
65
|
method: () => undefined,
|
|
64
66
|
requestId: () => undefined,
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import Koa from 'koa'
|
|
3
|
+
import { IncomingHttpHeaders, request, Server } from 'node:http'
|
|
4
|
+
import { AddressInfo } from 'node:net'
|
|
5
|
+
import { Readable } from 'node:stream'
|
|
6
|
+
import { gunzipSync, gzipSync, inflateSync, zstdDecompressSync } from 'node:zlib'
|
|
7
|
+
import { createCompressionMiddleware, isCompressibleType, negotiateEncoding } from '../../../src/application/compression.js'
|
|
8
|
+
|
|
9
|
+
describe('negotiateEncoding', () => {
|
|
10
|
+
test('no header, identity, or only unsupported encodings: no compression', () => {
|
|
11
|
+
for (const header of ['', 'identity', 'br', 'compress', 'gzip;q=0', 'GZIP;q=0, deflate;q=0']) {
|
|
12
|
+
expect(negotiateEncoding(header)).toBeUndefined()
|
|
13
|
+
}
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
test('prefers zstd, then gzip, then deflate, at equal quality', () => {
|
|
17
|
+
expect(negotiateEncoding('gzip, deflate, br, zstd')).toBe('zstd')
|
|
18
|
+
expect(negotiateEncoding('deflate, gzip, br')).toBe('gzip')
|
|
19
|
+
expect(negotiateEncoding('deflate')).toBe('deflate')
|
|
20
|
+
expect(negotiateEncoding('GZip')).toBe('gzip')
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
test('quality decides first', () => {
|
|
24
|
+
expect(negotiateEncoding('gzip;q=0.5, deflate')).toBe('deflate')
|
|
25
|
+
expect(negotiateEncoding('zstd;q=0.9, deflate;q=1')).toBe('deflate')
|
|
26
|
+
expect(negotiateEncoding('gzip;q=abc, deflate;q=0.1')).toBe('deflate')
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test('a bare * is gzip, and * covers what is not listed', () => {
|
|
30
|
+
expect(negotiateEncoding('*')).toBe('gzip')
|
|
31
|
+
expect(negotiateEncoding('*;q=0.5, zstd;q=0.1')).toBe('gzip')
|
|
32
|
+
expect(negotiateEncoding('*, identity;q=0')).toBe('zstd')
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
test('identity wins only with a higher quality', () => {
|
|
36
|
+
expect(negotiateEncoding('identity;q=1, gzip;q=0.5')).toBeUndefined()
|
|
37
|
+
expect(negotiateEncoding('identity, gzip')).toBe('gzip')
|
|
38
|
+
expect(negotiateEncoding('identity;q=0, gzip;q=0.1')).toBe('gzip')
|
|
39
|
+
})
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('isCompressibleType', () => {
|
|
43
|
+
for (
|
|
44
|
+
const type of [
|
|
45
|
+
'application/json',
|
|
46
|
+
'text/html',
|
|
47
|
+
'text/plain',
|
|
48
|
+
'text/css',
|
|
49
|
+
'text/javascript',
|
|
50
|
+
'application/javascript',
|
|
51
|
+
'image/svg+xml',
|
|
52
|
+
'application/manifest+json',
|
|
53
|
+
'Application/JSON',
|
|
54
|
+
]
|
|
55
|
+
) {
|
|
56
|
+
expect(isCompressibleType(type)).toBe(true)
|
|
57
|
+
}
|
|
58
|
+
for (const type of ['', 'image/png', 'font/woff2', 'application/octet-stream', 'application/x-ndjson']) {
|
|
59
|
+
expect(isCompressibleType(type)).toBe(false)
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
type Response = { status: number; headers: IncomingHttpHeaders; body: Buffer }
|
|
64
|
+
|
|
65
|
+
const get = (port: number, path: string, headers: Record<string, string>, method = 'GET'): Promise<Response> =>
|
|
66
|
+
new Promise((resolve, reject) => {
|
|
67
|
+
const req = request({ host: '127.0.0.1', port, path, method, headers }, res => {
|
|
68
|
+
const chunks: Buffer[] = []
|
|
69
|
+
res.on('data', chunk => chunks.push(chunk))
|
|
70
|
+
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks) }))
|
|
71
|
+
})
|
|
72
|
+
req.on('error', reject)
|
|
73
|
+
req.end()
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
describe('compression middleware', () => {
|
|
77
|
+
let server: Server
|
|
78
|
+
let port: number
|
|
79
|
+
const large = { data: 'x'.repeat(2000) }
|
|
80
|
+
const ndjson = '{"a":1}\n'.repeat(5)
|
|
81
|
+
|
|
82
|
+
beforeAll(async () => {
|
|
83
|
+
const koa = new Koa()
|
|
84
|
+
koa.silent = true
|
|
85
|
+
koa.use(createCompressionMiddleware())
|
|
86
|
+
koa.use(async ctx => {
|
|
87
|
+
switch (ctx.path) {
|
|
88
|
+
case '/large':
|
|
89
|
+
ctx.body = large
|
|
90
|
+
break
|
|
91
|
+
case '/small':
|
|
92
|
+
ctx.body = { data: 'x' }
|
|
93
|
+
break
|
|
94
|
+
case '/png':
|
|
95
|
+
ctx.type = 'image/png'
|
|
96
|
+
ctx.body = Buffer.alloc(2000)
|
|
97
|
+
break
|
|
98
|
+
case '/ndjson':
|
|
99
|
+
ctx.compress = true
|
|
100
|
+
ctx.type = 'application/x-ndjson'
|
|
101
|
+
ctx.body = Readable.from([ndjson])
|
|
102
|
+
break
|
|
103
|
+
case '/disabled':
|
|
104
|
+
ctx.compress = false
|
|
105
|
+
ctx.body = large
|
|
106
|
+
break
|
|
107
|
+
case '/no-transform':
|
|
108
|
+
ctx.set('Cache-Control', 'private, no-transform')
|
|
109
|
+
ctx.body = large
|
|
110
|
+
break
|
|
111
|
+
case '/encoded':
|
|
112
|
+
ctx.set('Content-Encoding', 'gzip')
|
|
113
|
+
ctx.type = 'text/plain'
|
|
114
|
+
ctx.body = gzipSync('y'.repeat(2000))
|
|
115
|
+
break
|
|
116
|
+
case '/empty':
|
|
117
|
+
ctx.status = 204
|
|
118
|
+
break
|
|
119
|
+
}
|
|
120
|
+
})
|
|
121
|
+
server = koa.listen(0)
|
|
122
|
+
await new Promise(resolve => server.once('listening', resolve))
|
|
123
|
+
port = (server.address() as AddressInfo).port
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
afterAll(() => {
|
|
127
|
+
server.close()
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
test('compresses a large JSON body with the negotiated encoding', async () => {
|
|
131
|
+
const gzip = await get(port, '/large', { 'Accept-Encoding': 'gzip, deflate' })
|
|
132
|
+
expect(gzip.headers['content-encoding']).toBe('gzip')
|
|
133
|
+
expect(gzip.headers['content-length']).toBeUndefined()
|
|
134
|
+
expect(gzip.headers.vary).toBe('Accept-Encoding')
|
|
135
|
+
expect(gzip.headers['content-type']).toBe('application/json; charset=utf-8')
|
|
136
|
+
expect(JSON.parse(gunzipSync(gzip.body).toString())).toEqual(large)
|
|
137
|
+
|
|
138
|
+
const deflate = await get(port, '/large', { 'Accept-Encoding': 'deflate' })
|
|
139
|
+
expect(JSON.parse(inflateSync(deflate.body).toString())).toEqual(large)
|
|
140
|
+
|
|
141
|
+
const zstd = await get(port, '/large', { 'Accept-Encoding': 'zstd, gzip' })
|
|
142
|
+
expect(zstd.headers['content-encoding']).toBe('zstd')
|
|
143
|
+
expect(JSON.parse(zstdDecompressSync(zstd.body).toString())).toEqual(large)
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
test('leaves the body alone without an accepted encoding', async () => {
|
|
147
|
+
const response = await get(port, '/large', {})
|
|
148
|
+
expect(response.headers['content-encoding']).toBeUndefined()
|
|
149
|
+
expect(response.headers.vary).toBe('Accept-Encoding')
|
|
150
|
+
expect(JSON.parse(response.body.toString())).toEqual(large)
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
test('a forced stream of a non-compressible type is compressed', async () => {
|
|
154
|
+
const response = await get(port, '/ndjson', { 'Accept-Encoding': 'gzip' })
|
|
155
|
+
expect(response.headers['content-encoding']).toBe('gzip')
|
|
156
|
+
expect(response.headers['content-type']).toBe('application/x-ndjson')
|
|
157
|
+
expect(gunzipSync(response.body).toString()).toBe(ndjson)
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
test('skips small, binary, opted-out, no-transform, already encoded, empty and HEAD responses', async () => {
|
|
161
|
+
for (const path of ['/small', '/png', '/disabled', '/no-transform']) {
|
|
162
|
+
const response = await get(port, path, { 'Accept-Encoding': 'gzip' })
|
|
163
|
+
expect([path, response.headers['content-encoding']]).toEqual([path, undefined])
|
|
164
|
+
}
|
|
165
|
+
const encoded = await get(port, '/encoded', { 'Accept-Encoding': 'zstd, deflate' })
|
|
166
|
+
expect(encoded.headers['content-encoding']).toBe('gzip')
|
|
167
|
+
expect(gunzipSync(encoded.body).toString()).toBe('y'.repeat(2000))
|
|
168
|
+
expect((await get(port, '/empty', { 'Accept-Encoding': 'gzip' })).headers['content-encoding']).toBeUndefined()
|
|
169
|
+
const head = await get(port, '/large', { 'Accept-Encoding': 'gzip' }, 'HEAD')
|
|
170
|
+
expect(head.headers['content-encoding']).toBeUndefined()
|
|
171
|
+
})
|
|
172
|
+
})
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import Koa from 'koa'
|
|
3
|
+
import { IncomingHttpHeaders, request, Server } from 'node:http'
|
|
4
|
+
import { createCorsMiddleware } from '../../../src/application/cors.js'
|
|
5
|
+
|
|
6
|
+
type Response = { status: number; headers: IncomingHttpHeaders; body: string }
|
|
7
|
+
|
|
8
|
+
// node:http instead of fetch: the test preload installs a browser fetch that enforces CORS itself.
|
|
9
|
+
const send = (port: number, path: string, method: string, headers: Record<string, string> = {}): Promise<Response> =>
|
|
10
|
+
new Promise((resolve, reject) => {
|
|
11
|
+
const req = request({ host: '127.0.0.1', port, path, method, headers }, res => {
|
|
12
|
+
let body = ''
|
|
13
|
+
res.setEncoding('utf8')
|
|
14
|
+
res.on('data', chunk => body += chunk)
|
|
15
|
+
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }))
|
|
16
|
+
})
|
|
17
|
+
req.on('error', reject)
|
|
18
|
+
req.end()
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
describe('CORS middleware', () => {
|
|
22
|
+
let server: Server
|
|
23
|
+
let port: number
|
|
24
|
+
|
|
25
|
+
beforeAll(async () => {
|
|
26
|
+
const koa = new Koa()
|
|
27
|
+
koa.silent = true
|
|
28
|
+
koa.use(createCorsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))
|
|
29
|
+
koa.use(async ctx => {
|
|
30
|
+
if (ctx.path === '/fail-plain') {
|
|
31
|
+
throw Object.assign(new Error('boom'), { status: 409, expose: true })
|
|
32
|
+
}
|
|
33
|
+
if (ctx.path === '/fail') {
|
|
34
|
+
throw Object.assign(new Error('boom'), { status: 418, expose: true, headers: { 'X-Custom': 'kept', Vary: 'Accept' } })
|
|
35
|
+
}
|
|
36
|
+
ctx.set('X-Contember-Mutation', 'ok')
|
|
37
|
+
ctx.body = { method: ctx.method }
|
|
38
|
+
})
|
|
39
|
+
server = koa.listen(0)
|
|
40
|
+
await new Promise(resolve => server.once('listening', resolve))
|
|
41
|
+
const address = server.address()
|
|
42
|
+
if (address === null || typeof address === 'string') {
|
|
43
|
+
throw new Error('Expected a TCP address')
|
|
44
|
+
}
|
|
45
|
+
port = address.port
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
afterAll(() => {
|
|
49
|
+
server.close()
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('simple request gets allow-origin and expose-headers', async () => {
|
|
53
|
+
const response = await send(port, '/', 'POST', { Origin: 'https://example.com' })
|
|
54
|
+
expect(response.status).toBe(200)
|
|
55
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
56
|
+
expect(response.headers['access-control-expose-headers']).toBe('X-Contember-Mutation')
|
|
57
|
+
expect(response.headers['access-control-allow-credentials']).toBeUndefined()
|
|
58
|
+
expect(response.headers['vary']).toBe('Origin')
|
|
59
|
+
expect(JSON.parse(response.body)).toEqual({ method: 'POST' })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('preflight answers 204 and echoes the requested headers', async () => {
|
|
63
|
+
const response = await send(port, '/', 'OPTIONS', {
|
|
64
|
+
Origin: 'https://example.com',
|
|
65
|
+
'Access-Control-Request-Method': 'POST',
|
|
66
|
+
'Access-Control-Request-Headers': 'authorization,content-type',
|
|
67
|
+
})
|
|
68
|
+
expect(response.status).toBe(204)
|
|
69
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
70
|
+
expect(response.headers['access-control-allow-methods']).toBe('GET,HEAD,PUT,POST,DELETE,PATCH')
|
|
71
|
+
expect(response.headers['access-control-allow-headers']).toBe('authorization,content-type')
|
|
72
|
+
expect(response.headers['access-control-expose-headers']).toBeUndefined()
|
|
73
|
+
expect(response.headers['vary']).toBe('Origin')
|
|
74
|
+
expect(response.body).toBe('')
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('preflight without requested headers sets no allow-headers', async () => {
|
|
78
|
+
const response = await send(port, '/', 'OPTIONS', { 'Access-Control-Request-Method': 'GET' })
|
|
79
|
+
expect(response.status).toBe(204)
|
|
80
|
+
expect(response.headers['access-control-allow-headers']).toBeUndefined()
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
test('OPTIONS without request method is not a preflight', async () => {
|
|
84
|
+
const response = await send(port, '/', 'OPTIONS')
|
|
85
|
+
expect(response.status).toBe(200)
|
|
86
|
+
expect(response.headers['access-control-allow-origin']).toBeUndefined()
|
|
87
|
+
expect(JSON.parse(response.body)).toEqual({ method: 'OPTIONS' })
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
test('CORS headers survive a thrown error', async () => {
|
|
91
|
+
const response = await send(port, '/fail', 'GET', { Origin: 'https://example.com' })
|
|
92
|
+
expect(response.status).toBe(418)
|
|
93
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
94
|
+
expect(response.headers['access-control-expose-headers']).toBe('X-Contember-Mutation')
|
|
95
|
+
expect(response.headers['x-custom']).toBe('kept')
|
|
96
|
+
expect(response.headers['vary']).toBe('Accept, Origin')
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
test('CORS headers survive a thrown error without own headers', async () => {
|
|
100
|
+
const response = await send(port, '/fail-plain', 'GET', { Origin: 'https://example.com' })
|
|
101
|
+
expect(response.status).toBe(409)
|
|
102
|
+
expect(response.headers['access-control-allow-origin']).toBe('*')
|
|
103
|
+
expect(response.headers['access-control-expose-headers']).toBe('X-Contember-Mutation')
|
|
104
|
+
expect(response.headers['vary']).toBe('Origin')
|
|
105
|
+
})
|
|
106
|
+
})
|