@celljs/web 4.2.0 → 4.4.0
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/README.md +48 -4
- package/cell.schema.json +266 -0
- package/cell.yml +12 -17
- package/esm/common/constants.d.ts +3 -3
- package/esm/common/constants.js +3 -3
- package/esm/common/constants.js.map +1 -1
- package/esm/node/body/body-middleware.js +1 -1
- package/esm/node/body/body-middleware.js.map +1 -1
- package/esm/node/body/body-parser.d.ts +5 -0
- package/esm/node/body/body-parser.js +7 -0
- package/esm/node/body/body-parser.js.map +1 -1
- package/esm/node/body/body-protocol.d.ts +1 -1
- package/esm/node/context.d.ts +4 -0
- package/esm/node/context.js +11 -11
- package/esm/node/context.js.map +1 -1
- package/esm/node/cookies/cookies-factory.js +2 -2
- package/esm/node/cookies/cookies-factory.js.map +1 -1
- package/esm/node/cookies/cookies-protocol.d.ts +1 -1
- package/esm/node/cookies/cookies-security-check.d.ts +13 -0
- package/esm/node/cookies/cookies-security-check.js +55 -0
- package/esm/node/cookies/cookies-security-check.js.map +1 -0
- package/esm/node/cookies/cookies.d.ts +1 -1
- package/esm/node/cookies/cookies.js +1 -1
- package/esm/node/cookies/index.d.ts +1 -0
- package/esm/node/cookies/index.js +1 -0
- package/esm/node/cookies/index.js.map +1 -1
- package/esm/node/cors/cors-middleware.d.ts +1 -1
- package/esm/node/cors/cors-middleware.js +1 -1
- package/esm/node/cors/cors-middleware.js.map +1 -1
- package/esm/node/cors/cors-protocol.d.ts +1 -1
- package/esm/node/dispatcher/dispatcher.d.ts +10 -0
- package/esm/node/dispatcher/dispatcher.js +36 -3
- package/esm/node/dispatcher/dispatcher.js.map +1 -1
- package/esm/node/error/error-handler-provider.d.ts +6 -2
- package/esm/node/error/error-handler-provider.js +17 -9
- package/esm/node/error/error-handler-provider.js.map +1 -1
- package/esm/node/error/error-message-resolver.d.ts +11 -0
- package/esm/node/error/error-message-resolver.js +43 -0
- package/esm/node/error/error-message-resolver.js.map +1 -0
- package/esm/node/error/error-protocol.d.ts +12 -2
- package/esm/node/error/error-protocol.js +3 -2
- package/esm/node/error/error-protocol.js.map +1 -1
- package/esm/node/error/error-response-util.d.ts +8 -0
- package/esm/node/error/error-response-util.js +24 -0
- package/esm/node/error/error-response-util.js.map +1 -0
- package/esm/node/error/http-error.d.ts +9 -1
- package/esm/node/error/http-error.js +6 -2
- package/esm/node/error/http-error.js.map +1 -1
- package/esm/node/error/index.d.ts +2 -0
- package/esm/node/error/index.js +2 -0
- package/esm/node/error/index.js.map +1 -1
- package/esm/node/health/health-executor.js +8 -12
- package/esm/node/health/health-executor.js.map +1 -1
- package/esm/node/health/health-middleware.js +1 -1
- package/esm/node/health/health-middleware.js.map +1 -1
- package/esm/node/matcher/request-matcher.js +2 -2
- package/esm/node/matcher/request-matcher.js.map +1 -1
- package/esm/node/session/session-manager.js +2 -2
- package/esm/node/session/session-manager.js.map +1 -1
- package/esm/node/session/session-middleware.js +1 -1
- package/esm/node/session/session-middleware.js.map +1 -1
- package/esm/node/session/session-store.js +1 -1
- package/esm/node/session/session-store.js.map +1 -1
- package/esm/node/session/session-strategy.js +1 -1
- package/esm/node/session/session-strategy.js.map +1 -1
- package/esm/node/session/session.d.ts +14 -2
- package/esm/node/session/session.js +33 -4
- package/esm/node/session/session.js.map +1 -1
- package/esm/node/trace/trace-id-resolver.js +2 -2
- package/esm/node/trace/trace-id-resolver.js.map +1 -1
- package/esm/node/trace/trace-protocol.d.ts +2 -2
- package/esm/node/trace/trace-protocol.js +2 -2
- package/esm/node/trace/trace-protocol.js.map +1 -1
- package/lib/common/constants.d.ts +3 -3
- package/lib/common/constants.d.ts.map +1 -1
- package/lib/common/constants.js +3 -3
- package/lib/common/constants.js.map +1 -1
- package/lib/node/body/body-middleware.js +1 -1
- package/lib/node/body/body-middleware.js.map +1 -1
- package/lib/node/body/body-parser.d.ts +5 -0
- package/lib/node/body/body-parser.d.ts.map +1 -1
- package/lib/node/body/body-parser.js +7 -0
- package/lib/node/body/body-parser.js.map +1 -1
- package/lib/node/body/body-protocol.d.ts +1 -1
- package/lib/node/body/body-protocol.d.ts.map +1 -1
- package/lib/node/context.d.ts +4 -0
- package/lib/node/context.d.ts.map +1 -1
- package/lib/node/context.js +11 -11
- package/lib/node/context.js.map +1 -1
- package/lib/node/context.spec.d.ts +2 -0
- package/lib/node/context.spec.d.ts.map +1 -0
- package/lib/node/context.spec.js +25 -0
- package/lib/node/context.spec.js.map +1 -0
- package/lib/node/cookies/cookies-factory.js +2 -2
- package/lib/node/cookies/cookies-factory.js.map +1 -1
- package/lib/node/cookies/cookies-protocol.d.ts +1 -1
- package/lib/node/cookies/cookies-protocol.d.ts.map +1 -1
- package/lib/node/cookies/cookies-security-check.d.ts +14 -0
- package/lib/node/cookies/cookies-security-check.d.ts.map +1 -0
- package/lib/node/cookies/cookies-security-check.js +58 -0
- package/lib/node/cookies/cookies-security-check.js.map +1 -0
- package/lib/node/cookies/cookies-security-check.spec.d.ts +2 -0
- package/lib/node/cookies/cookies-security-check.spec.d.ts.map +1 -0
- package/lib/node/cookies/cookies-security-check.spec.js +21 -0
- package/lib/node/cookies/cookies-security-check.spec.js.map +1 -0
- package/lib/node/cookies/cookies.d.ts +1 -1
- package/lib/node/cookies/cookies.js +1 -1
- package/lib/node/cookies/index.d.ts +1 -0
- package/lib/node/cookies/index.d.ts.map +1 -1
- package/lib/node/cookies/index.js +1 -0
- package/lib/node/cookies/index.js.map +1 -1
- package/lib/node/cors/cors-middleware.d.ts +1 -1
- package/lib/node/cors/cors-middleware.d.ts.map +1 -1
- package/lib/node/cors/cors-middleware.js +1 -1
- package/lib/node/cors/cors-middleware.js.map +1 -1
- package/lib/node/cors/cors-protocol.d.ts +1 -1
- package/lib/node/cors/cors-protocol.d.ts.map +1 -1
- package/lib/node/dispatcher/dispatcher.d.ts +10 -0
- package/lib/node/dispatcher/dispatcher.d.ts.map +1 -1
- package/lib/node/dispatcher/dispatcher.js +36 -3
- package/lib/node/dispatcher/dispatcher.js.map +1 -1
- package/lib/node/dispatcher/dispatcher.spec.d.ts +2 -0
- package/lib/node/dispatcher/dispatcher.spec.d.ts.map +1 -0
- package/lib/node/dispatcher/dispatcher.spec.js +105 -0
- package/lib/node/dispatcher/dispatcher.spec.js.map +1 -0
- package/lib/node/error/error-handler-provider.d.ts +6 -2
- package/lib/node/error/error-handler-provider.d.ts.map +1 -1
- package/lib/node/error/error-handler-provider.js +16 -8
- package/lib/node/error/error-handler-provider.js.map +1 -1
- package/lib/node/error/error-message-resolver.d.ts +12 -0
- package/lib/node/error/error-message-resolver.d.ts.map +1 -0
- package/lib/node/error/error-message-resolver.js +46 -0
- package/lib/node/error/error-message-resolver.js.map +1 -0
- package/lib/node/error/error-message-resolver.spec.d.ts +2 -0
- package/lib/node/error/error-message-resolver.spec.d.ts.map +1 -0
- package/lib/node/error/error-message-resolver.spec.js +42 -0
- package/lib/node/error/error-message-resolver.spec.js.map +1 -0
- package/lib/node/error/error-protocol.d.ts +12 -2
- package/lib/node/error/error-protocol.d.ts.map +1 -1
- package/lib/node/error/error-protocol.js +4 -3
- package/lib/node/error/error-protocol.js.map +1 -1
- package/lib/node/error/error-response-util.d.ts +9 -0
- package/lib/node/error/error-response-util.d.ts.map +1 -0
- package/lib/node/error/error-response-util.js +27 -0
- package/lib/node/error/error-response-util.js.map +1 -0
- package/lib/node/error/http-error.d.ts +9 -1
- package/lib/node/error/http-error.d.ts.map +1 -1
- package/lib/node/error/http-error.js +6 -2
- package/lib/node/error/http-error.js.map +1 -1
- package/lib/node/error/index.d.ts +2 -0
- package/lib/node/error/index.d.ts.map +1 -1
- package/lib/node/error/index.js +2 -0
- package/lib/node/error/index.js.map +1 -1
- package/lib/node/health/health-executor.d.ts.map +1 -1
- package/lib/node/health/health-executor.js +8 -12
- package/lib/node/health/health-executor.js.map +1 -1
- package/lib/node/health/health-executor.spec.d.ts +2 -0
- package/lib/node/health/health-executor.spec.d.ts.map +1 -0
- package/lib/node/health/health-executor.spec.js +44 -0
- package/lib/node/health/health-executor.spec.js.map +1 -0
- package/lib/node/health/health-middleware.js +1 -1
- package/lib/node/health/health-middleware.js.map +1 -1
- package/lib/node/matcher/request-matcher.js +2 -2
- package/lib/node/matcher/request-matcher.js.map +1 -1
- package/lib/node/session/session-manager.js +2 -2
- package/lib/node/session/session-manager.js.map +1 -1
- package/lib/node/session/session-middleware.js +1 -1
- package/lib/node/session/session-middleware.js.map +1 -1
- package/lib/node/session/session-store.js +1 -1
- package/lib/node/session/session-store.js.map +1 -1
- package/lib/node/session/session-strategy.js +1 -1
- package/lib/node/session/session-strategy.js.map +1 -1
- package/lib/node/session/session.d.ts +14 -2
- package/lib/node/session/session.d.ts.map +1 -1
- package/lib/node/session/session.js +33 -4
- package/lib/node/session/session.js.map +1 -1
- package/lib/node/session/session.spec.js +21 -0
- package/lib/node/session/session.spec.js.map +1 -1
- package/lib/node/trace/trace-id-resolver.js +1 -1
- package/lib/node/trace/trace-id-resolver.js.map +1 -1
- package/lib/node/trace/trace-protocol.d.ts +2 -2
- package/lib/node/trace/trace-protocol.d.ts.map +1 -1
- package/lib/node/trace/trace-protocol.js +2 -2
- package/lib/node/trace/trace-protocol.js.map +1 -1
- package/package.json +5 -4
- package/src/common/constants.ts +3 -3
- package/src/node/body/body-middleware.ts +1 -1
- package/src/node/body/body-parser.ts +8 -0
- package/src/node/body/body-protocol.ts +1 -1
- package/src/node/context.spec.ts +25 -0
- package/src/node/context.ts +9 -9
- package/src/node/cookies/cookies-factory.ts +2 -2
- package/src/node/cookies/cookies-protocol.ts +1 -1
- package/src/node/cookies/cookies-security-check.spec.ts +21 -0
- package/src/node/cookies/cookies-security-check.ts +44 -0
- package/src/node/cookies/cookies.ts +1 -1
- package/src/node/cookies/index.ts +1 -1
- package/src/node/cors/cors-middleware.ts +1 -1
- package/src/node/cors/cors-protocol.ts +1 -1
- package/src/node/dispatcher/dispatcher.spec.ts +110 -0
- package/src/node/dispatcher/dispatcher.ts +37 -4
- package/src/node/error/error-handler-provider.ts +17 -11
- package/src/node/error/error-message-resolver.spec.ts +44 -0
- package/src/node/error/error-message-resolver.ts +31 -0
- package/src/node/error/error-protocol.ts +14 -3
- package/src/node/error/error-response-util.ts +24 -0
- package/src/node/error/http-error.ts +14 -2
- package/src/node/error/index.ts +1 -1
- package/src/node/health/health-executor.spec.ts +40 -0
- package/src/node/health/health-executor.ts +8 -13
- package/src/node/health/health-middleware.ts +1 -1
- package/src/node/matcher/request-matcher.ts +2 -2
- package/src/node/session/session-manager.ts +2 -2
- package/src/node/session/session-middleware.ts +1 -1
- package/src/node/session/session-store.ts +1 -1
- package/src/node/session/session-strategy.ts +1 -1
- package/src/node/session/session.spec.ts +24 -0
- package/src/node/session/session.ts +41 -7
- package/src/node/trace/trace-id-resolver.ts +2 -2
- package/src/node/trace/trace-protocol.ts +2 -2
|
@@ -1,21 +1,25 @@
|
|
|
1
1
|
import { Context } from '../context';
|
|
2
2
|
import { Component, Autowired, Prioritizeable } from '@celljs/core';
|
|
3
|
-
import { ErrorHandler,
|
|
3
|
+
import { ErrorHandler, ErrorMessageResolver, DEFAULT_ERROR_HANDLER_PRIORITY, HTTP_ERROR_HANDLER_PRIORITY, VALIDATION_ERRORS_ERROR_HANDLER_PRIORITY } from './error-protocol';
|
|
4
4
|
import { HttpError } from './http-error';
|
|
5
|
+
import { ErrorResponseUtil } from './error-response-util';
|
|
5
6
|
import { HttpStatus } from '@celljs/http';
|
|
6
7
|
import { ValidationErrors } from '../../common/pipe';
|
|
7
8
|
|
|
8
9
|
export abstract class AbstractErrorHandler implements ErrorHandler {
|
|
9
|
-
readonly priority: number =
|
|
10
|
+
readonly priority: number = DEFAULT_ERROR_HANDLER_PRIORITY;
|
|
11
|
+
|
|
12
|
+
@Autowired(ErrorMessageResolver)
|
|
13
|
+
protected readonly errorMessageResolver: ErrorMessageResolver;
|
|
10
14
|
|
|
11
15
|
canHandle(ctx: Context, err: Error): Promise<boolean> {
|
|
12
16
|
return Promise.resolve(true);
|
|
13
17
|
}
|
|
14
18
|
|
|
19
|
+
/** The dispatcher has logged the error already; the client gets what {@link ErrorMessageResolver} decides. */
|
|
15
20
|
async handle(ctx: Context, err: Error): Promise<void> {
|
|
16
|
-
|
|
17
|
-
ctx
|
|
18
|
-
ctx.response.end(err.message);
|
|
21
|
+
const { status, message } = this.errorMessageResolver.resolve(err);
|
|
22
|
+
ErrorResponseUtil.end(ctx, status, message);
|
|
19
23
|
await this.doHandle(ctx, err);
|
|
20
24
|
}
|
|
21
25
|
|
|
@@ -32,13 +36,16 @@ export class DefaultErrorHandler extends AbstractErrorHandler {
|
|
|
32
36
|
export class HttpErrorHandler implements ErrorHandler {
|
|
33
37
|
readonly priority: number = HTTP_ERROR_HANDLER_PRIORITY;
|
|
34
38
|
|
|
39
|
+
@Autowired(ErrorMessageResolver)
|
|
40
|
+
protected readonly errorMessageResolver: ErrorMessageResolver;
|
|
41
|
+
|
|
35
42
|
canHandle(ctx: Context, err: Error): Promise<boolean> {
|
|
36
43
|
return Promise.resolve(err instanceof HttpError);
|
|
37
44
|
}
|
|
38
45
|
|
|
39
46
|
async handle(ctx: Context, err: HttpError): Promise<void> {
|
|
40
|
-
|
|
41
|
-
|
|
47
|
+
const { status, message } = this.errorMessageResolver.resolve(err);
|
|
48
|
+
ErrorResponseUtil.end(ctx, status, message);
|
|
42
49
|
}
|
|
43
50
|
}
|
|
44
51
|
|
|
@@ -50,9 +57,8 @@ export class ValidationErrorsHandler implements ErrorHandler {
|
|
|
50
57
|
return Promise.resolve(err instanceof ValidationErrors);
|
|
51
58
|
}
|
|
52
59
|
|
|
53
|
-
async handle(ctx: Context, err:
|
|
54
|
-
ctx
|
|
55
|
-
ctx.response.end(err.message);
|
|
60
|
+
async handle(ctx: Context, err: ValidationErrors): Promise<void> {
|
|
61
|
+
ErrorResponseUtil.end(ctx, HttpStatus.BAD_REQUEST, err.message);
|
|
56
62
|
}
|
|
57
63
|
}
|
|
58
64
|
|
|
@@ -73,4 +79,4 @@ export class ErrorHandlerProvider {
|
|
|
73
79
|
return this.prioritized;
|
|
74
80
|
}
|
|
75
81
|
|
|
76
|
-
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { afterEach, describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { ErrorMessageResolverImpl } from './error-message-resolver';
|
|
4
|
+
import { HttpError } from './http-error';
|
|
5
|
+
import { NotFoundError } from './not-found-error';
|
|
6
|
+
|
|
7
|
+
const nodeEnv = process.env.NODE_ENV;
|
|
8
|
+
afterEach(() => {
|
|
9
|
+
process.env.NODE_ENV = nodeEnv;
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
function resolver(exposeMessages?: boolean): ErrorMessageResolverImpl {
|
|
13
|
+
return Object.assign(new ErrorMessageResolverImpl(), { exposeMessages });
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('ErrorMessageResolverImpl', () => {
|
|
17
|
+
it('sends the message of a 4xx HttpError, the status text of anything else in production', () => {
|
|
18
|
+
process.env.NODE_ENV = 'production';
|
|
19
|
+
expect(resolver().resolve(new NotFoundError('no user 7'))).to.deep.equal({ status: 404, message: 'no user 7' });
|
|
20
|
+
expect(resolver().resolve(new Error('ECONNREFUSED 10.0.0.5:5432'))).to.deep.equal({ status: 500, message: 'Internal Server Error' });
|
|
21
|
+
expect(resolver().resolve(new HttpError(502, 'upstream 10.0.0.5 failed'))).to.deep.equal({ status: 502, message: 'Bad Gateway' });
|
|
22
|
+
expect(resolver().resolve(new HttpError(503, 'Down for maintenance', { expose: true }))).to.deep.equal({ status: 503, message: 'Down for maintenance' });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('sends every message outside production, or when web.errors.exposeMessages says so', () => {
|
|
26
|
+
process.env.NODE_ENV = 'development';
|
|
27
|
+
expect(resolver().resolve(new Error('boom')).message).to.equal('boom');
|
|
28
|
+
expect(resolver(false).resolve(new Error('boom')).message).to.equal('Internal Server Error');
|
|
29
|
+
process.env.NODE_ENV = 'production';
|
|
30
|
+
expect(resolver(true).resolve(new Error('boom')).message).to.equal('boom');
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
describe('HttpError', () => {
|
|
35
|
+
it('defaults the message to the status text and keeps the cause', () => {
|
|
36
|
+
const cause = new Error('EACCES /srv/app/secret');
|
|
37
|
+
const error = new HttpError(500, undefined, { cause });
|
|
38
|
+
expect(error.message).to.equal('Internal Server Error');
|
|
39
|
+
expect((error as { cause?: unknown }).cause).to.equal(cause);
|
|
40
|
+
expect(error.expose).to.equal(false);
|
|
41
|
+
expect(new NotFoundError().message).to.equal('Not Found');
|
|
42
|
+
expect(new HttpError(404).expose).to.equal(true);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { STATUS_CODES } from 'node:http';
|
|
2
|
+
import { Component, Value } from '@celljs/core';
|
|
3
|
+
import { HttpError } from './http-error';
|
|
4
|
+
import { ErrorMessageResolver, ErrorResponse } from './error-protocol';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A 4xx `HttpError` (or one with `expose: true`) answers with its message. Any other error answers
|
|
8
|
+
* with the status text (`Internal Server Error`) in production, so that messages of internal errors
|
|
9
|
+
* (SQL, file paths, hosts) stay in the log; `web.errors.exposeMessages` decides otherwise.
|
|
10
|
+
*/
|
|
11
|
+
@Component(ErrorMessageResolver)
|
|
12
|
+
export class ErrorMessageResolverImpl implements ErrorMessageResolver {
|
|
13
|
+
|
|
14
|
+
@Value('web.errors.exposeMessages')
|
|
15
|
+
protected readonly exposeMessages?: boolean;
|
|
16
|
+
|
|
17
|
+
resolve(error: unknown): ErrorResponse {
|
|
18
|
+
const status = error instanceof HttpError ? error.statusCode : 500;
|
|
19
|
+
const statusText = STATUS_CODES[status] ?? `HTTP ${status}`;
|
|
20
|
+
const exposed = (error instanceof HttpError && error.expose) || this.exposesMessages();
|
|
21
|
+
const message = error instanceof Error ? error.message : undefined;
|
|
22
|
+
return { status, message: exposed && message ? message : statusText };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
protected exposesMessages(): boolean {
|
|
26
|
+
if (typeof this.exposeMessages === 'boolean') {
|
|
27
|
+
return this.exposeMessages;
|
|
28
|
+
}
|
|
29
|
+
return process.env.NODE_ENV !== 'production';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -1,16 +1,27 @@
|
|
|
1
1
|
import { Context } from '../context';
|
|
2
2
|
|
|
3
3
|
export const ErrorHandler = Symbol('ErrorHandler');
|
|
4
|
+
export const ErrorMessageResolver = Symbol('ErrorMessageResolver');
|
|
4
5
|
|
|
5
|
-
export const
|
|
6
|
-
export const HTTP_ERROR_HANDLER_PRIORITY =
|
|
6
|
+
export const DEFAULT_ERROR_HANDLER_PRIORITY = 1;
|
|
7
|
+
export const HTTP_ERROR_HANDLER_PRIORITY = DEFAULT_ERROR_HANDLER_PRIORITY + 100;
|
|
7
8
|
export const VALIDATION_ERRORS_ERROR_HANDLER_PRIORITY = HTTP_ERROR_HANDLER_PRIORITY + 100;
|
|
8
9
|
|
|
9
10
|
export interface ErrorHandler {
|
|
10
11
|
/**
|
|
11
|
-
* The priority value must be greater than the default Error Handler's priority:
|
|
12
|
+
* The priority value must be greater than the default Error Handler's priority: DEFAULT_ERROR_HANDLER_PRIORITY, otherwise it will never be executed.
|
|
12
13
|
*/
|
|
13
14
|
readonly priority: number;
|
|
14
15
|
canHandle(ctx: Context, err: Error): Promise<boolean>;
|
|
15
16
|
handle(ctx: Context, err: Error): Promise<void>;
|
|
16
17
|
}
|
|
18
|
+
/** What the client is told about an error. */
|
|
19
|
+
export interface ErrorResponse {
|
|
20
|
+
status: number;
|
|
21
|
+
message: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Decides the status and the message an error answers with; error handlers and the mvc JSON view use it. */
|
|
25
|
+
export interface ErrorMessageResolver {
|
|
26
|
+
resolve(error: unknown): ErrorResponse;
|
|
27
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Context } from '../context';
|
|
2
|
+
|
|
3
|
+
export namespace ErrorResponseUtil {
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Ends the response of a failed request with `status` and `body` (and `contentType` when given).
|
|
7
|
+
* A response the handler had already started is only ended; an ended one is left alone.
|
|
8
|
+
*/
|
|
9
|
+
export function end(ctx: Context, status: number, body: string, contentType?: string): void {
|
|
10
|
+
const { response } = ctx;
|
|
11
|
+
if (response.writableEnded) {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
if (response.headersSent) {
|
|
15
|
+
response.end();
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
response.statusCode = status;
|
|
19
|
+
if (contentType) {
|
|
20
|
+
response.setHeader('Content-Type', contentType);
|
|
21
|
+
}
|
|
22
|
+
response.end(body);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -1,9 +1,21 @@
|
|
|
1
|
+
import { STATUS_CODES } from 'node:http';
|
|
1
2
|
import { CustomError } from '@celljs/core';
|
|
2
3
|
|
|
4
|
+
export interface HttpErrorOptions {
|
|
5
|
+
/** The error behind this one; logged with it, never sent. */
|
|
6
|
+
cause?: unknown;
|
|
7
|
+
/** Whether the client gets `message`; default: for 4xx, not for 5xx (see `web.errors.exposeMessages`). */
|
|
8
|
+
expose?: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** An error that answers with `statusCode`. Without a message, the message is the status text (`Not Found`). */
|
|
3
12
|
export class HttpError extends CustomError {
|
|
4
13
|
|
|
5
|
-
|
|
6
|
-
|
|
14
|
+
readonly expose: boolean;
|
|
15
|
+
|
|
16
|
+
constructor(public statusCode: number, message?: string, options: HttpErrorOptions = {}) {
|
|
17
|
+
super(message ?? STATUS_CODES[statusCode] ?? `HTTP ${statusCode}`, options.cause === undefined ? undefined : { cause: options.cause });
|
|
18
|
+
this.expose = options.expose ?? statusCode < 500;
|
|
7
19
|
}
|
|
8
20
|
|
|
9
21
|
}
|
package/src/node/error/index.ts
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { HealthExecutorImpl } from './health-executor';
|
|
4
|
+
import { HealthStatusAggregatorImpl } from './health-status-aggregator';
|
|
5
|
+
import { Health, HealthIndicator, HealthStatus } from './health-protocol';
|
|
6
|
+
|
|
7
|
+
class CountingHealthIndicator implements HealthIndicator {
|
|
8
|
+
calls = 0;
|
|
9
|
+
constructor(protected readonly status: HealthStatus, protected readonly wait = 0) { }
|
|
10
|
+
async health(): Promise<Health> {
|
|
11
|
+
this.calls++;
|
|
12
|
+
await new Promise(resolve => setTimeout(resolve, this.wait));
|
|
13
|
+
return { status: this.status };
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
class DbHealthIndicator extends CountingHealthIndicator { }
|
|
17
|
+
class DiskHealthIndicator extends CountingHealthIndicator { }
|
|
18
|
+
|
|
19
|
+
function executor(...indicators: HealthIndicator[]): HealthExecutorImpl {
|
|
20
|
+
return Object.assign(new HealthExecutorImpl(), { healthIndicators: indicators, healthStatusAggregator: new HealthStatusAggregatorImpl() });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe('HealthExecutorImpl', () => {
|
|
24
|
+
it('checks each indicator once and keeps their order, whichever answers first', async () => {
|
|
25
|
+
const db = new DbHealthIndicator(HealthStatus.UP, 10);
|
|
26
|
+
const disk = new DiskHealthIndicator(HealthStatus.DOWN);
|
|
27
|
+
const result: any = await executor(db, disk).execute();
|
|
28
|
+
expect([db.calls, disk.calls]).to.deep.equal([1, 1]);
|
|
29
|
+
expect(Object.keys(result.components)).to.deep.equal(['db', 'disk']);
|
|
30
|
+
expect(result.components.disk.status).to.equal(HealthStatus.DOWN);
|
|
31
|
+
expect(result.status).to.equal(HealthStatus.DOWN);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('checks only the indicator asked for by name', async () => {
|
|
35
|
+
const db = new DbHealthIndicator(HealthStatus.UP);
|
|
36
|
+
const disk = new DiskHealthIndicator(HealthStatus.UP);
|
|
37
|
+
expect((await executor(db, disk).execute('disk')).status).to.equal(HealthStatus.UP);
|
|
38
|
+
expect([db.calls, disk.calls]).to.deep.equal([0, 1]);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
@@ -26,20 +26,15 @@ export class HealthExecutorImpl implements HealthExecutor {
|
|
|
26
26
|
}
|
|
27
27
|
throw new HealthNotFoundError(indicatorName, `Health indicator ${indicatorName} not found`);
|
|
28
28
|
}
|
|
29
|
+
// Each indicator is checked once, all at the same time; the components keep the order of the indicators.
|
|
30
|
+
const named = this.healthIndicators
|
|
31
|
+
.map(indicator => ({ indicator, name: this.getHealthIndicatorName(indicator) }))
|
|
32
|
+
.filter((entry): entry is { indicator: HealthIndicator, name: string } => !!entry.name);
|
|
33
|
+
const healths = await Promise.all(named.map(({ indicator }) => indicator.health()));
|
|
29
34
|
const components: { [key: string]: HealthComponent } = {};
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
components[name.toLowerCase().replace('healthindicator', '')] = await healthIndicator.health();
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
await Promise.all(this.healthIndicators.map(async h => {
|
|
38
|
-
const name = this.getHealthIndicatorName(h);
|
|
39
|
-
if (name) {
|
|
40
|
-
components[name.toLowerCase().replace('healthindicator', '')] = await h.health();
|
|
41
|
-
}
|
|
42
|
-
}));
|
|
35
|
+
named.forEach(({ name }, index) => {
|
|
36
|
+
components[name.replace('healthindicator', '')] = healths[index];
|
|
37
|
+
});
|
|
43
38
|
|
|
44
39
|
return <CompositeHealth>{
|
|
45
40
|
status: this.healthStatusAggregator.aggregate(Object.values(components).map(c => c.status)),
|
|
@@ -19,7 +19,7 @@ export class HealthMiddleware implements Middleware {
|
|
|
19
19
|
@Autowired(PathResolver)
|
|
20
20
|
protected readonly pathResolver: PathResolver;
|
|
21
21
|
|
|
22
|
-
@Value('
|
|
22
|
+
@Value('web.health')
|
|
23
23
|
protected readonly healthOptions: HealthOptions;
|
|
24
24
|
|
|
25
25
|
async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
|
|
@@ -7,12 +7,12 @@ import { PathPattern } from './path-pattern';
|
|
|
7
7
|
export class RequestMatcherImpl implements RequestMatcher {
|
|
8
8
|
protected caches: Map<string, PathPattern> = new Map<string, PathPattern>();
|
|
9
9
|
|
|
10
|
-
@Value('
|
|
10
|
+
@Value('web.route.cacheSize')
|
|
11
11
|
protected readonly cacheSize: number;
|
|
12
12
|
|
|
13
13
|
async match(pattern: any, method?: string): Promise<any> {
|
|
14
14
|
const request = Context.getRequest();
|
|
15
|
-
if (method && request.method && method.toUpperCase() !== request.method.toUpperCase()) {
|
|
15
|
+
if (method && request.method && method !== request.method && method.toUpperCase() !== request.method.toUpperCase()) {
|
|
16
16
|
return false;
|
|
17
17
|
}
|
|
18
18
|
pattern = pattern || '/';
|
|
@@ -5,10 +5,10 @@ import { Context } from '../context';
|
|
|
5
5
|
@Component(SessionManager)
|
|
6
6
|
export class SessionManagerImpl implements SessionManager {
|
|
7
7
|
|
|
8
|
-
@Value('
|
|
8
|
+
@Value('web.session.sessionIdKey')
|
|
9
9
|
protected readonly sessionIdKey: string;
|
|
10
10
|
|
|
11
|
-
@Value('
|
|
11
|
+
@Value('web.session')
|
|
12
12
|
protected readonly sessionOptions: any;
|
|
13
13
|
|
|
14
14
|
@Autowired(SessionStrategy)
|
|
@@ -9,7 +9,7 @@ export class SessionMiddleware implements Middleware {
|
|
|
9
9
|
@Autowired(SessionManager)
|
|
10
10
|
protected readonly sessionManager: SessionManager;
|
|
11
11
|
|
|
12
|
-
@Value('
|
|
12
|
+
@Value('web.session')
|
|
13
13
|
protected readonly sessionOptions: any;
|
|
14
14
|
|
|
15
15
|
async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
|
|
@@ -5,7 +5,7 @@ import { Value, Component } from '@celljs/core';
|
|
|
5
5
|
@Component(SessionStrategy)
|
|
6
6
|
export class SessionStrategyImpl implements SessionStrategy {
|
|
7
7
|
|
|
8
|
-
@Value('
|
|
8
|
+
@Value('web.session')
|
|
9
9
|
protected readonly sessionOptions: any;
|
|
10
10
|
|
|
11
11
|
async valid(session: Session): Promise<boolean> {
|
|
@@ -31,6 +31,30 @@ describe('SessionImpl', () => {
|
|
|
31
31
|
expect(session.changed).to.equal(true);
|
|
32
32
|
});
|
|
33
33
|
|
|
34
|
+
it('a new session changes like its JSON does: undefined values do not count, a new expiry does', () => {
|
|
35
|
+
const session = new SessionImpl(options) as SessionImpl & Record<string, unknown>;
|
|
36
|
+
session.nothing = undefined;
|
|
37
|
+
session.callback = () => undefined;
|
|
38
|
+
expect(session.changed).to.equal(false);
|
|
39
|
+
session.expire += 1000;
|
|
40
|
+
expect(session.changed).to.equal(true);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('a restored session keeps its id and notices changes inside its values', () => {
|
|
44
|
+
const restored = new SessionImpl(options, { id: 'kept', expire: 1, maxAge: 1000, user: { name: 'tom' } }) as SessionImpl & Record<string, any>;
|
|
45
|
+
expect(restored.id).to.equal('kept');
|
|
46
|
+
expect(restored.isNew).to.equal(false);
|
|
47
|
+
expect(restored.changed).to.equal(false);
|
|
48
|
+
restored.user.name = 'jerry';
|
|
49
|
+
expect(restored.changed).to.equal(true);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('new sessions get distinct random ids', () => {
|
|
53
|
+
const ids = new Set(Array.from({ length: 100 }, () => new SessionImpl(options).id));
|
|
54
|
+
expect(ids.size).to.equal(100);
|
|
55
|
+
expect([...ids][0]).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
|
56
|
+
});
|
|
57
|
+
|
|
34
58
|
it('serializes its values without isNew and private fields', () => {
|
|
35
59
|
const session = new SessionImpl(options) as SessionImpl & Record<string, unknown>;
|
|
36
60
|
session.user = 'tom';
|
|
@@ -1,24 +1,39 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { Session } from './session-protocol';
|
|
3
3
|
|
|
4
|
+
/** What JSON.stringify leaves out: a key holding it does not make a session changed. */
|
|
5
|
+
function isSerialized(value: unknown): boolean {
|
|
6
|
+
return value !== undefined && typeof value !== 'function' && typeof value !== 'symbol';
|
|
7
|
+
}
|
|
8
|
+
|
|
4
9
|
export class SessionImpl implements Session {
|
|
5
|
-
|
|
10
|
+
/** From node:crypto: a session id must be unguessable on every runtime (Node.js 18 has no global `crypto`). */
|
|
11
|
+
readonly id: string;
|
|
6
12
|
isNew = true;
|
|
7
13
|
expire: number;
|
|
8
14
|
maxAge: number;
|
|
9
|
-
/** The serialized values
|
|
10
|
-
protected _snapshot
|
|
15
|
+
/** The serialized values of a restored session, to tell whether it changed. */
|
|
16
|
+
protected _snapshot?: string;
|
|
17
|
+
/** `expire` and `maxAge` of a new session as created. */
|
|
18
|
+
protected _created?: { id: string, expire: number, maxAge: number };
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Every request without a session gets a new one, so a new session is cheap: no serialization, and
|
|
22
|
+
* `changed` compares its few values instead of JSON. A restored session is serialized once to compare.
|
|
23
|
+
*/
|
|
11
24
|
constructor(sessionOptions: any, obj?: any) {
|
|
12
25
|
if (obj) {
|
|
13
26
|
this.isNew = false;
|
|
14
27
|
for (const key of Object.keys(obj)) {
|
|
15
28
|
(this as any)[key] = obj[key];
|
|
16
29
|
}
|
|
30
|
+
this._snapshot = this.serialize();
|
|
17
31
|
} else {
|
|
32
|
+
this.id = randomUUID();
|
|
18
33
|
this.expire = sessionOptions.maxAge + Date.now();
|
|
19
34
|
this.maxAge = sessionOptions.maxAge;
|
|
35
|
+
this._created = { id: this.id, expire: this.expire, maxAge: this.maxAge };
|
|
20
36
|
}
|
|
21
|
-
this._snapshot = this.serialize();
|
|
22
37
|
}
|
|
23
38
|
|
|
24
39
|
protected serialize(): string {
|
|
@@ -35,8 +50,27 @@ export class SessionImpl implements Session {
|
|
|
35
50
|
return obj;
|
|
36
51
|
}
|
|
37
52
|
|
|
38
|
-
|
|
39
|
-
|
|
53
|
+
/** Whether the serialized session differs from the one created or restored. */
|
|
54
|
+
get changed(): boolean {
|
|
55
|
+
const created = this._created;
|
|
56
|
+
if (!created) {
|
|
57
|
+
return this._snapshot !== this.serialize();
|
|
58
|
+
}
|
|
59
|
+
// A new session holds only id, expire and maxAge: anything else that would be serialized is a change.
|
|
60
|
+
for (const key of Object.keys(this)) {
|
|
61
|
+
if (key === 'isNew' || key[0] === '_') {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const value = (this as any)[key];
|
|
65
|
+
if (key === 'id' || key === 'expire' || key === 'maxAge') {
|
|
66
|
+
if (value !== created[key]) {
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
} else if (isSerialized(value)) {
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
40
74
|
}
|
|
41
75
|
|
|
42
76
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Component, Value,
|
|
1
|
+
import { Component, Value, generateUUID } from '@celljs/core';
|
|
2
2
|
import { TraceIdResolver, TRACE_ID_REQUEST_FIELD } from './trace-protocol';
|
|
3
3
|
import { Context } from '../context';
|
|
4
4
|
|
|
@@ -14,6 +14,6 @@ export class TraceIdResolverImpl implements TraceIdResolver {
|
|
|
14
14
|
return Promise.resolve(traceId);
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
-
return Promise.resolve(
|
|
17
|
+
return Promise.resolve(generateUUID());
|
|
18
18
|
}
|
|
19
19
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Be sure this middleware is always at first position
|
|
2
2
|
export const TRACE_MIDDLEWARE_PRIORITY = 2200;
|
|
3
3
|
|
|
4
|
-
export const TRACE_ID_REQUEST_FIELD = '
|
|
5
|
-
export const TRACE_ID_RESPONSE_FIELD = '
|
|
4
|
+
export const TRACE_ID_REQUEST_FIELD = 'web.trace.requestField';
|
|
5
|
+
export const TRACE_ID_RESPONSE_FIELD = 'web.trace.responseField';
|
|
6
6
|
|
|
7
7
|
export const TraceIdResolver = Symbol('TraceIdResolver');
|
|
8
8
|
|