@naturalcycles/backend-lib 9.77.0 → 9.77.2

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.
@@ -2,6 +2,17 @@ import { _anyToError, _errorLikeToErrorObject } from '@naturalcycles/js-lib/erro
2
2
  import { _objectAssign } from '@naturalcycles/js-lib/types';
3
3
  const { APP_ENV } = process.env;
4
4
  const includeErrorStack = APP_ENV === 'dev';
5
+ // Headers a handler may have set for the response it never got to send;
6
+ // they would wrongly describe the error response (e.g `res.json` keeps a pre-set Content-Type)
7
+ const staleResponseHeaders = [
8
+ 'Content-Type',
9
+ 'Content-Disposition',
10
+ 'Content-Encoding',
11
+ 'Content-Language',
12
+ 'Content-Range',
13
+ 'ETag',
14
+ 'Last-Modified',
15
+ ];
5
16
  // Hacky way to store the errorService, so it's available to `respondWithError` function
6
17
  let errorService;
7
18
  let formatError;
@@ -14,17 +25,6 @@ export function genericErrorMiddleware(cfg = {}) {
14
25
  errorService ||= cfg.errorReportingService;
15
26
  formatError = cfg.formatError;
16
27
  return (err, req, res, _next) => {
17
- // if (res.headersSent) {
18
- // Here we don't even log this error
19
- // It's known that it comes from sentry.requestHandler()
20
- // requestHandler waits for all promises/timeouts to finish in the request, and then emits this error here,
21
- // while `res` is the same as was returned to the User (so, both headers and the data was already returned by that time)
22
- // req.log.warn(`genericErrorHandler, but headersSent=true`, err)
23
- // Here we don't propagate the error further, cause there's only "default express error logger" behind it
24
- // and nothing else. Previously it was logging the same error once again because of this. Avoid.
25
- // return next(err)
26
- // return next()
27
- // }
28
28
  respondWithError(req, res, err);
29
29
  };
30
30
  }
@@ -48,18 +48,45 @@ export function respondWithError(req, res, err) {
48
48
  // todo: add endpoint to the log
49
49
  // todo: add userId from the "Context" (or, just req.userId?) to the log
50
50
  }
51
- if (headersSent)
51
+ if (headersSent) {
52
+ // Too late for an error response. A finished response needs nothing beyond the reporting above.
53
+ // An unfinished one (error mid-stream) is cut off, so the client sees a failed transfer right away
54
+ // instead of waiting for a body that never completes. Same as Express' default error handler.
55
+ if (!res.writableEnded)
56
+ res.destroy();
52
57
  return;
58
+ }
53
59
  const httpError = _errorLikeToErrorObject(originalError);
54
60
  if (!includeErrorStack)
55
61
  delete httpError.stack;
56
- httpError.data.backendResponseStatusCode ||= 500; // default to 500
62
+ // http-errors (express itself, its body parsers) carry the status they should be answered with
63
+ const httpErrorLike = isHttpError(originalError) ? originalError : undefined;
64
+ httpError.data.backendResponseStatusCode ||= httpErrorLike?.statusCode || 500; // default to 500
57
65
  _objectAssign(httpError.data, {
58
66
  errorId,
59
67
  headersSent: headersSent || undefined,
60
68
  });
61
69
  formatError?.(httpError, req); // Mutates the error
70
+ for (const header of staleResponseHeaders)
71
+ res.removeHeader(header);
72
+ res.setHeader('Cache-Control', 'no-store');
73
+ if (httpErrorLike?.headers)
74
+ res.set(httpErrorLike.headers);
62
75
  res.status(httpError.data.backendResponseStatusCode).json({
63
76
  error: httpError,
64
77
  });
65
78
  }
79
+ /**
80
+ * Errors created by the `http-errors` package (express itself, body-parser, raw-body, send)
81
+ * describe the response they expect: `status` and `statusCode` (always equal),
82
+ * `expose` (whether the message is safe to show to the client) and optional response `headers`.
83
+ * The first three together are the marker: other libraries also put `statusCode` or `headers`
84
+ * on their errors (e.g a gateway's response), which say nothing about how we should respond.
85
+ */
86
+ function isHttpError(err) {
87
+ const { status, statusCode, expose } = err;
88
+ if (typeof expose !== 'boolean' || typeof statusCode !== 'number' || status !== statusCode) {
89
+ return false;
90
+ }
91
+ return Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599;
92
+ }
@@ -43,6 +43,6 @@ function buildRequestEndpoint(req, stripPrefix, sanitize) {
43
43
  // the exact bytes are not worth preserving here, `req.url` still has them.
44
44
  const UNSAFE_PATH_CHAR = /[^\w\-./:@%!$*+,;=~]/gu;
45
45
  function sanitizePath(path) {
46
- return path.replace(UNSAFE_PATH_CHAR, '_');
46
+ return path.replaceAll(UNSAFE_PATH_CHAR, '_');
47
47
  }
48
48
  const identity = (path) => path;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/backend-lib",
3
3
  "type": "module",
4
- "version": "9.77.0",
4
+ "version": "9.77.2",
5
5
  "dependencies": {
6
6
  "@naturalcycles/db-lib": "^10",
7
7
  "@naturalcycles/js-lib": "^15",
@@ -1,5 +1,6 @@
1
1
  import type { BackendErrorResponseObject, ErrorObject } from '@naturalcycles/js-lib/error'
2
2
  import { _anyToError, _errorLikeToErrorObject } from '@naturalcycles/js-lib/error'
3
+ import type { StringMap } from '@naturalcycles/js-lib/types'
3
4
  import { _objectAssign } from '@naturalcycles/js-lib/types'
4
5
  import type { BackendErrorRequestHandler, BackendRequest, BackendResponse } from './server.model.js'
5
6
 
@@ -29,6 +30,18 @@ export interface ErrorReportingService {
29
30
  const { APP_ENV } = process.env
30
31
  const includeErrorStack = APP_ENV === 'dev'
31
32
 
33
+ // Headers a handler may have set for the response it never got to send;
34
+ // they would wrongly describe the error response (e.g `res.json` keeps a pre-set Content-Type)
35
+ const staleResponseHeaders = [
36
+ 'Content-Type',
37
+ 'Content-Disposition',
38
+ 'Content-Encoding',
39
+ 'Content-Language',
40
+ 'Content-Range',
41
+ 'ETag',
42
+ 'Last-Modified',
43
+ ]
44
+
32
45
  // Hacky way to store the errorService, so it's available to `respondWithError` function
33
46
  let errorService: ErrorReportingService | undefined
34
47
  let formatError: GenericErrorMiddlewareCfg['formatError']
@@ -45,18 +58,6 @@ export function genericErrorMiddleware(
45
58
  formatError = cfg.formatError
46
59
 
47
60
  return (err, req, res, _next) => {
48
- // if (res.headersSent) {
49
- // Here we don't even log this error
50
- // It's known that it comes from sentry.requestHandler()
51
- // requestHandler waits for all promises/timeouts to finish in the request, and then emits this error here,
52
- // while `res` is the same as was returned to the User (so, both headers and the data was already returned by that time)
53
- // req.log.warn(`genericErrorHandler, but headersSent=true`, err)
54
- // Here we don't propagate the error further, cause there's only "default express error logger" behind it
55
- // and nothing else. Previously it was logging the same error once again because of this. Avoid.
56
- // return next(err)
57
- // return next()
58
- // }
59
-
60
61
  respondWithError(req, res, err)
61
62
  }
62
63
  }
@@ -84,12 +85,20 @@ export function respondWithError(req: BackendRequest, res: BackendResponse, err:
84
85
  // todo: add userId from the "Context" (or, just req.userId?) to the log
85
86
  }
86
87
 
87
- if (headersSent) return
88
+ if (headersSent) {
89
+ // Too late for an error response. A finished response needs nothing beyond the reporting above.
90
+ // An unfinished one (error mid-stream) is cut off, so the client sees a failed transfer right away
91
+ // instead of waiting for a body that never completes. Same as Express' default error handler.
92
+ if (!res.writableEnded) res.destroy()
93
+ return
94
+ }
88
95
 
89
96
  const httpError = _errorLikeToErrorObject(originalError)
90
97
  if (!includeErrorStack) delete httpError.stack
91
98
 
92
- httpError.data.backendResponseStatusCode ||= 500 // default to 500
99
+ // http-errors (express itself, its body parsers) carry the status they should be answered with
100
+ const httpErrorLike = isHttpError(originalError) ? originalError : undefined
101
+ httpError.data.backendResponseStatusCode ||= httpErrorLike?.statusCode || 500 // default to 500
93
102
  _objectAssign(httpError.data, {
94
103
  errorId,
95
104
  headersSent: headersSent || undefined,
@@ -97,7 +106,33 @@ export function respondWithError(req: BackendRequest, res: BackendResponse, err:
97
106
 
98
107
  formatError?.(httpError, req) // Mutates the error
99
108
 
109
+ for (const header of staleResponseHeaders) res.removeHeader(header)
110
+ res.setHeader('Cache-Control', 'no-store')
111
+ if (httpErrorLike?.headers) res.set(httpErrorLike.headers)
112
+
100
113
  res.status(httpError.data.backendResponseStatusCode).json({
101
114
  error: httpError,
102
115
  } satisfies BackendErrorResponseObject)
103
116
  }
117
+
118
+ interface HttpErrorLike extends Error {
119
+ status: number
120
+ statusCode: number
121
+ expose: boolean
122
+ headers?: StringMap<string>
123
+ }
124
+
125
+ /**
126
+ * Errors created by the `http-errors` package (express itself, body-parser, raw-body, send)
127
+ * describe the response they expect: `status` and `statusCode` (always equal),
128
+ * `expose` (whether the message is safe to show to the client) and optional response `headers`.
129
+ * The first three together are the marker: other libraries also put `statusCode` or `headers`
130
+ * on their errors (e.g a gateway's response), which say nothing about how we should respond.
131
+ */
132
+ function isHttpError(err: Error): err is HttpErrorLike {
133
+ const { status, statusCode, expose } = err as Partial<HttpErrorLike>
134
+ if (typeof expose !== 'boolean' || typeof statusCode !== 'number' || status !== statusCode) {
135
+ return false
136
+ }
137
+ return Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599
138
+ }
@@ -55,7 +55,7 @@ function buildRequestEndpoint(
55
55
  const UNSAFE_PATH_CHAR = /[^\w\-./:@%!$*+,;=~]/gu
56
56
 
57
57
  function sanitizePath(path: string): string {
58
- return path.replace(UNSAFE_PATH_CHAR, '_')
58
+ return path.replaceAll(UNSAFE_PATH_CHAR, '_')
59
59
  }
60
60
 
61
61
  const identity = (path: string): string => path