@webpieces/http-server 0.4.761 → 0.4.763

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-server",
3
- "version": "0.4.761",
3
+ "version": "0.4.763",
4
4
  "description": "WebPieces server with filter chain and dependency injection",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -22,10 +22,10 @@
22
22
  "access": "public"
23
23
  },
24
24
  "dependencies": {
25
- "@webpieces/core-context": "0.4.761",
26
- "@webpieces/core-util": "0.4.761",
27
- "@webpieces/gcp-identity": "0.4.761",
28
- "@webpieces/http-routing": "0.4.761",
25
+ "@webpieces/core-context": "0.4.763",
26
+ "@webpieces/core-util": "0.4.763",
27
+ "@webpieces/gcp-identity": "0.4.763",
28
+ "@webpieces/http-routing": "0.4.763",
29
29
  "cors": "2.8.5",
30
30
  "express": "5.1.0",
31
31
  "inversify": "7.10.4"
@@ -0,0 +1,14 @@
1
+ import { HttpResponseDto } from '@webpieces/core-util';
2
+ /** HTTP adapter for the transport-neutral API error taxonomy. */
3
+ export declare class ApiErrorHttpMapper {
4
+ private readonly genericMessages;
5
+ /**
6
+ * Unknown throws and caller-local failures become a concrete implementation failure at this
7
+ * owning API boundary. ApiError itself has no fallback status mapping.
8
+ */
9
+ toResponse(thrown: unknown): HttpResponseDto;
10
+ genericMessage(code: number): string;
11
+ private normalize;
12
+ private operatorDetail;
13
+ private logOperatorDetail;
14
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiErrorHttpMapper = void 0;
4
+ const core_util_1 = require("@webpieces/core-util");
5
+ const log = core_util_1.LogManager.getLogger('ApiErrorHttpMapper');
6
+ /** HTTP adapter for the transport-neutral API error taxonomy. */
7
+ class ApiErrorHttpMapper {
8
+ genericMessages = new Map([
9
+ [266, 'End User Error'],
10
+ [400, 'Bad Request'],
11
+ [401, 'Unauthorized'],
12
+ [403, 'Forbidden'],
13
+ [404, 'Not Found'],
14
+ [408, 'Request Timeout'],
15
+ [429, 'Too Many Requests'],
16
+ [500, 'Internal Server Error'],
17
+ [502, 'Bad Gateway'],
18
+ [503, 'Service Unavailable'],
19
+ [504, 'Gateway Timeout'],
20
+ ]);
21
+ /**
22
+ * Unknown throws and caller-local failures become a concrete implementation failure at this
23
+ * owning API boundary. ApiError itself has no fallback status mapping.
24
+ */
25
+ // webpieces-disable no-any-unknown -- thrown values are unknown until normalized at this boundary
26
+ toResponse(thrown) {
27
+ const error = this.normalize(thrown);
28
+ const status = core_util_1.ApiErrorHttpStatus.code(error);
29
+ this.logOperatorDetail(error);
30
+ const headers = error instanceof core_util_1.ApiDependencyBackoffError
31
+ ? [new core_util_1.HttpHeader('retry-after', String(error.retryAfterSeconds))]
32
+ : [];
33
+ return new core_util_1.HttpResponseDto(new core_util_1.HttpResponseStatus(status, this.genericMessage(status)), headers, core_util_1.ApiErrorCodec.encode(error));
34
+ }
35
+ genericMessage(code) {
36
+ return this.genericMessages.get(code) ?? 'Request Failed';
37
+ }
38
+ // webpieces-disable no-any-unknown -- thrown values are unknown until normalized
39
+ normalize(thrown) {
40
+ if (thrown instanceof core_util_1.ApiError && !(thrown instanceof core_util_1.ApiConnectionError))
41
+ return thrown;
42
+ const error = (0, core_util_1.toError)(thrown);
43
+ return new core_util_1.ApiImplementationError(error.message, error);
44
+ }
45
+ operatorDetail(error) {
46
+ const cause = error.cause instanceof Error ? ` cause=${error.cause.message}` : '';
47
+ return `[name=${error.name} kind=${error.kind} subType=${error.subType ?? 'none'}] ${error.message}${cause}`;
48
+ }
49
+ logOperatorDetail(error) {
50
+ const detail = this.operatorDetail(error);
51
+ if (error instanceof core_util_1.ApiEndUserError)
52
+ log.info(`End User Error: ${detail}`);
53
+ else if (error instanceof core_util_1.ApiBadRequestError)
54
+ log.info(`Bad Request: ${detail}`);
55
+ else if (error instanceof core_util_1.ApiNotFoundError)
56
+ log.info(`Not Found: ${detail}`);
57
+ else if (error instanceof core_util_1.ApiUnauthorizedError)
58
+ log.info(`Unauthorized: ${detail}`);
59
+ else if (error instanceof core_util_1.ApiForbiddenError)
60
+ log.info(`Forbidden: ${detail}`);
61
+ else if (error instanceof core_util_1.ApiRequestTimeoutError)
62
+ log.error(`Request Timeout: ${detail}`);
63
+ else
64
+ log.error(`API failure: ${detail}`);
65
+ }
66
+ }
67
+ exports.ApiErrorHttpMapper = ApiErrorHttpMapper;
68
+ //# sourceMappingURL=ApiErrorHttpMapper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ApiErrorHttpMapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ApiErrorHttpMapper.ts"],"names":[],"mappings":";;;AAAA,oDAkB8B;AAE9B,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;AAEvD,iEAAiE;AACjE,MAAa,kBAAkB;IACV,eAAe,GAAwB,IAAI,GAAG,CAAiB;QAC5E,CAAC,GAAG,EAAE,gBAAgB,CAAC;QACvB,CAAC,GAAG,EAAE,aAAa,CAAC;QACpB,CAAC,GAAG,EAAE,cAAc,CAAC;QACrB,CAAC,GAAG,EAAE,WAAW,CAAC;QAClB,CAAC,GAAG,EAAE,WAAW,CAAC;QAClB,CAAC,GAAG,EAAE,iBAAiB,CAAC;QACxB,CAAC,GAAG,EAAE,mBAAmB,CAAC;QAC1B,CAAC,GAAG,EAAE,uBAAuB,CAAC;QAC9B,CAAC,GAAG,EAAE,aAAa,CAAC;QACpB,CAAC,GAAG,EAAE,qBAAqB,CAAC;QAC5B,CAAC,GAAG,EAAE,iBAAiB,CAAC;KAC3B,CAAC,CAAC;IAEH;;;OAGG;IACH,kGAAkG;IAC3F,UAAU,CAAC,MAAe;QAC7B,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,MAAM,GAAG,8BAAk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,GAAG,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;QAC1C,IAAI,KAAK,YAAY,2BAAe;YAAE,GAAG,CAAC,IAAI,CAAC,mBAAmB,MAAM,EAAE,CAAC,CAAC;aACvE,IAAI,KAAK,YAAY,8BAAkB;YAAE,GAAG,CAAC,IAAI,CAAC,gBAAgB,MAAM,EAAE,CAAC,CAAC;aAC5E,IAAI,KAAK,YAAY,4BAAgB;YAAE,GAAG,CAAC,IAAI,CAAC,cAAc,MAAM,EAAE,CAAC,CAAC;aACxE,IAAI,KAAK,YAAY,gCAAoB;YAAE,GAAG,CAAC,IAAI,CAAC,iBAAiB,MAAM,EAAE,CAAC,CAAC;aAC/E,IAAI,KAAK,YAAY,6BAAiB;YAAE,GAAG,CAAC,IAAI,CAAC,cAAc,MAAM,EAAE,CAAC,CAAC;aACzE,IAAI,KAAK,YAAY,kCAAsB;YAAE,GAAG,CAAC,KAAK,CAAC,oBAAoB,MAAM,EAAE,CAAC,CAAC;;YACrF,GAAG,CAAC,KAAK,CAAC,gBAAgB,MAAM,EAAE,CAAC,CAAC;IAC7C,CAAC;CACJ;AA7DD,gDA6DC","sourcesContent":["import {\n ApiBadRequestError,\n ApiConnectionError,\n ApiDependencyBackoffError,\n ApiEndUserError,\n ApiError,\n ApiErrorCodec,\n ApiForbiddenError,\n ApiImplementationError,\n ApiNotFoundError,\n ApiRequestTimeoutError,\n ApiUnauthorizedError,\n ApiErrorHttpStatus,\n HttpHeader,\n HttpResponseDto,\n HttpResponseStatus,\n LogManager,\n toError,\n} from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('ApiErrorHttpMapper');\n\n/** HTTP adapter for the transport-neutral API error taxonomy. */\nexport class ApiErrorHttpMapper {\n private readonly genericMessages: Map<number, string> = new Map<number, string>([\n [266, 'End User Error'],\n [400, 'Bad Request'],\n [401, 'Unauthorized'],\n [403, 'Forbidden'],\n [404, 'Not Found'],\n [408, 'Request Timeout'],\n [429, 'Too Many Requests'],\n [500, 'Internal Server Error'],\n [502, 'Bad Gateway'],\n [503, 'Service Unavailable'],\n [504, 'Gateway Timeout'],\n ]);\n\n /**\n * Unknown throws and caller-local failures become a concrete implementation failure at this\n * owning API boundary. ApiError itself has no fallback status mapping.\n */\n // webpieces-disable no-any-unknown -- thrown values are unknown until normalized at this boundary\n public toResponse(thrown: unknown): HttpResponseDto {\n const error = this.normalize(thrown);\n const status = ApiErrorHttpStatus.code(error);\n this.logOperatorDetail(error);\n const headers =\n error instanceof ApiDependencyBackoffError\n ? [new HttpHeader('retry-after', String(error.retryAfterSeconds))]\n : [];\n return new HttpResponseDto(\n new HttpResponseStatus(status, this.genericMessage(status)),\n headers,\n ApiErrorCodec.encode(error),\n );\n }\n\n public genericMessage(code: number): string {\n return this.genericMessages.get(code) ?? 'Request Failed';\n }\n\n // webpieces-disable no-any-unknown -- thrown values are unknown until normalized\n private normalize(thrown: unknown): ApiError {\n if (thrown instanceof ApiError && !(thrown instanceof ApiConnectionError)) return thrown;\n const error = toError(thrown);\n return new ApiImplementationError(error.message, error);\n }\n\n private operatorDetail(error: ApiError): string {\n const cause = error.cause instanceof Error ? ` cause=${error.cause.message}` : '';\n return `[name=${error.name} kind=${error.kind} subType=${error.subType ?? 'none'}] ${error.message}${cause}`;\n }\n\n private logOperatorDetail(error: ApiError): void {\n const detail = this.operatorDetail(error);\n if (error instanceof ApiEndUserError) log.info(`End User Error: ${detail}`);\n else if (error instanceof ApiBadRequestError) log.info(`Bad Request: ${detail}`);\n else if (error instanceof ApiNotFoundError) log.info(`Not Found: ${detail}`);\n else if (error instanceof ApiUnauthorizedError) log.info(`Unauthorized: ${detail}`);\n else if (error instanceof ApiForbiddenError) log.info(`Forbidden: ${detail}`);\n else if (error instanceof ApiRequestTimeoutError) log.error(`Request Timeout: ${detail}`);\n else log.error(`API failure: ${detail}`);\n }\n}\n"]}
@@ -49,8 +49,8 @@ export declare class ExpressWrapper {
49
49
  */
50
50
  private maxBodyBytes;
51
51
  /**
52
- * Decides what an outside caller is allowed to see of a thrown {@link HttpError}. Stateless —
53
- * one instance per wrapper is fine, and the class doc there is where the "only UserError's
52
+ * Decides what an outside caller is allowed to see of a thrown {@link API error}. Stateless —
53
+ * one instance per wrapper is fine, and the class doc there is where the "only ApiEndUserError's
54
54
  * message goes on the wire" rule is stated.
55
55
  */
56
56
  private readonly errorWireMapper;
@@ -152,12 +152,12 @@ export declare class ExpressWrapper {
152
152
  *
153
153
  * Two sources, in this order:
154
154
  * 1. the app's {@link ErrorTranslators}, if it claims the error — it owns the ENTIRE response;
155
- * 2. else {@link HttpErrorWireMapper.toResponse}, the webpieces default, which maps every
156
- * `HttpError` subclass to its status and a CALLER-SAFE body (only `UserError`'s message
155
+ * 2. else {@link ApiErrorHttpMapper.toResponse}, the webpieces default, which maps every
156
+ * `ApiError` subclass to its status and a CALLER-SAFE body (only `ApiEndUserError`'s message
157
157
  * is written for a human, so only it goes out verbatim; everything else sends the generic
158
158
  * reason phrase and logs the real one) and turns anything else into a generic 500.
159
159
  *
160
- * Nothing status-specific is decided here any more — read `HttpErrorWireMapper` for the full rule
160
+ * Nothing status-specific is decided here any more — read `ApiErrorHttpMapper` for the full rule
161
161
  * and the list of statuses, which must stay in step with `ClientErrorTranslator`'s built-in
162
162
  * mapping.
163
163
  */
@@ -180,7 +180,7 @@ export declare class ExpressWrapper {
180
180
  * Put the transaction id on EVERY response — success and error, webpieces' default body and an
181
181
  * app's own. It is INFRASTRUCTURE, not app policy: an app that overrides what an error looks like
182
182
  * must not thereby lose the header its support desk quotes back. That is why this lives here and
183
- * not in {@link HttpErrorWireMapper.toResponse} or in an app's translators.
183
+ * not in {@link ApiErrorHttpMapper.toResponse} or in an app's translators.
184
184
  *
185
185
  * Silently absent when there is no id to send, which is exactly the accepted known issue recorded
186
186
  * at step 0 of {@link executeImpl}: a malformed or oversize body fails before `fillFromRequest`
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ExpressWrapper = exports.MAX_BODY_BYTES = void 0;
4
4
  const core_util_1 = require("@webpieces/core-util");
5
5
  const core_context_1 = require("@webpieces/core-context");
6
- const HttpErrorWireMapper_1 = require("./HttpErrorWireMapper");
6
+ const ApiErrorHttpMapper_1 = require("./ApiErrorHttpMapper");
7
7
  /**
8
8
  * The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body
9
9
  * crosses it — the bytes already read are dropped, nothing further is buffered.
@@ -51,11 +51,11 @@ class ExpressWrapper {
51
51
  rawBody;
52
52
  maxBodyBytes;
53
53
  /**
54
- * Decides what an outside caller is allowed to see of a thrown {@link HttpError}. Stateless —
55
- * one instance per wrapper is fine, and the class doc there is where the "only UserError's
54
+ * Decides what an outside caller is allowed to see of a thrown {@link API error}. Stateless —
55
+ * one instance per wrapper is fine, and the class doc there is where the "only ApiEndUserError's
56
56
  * message goes on the wire" rule is stated.
57
57
  */
58
- errorWireMapper = new HttpErrorWireMapper_1.HttpErrorWireMapper();
58
+ errorWireMapper = new ApiErrorHttpMapper_1.ApiErrorHttpMapper();
59
59
  constructor(
60
60
  // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
61
61
  clientMethod, path,
@@ -194,14 +194,14 @@ class ExpressWrapper {
194
194
  * past auth. Everywhere else, fail now.
195
195
  */
196
196
  parseJson(bodyText) {
197
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- translate parse failure to a 400 HttpError
197
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- translate parse failure to an ApiBadRequestError
198
198
  try {
199
199
  return new ParsedBody(bodyText ? JSON.parse(bodyText) : {}, undefined);
200
200
  }
201
201
  catch (err) {
202
202
  const error = (0, core_util_1.toError)(err);
203
203
  if (!this.rawBody) {
204
- throw new core_util_1.BadRequestError('Request body is not valid JSON', undefined, undefined, error);
204
+ throw new core_util_1.ApiBadRequestError('Request body is not valid JSON', undefined, undefined, error);
205
205
  }
206
206
  return new ParsedBody({}, undefined, error);
207
207
  }
@@ -286,7 +286,7 @@ class ExpressWrapper {
286
286
  if (size > this.maxBodyBytes) {
287
287
  chunks = [];
288
288
  req.destroy();
289
- reject(new core_util_1.BadRequestError(`Request body exceeds the ${this.maxBodyBytes} byte limit`));
289
+ reject(new core_util_1.ApiBadRequestError(`Request body exceeds the ${this.maxBodyBytes} byte limit`));
290
290
  return;
291
291
  }
292
292
  chunks.push(chunk);
@@ -308,12 +308,12 @@ class ExpressWrapper {
308
308
  *
309
309
  * Two sources, in this order:
310
310
  * 1. the app's {@link ErrorTranslators}, if it claims the error — it owns the ENTIRE response;
311
- * 2. else {@link HttpErrorWireMapper.toResponse}, the webpieces default, which maps every
312
- * `HttpError` subclass to its status and a CALLER-SAFE body (only `UserError`'s message
311
+ * 2. else {@link ApiErrorHttpMapper.toResponse}, the webpieces default, which maps every
312
+ * `ApiError` subclass to its status and a CALLER-SAFE body (only `ApiEndUserError`'s message
313
313
  * is written for a human, so only it goes out verbatim; everything else sends the generic
314
314
  * reason phrase and logs the real one) and turns anything else into a generic 500.
315
315
  *
316
- * Nothing status-specific is decided here any more — read `HttpErrorWireMapper` for the full rule
316
+ * Nothing status-specific is decided here any more — read `ApiErrorHttpMapper` for the full rule
317
317
  * and the list of statuses, which must stay in step with `ClientErrorTranslator`'s built-in
318
318
  * mapping.
319
319
  */
@@ -363,7 +363,7 @@ class ExpressWrapper {
363
363
  * Put the transaction id on EVERY response — success and error, webpieces' default body and an
364
364
  * app's own. It is INFRASTRUCTURE, not app policy: an app that overrides what an error looks like
365
365
  * must not thereby lose the header its support desk quotes back. That is why this lives here and
366
- * not in {@link HttpErrorWireMapper.toResponse} or in an app's translators.
366
+ * not in {@link ApiErrorHttpMapper.toResponse} or in an app's translators.
367
367
  *
368
368
  * Silently absent when there is no id to send, which is exactly the accepted known issue recorded
369
369
  * at step 0 of {@link executeImpl}: a malformed or oversize body fails before `fillFromRequest`
@@ -1 +1 @@
1
- {"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.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,EAAE,EAAE,CAAC;YAC7B,OAAO;QACX,CAAC;QACD,MAAM,IAAI,GAAG,6BAAc,CAAC,YAAY,CAAC,gCAAoB,CAAC,UAAU,CAAC,CAAC;QAC1E,IAAI,IAAI,EAAE,CAAC;YACP,GAAG,CAAC,SAAS,CAAC,gCAAoB,CAAC,UAAU,CAAC,UAAW,EAAE,IAAI,CAAC,CAAC;QACrE,CAAC;IACL,CAAC;CACJ;AA3WD,wCA2WC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ClientRegistry,\n BadRequestError,\n HttpHeader,\n HttpResponseDto,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport {\n RequestContext,\n HttpRequest,\n RawRequest,\n RequestContextHeaders,\n} from '@webpieces/core-context';\nimport { HttpErrorWireMapper } from './HttpErrorWireMapper';\n\n/**\n * The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body\n * crosses it — the bytes already read are dropped, nothing further is buffered.\n *\n * There was NO limit at all before, which was a latent memory DoS on every route and an outright one\n * on a webhook route: `{ rawBody: true }` retains what it reads, and a webhook url is public by\n * construction, so the endpoint most likely to be flooded was also the one that held on to the flood.\n * 10 MiB is comfortably above any api DTO and well under Cloud Run's own 32 MiB request limit.\n *\n * Read this as FRAMEWORK-FIXED, because today an app has no knob for it. The only seam that accepts a\n * different number is the {@link ExpressWrapper} constructor parameter, and nothing production reaches\n * it: `WebpiecesMiddleware.createExpressWrapper` forwards no such argument, and neither\n * `ExpressWrapper` nor this constant is exported from this package's barrel (`src/index.ts`), so the\n * only caller that can vary the cap is a spec inside this package. An app that legitimately needs to\n * accept a larger body therefore cannot unblock itself and has to open an issue. Making it tunable is a\n * code change, not a config one — a follow-up has to thread a value through `createExpressWrapper` and\n * decide where an app declares it (per-route, most likely, since that is the granularity the need has).\n */\nexport const MAX_BODY_BYTES = 10 * 1024 * 1024;\n\n/**\n * What {@link ExpressWrapper.parseBody} produced: the DTO the controller receives, the verbatim\n * {@link RawRequest} when the route asked for one, and the held parse failure on a raw-body route.\n *\n * Data-only, so a class rather than an inline object literal, per the webpieces guidelines.\n */\nclass ParsedBody {\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n public readonly requestDto: unknown,\n public readonly raw: RawRequest | undefined,\n /** Set only on a raw-body route, where the failure is HELD for AuthFilter instead of thrown. */\n public readonly parseError?: Error,\n ) {}\n}\n\nexport class ExpressWrapper {\n /**\n * Decides what an outside caller is allowed to see of a thrown {@link HttpError}. Stateless —\n * one instance per wrapper is fine, and the class doc there is where the \"only UserError's\n * message goes on the wire\" rule is stated.\n */\n private readonly errorWireMapper = new HttpErrorWireMapper();\n\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n private clientMethod: (requestDto: unknown) => Promise<unknown>,\n private path: string,\n /** Owns the wire<->context transfer, both directions. Stateless framework singleton. */\n private headers: RequestContextHeaders,\n /**\n * True for an @Endpoint(..., { formPost: true }) route: parse the body as\n * application/x-www-form-urlencoded (flat) instead of JSON. Driven by the ANNOTATION, not\n * the request Content-Type header — the annotation is the single source of truth.\n */\n private formPost: boolean = false,\n /**\n * True for an @Endpoint(..., { rawBody: true }) route: RETAIN the verbatim bytes + the\n * absolute url on the published {@link HttpRequest}, so an @WpAuthWebhook hook can verify a\n * vendor signature over what the sender actually transmitted. Also switches the JSON parse\n * failure from \"throw now\" to \"hold it for AuthFilter\" — see {@link RawRequest.bodyParseError}.\n */\n private rawBody: boolean = false,\n /**\n * The inbound body cap for this route. See {@link MAX_BODY_BYTES}.\n *\n * No production caller passes this — `WebpiecesMiddleware.createExpressWrapper` builds every\n * wrapper without it, so every live route runs on the default. The parameter exists so the\n * refusal path can be tested against a small cap instead of a 10 MiB fixture, and the specs in\n * this package are its only callers; it is not an app-facing tuning point, since the class is\n * not exported from `src/index.ts`. If a route ever needs a different cap, thread it through\n * `createExpressWrapper` rather than reaching around the middleware to construct a wrapper.\n */\n private maxBodyBytes: number = MAX_BODY_BYTES,\n ) {}\n\n public async execute(req: Request, res: Response, next: NextFunction): Promise<void> {\n // MOVED: Wrap entire request in RequestContext.run()\n // This establishes AsyncLocalStorage context for the request\n await RequestContext.run(async () => {\n await this.executeTryCatch(req, res, next);\n });\n }\n\n public async executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- ExpressWrapper catches errors to translate to HTTP responses\n try {\n await this.executeImpl(req, res, next);\n } catch (err: unknown) {\n const error = toError(err);\n // 5. Handle errors\n this.handleError(res, error);\n }\n }\n\n public async executeImpl(req: Request, res: Response, next: NextFunction): Promise<void> {\n // 0. PUBLISH the transport-neutral request BEFORE anything that can throw.\n //\n // This is the ordering bug issue #862 was filed for. An app's ErrorTranslators.toWire has\n // to be able to tell WHICH request it is answering for — the surface, the route, the\n // method — and the only place that lives is RequestContext.getRequest(). Publishing it at\n // step 3 (below) meant a body that failed to parse at step 1 reached handleError with an\n // EMPTY scope, so a translator asked \"is this my surface?\" could only answer \"I don't\n // know\" and step aside. The translator was never too late; the context it needs was.\n //\n // No `raw` yet — the bytes have not been read. Step 3 republishes WITH them, below the\n // same request scope and still above the filter chain, so @WpAuthWebhook signature\n // verification sees exactly what it saw before.\n //\n // KNOWN ISSUE, ACCEPTED AND NOT FIXED (issue #862): this publishes the request but does\n // NOT mint the transaction id — that is `fillFromRequest`'s job and it stays at step 3,\n // below the body read. So a caller whose body is malformed or oversize, and who sent no\n // x-request-id of its own, gets an error response with NO transaction id to quote at\n // support. Moving the whole fill up here would drag the raw-body republish into every\n // route, which is the complexity this change deliberately declines. Pinned by a test so a\n // future change to it is a decision rather than an accident.\n RequestContext.setRequest(this.toWebpiecesRequest(req));\n\n // 1. Parse the request body (see parseBody: the PARSER is chosen by the @Endpoint\n // annotation, never by the request Content-Type header).\n const parsed = await this.parseBody(req);\n\n // 2. Translate express's request into the transport-neutral HttpRequest webpieces speaks —\n // now WITH the raw bytes, when the route asked for them.\n const httpRequest = this.toWebpiecesRequest(req, parsed.raw);\n\n // 3. Re-publish the transport-neutral HttpRequest, then move its headers into the context and\n // mint a request id if the caller sent none. BOTH happen above the api boundary, because\n // http-routing requires an already-established, already-filled request scope — it never\n // builds one for you. This is the \"translation layer\" every transport must provide.\n this.headers.fillFromRequest(httpRequest);\n\n // 4. Invoke the api CLIENT method — the SAME proxy tests use. Its filter chain + controller\n // run here, reading the context filled above; the chain never touches express `req`.\n const result = await this.clientMethod(parsed.requestDto);\n\n // 5. Serialize the response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(result);\n this.stampTransactionId(res);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n\n /**\n * Read and parse the request body: the DTO the controller receives, plus the verbatim\n * {@link RawRequest} when the route asked for one.\n *\n * The PARSER is chosen by the `@Endpoint` annotation (`this.formPost`), NOT by the request\n * Content-Type header — the annotation is the single source of truth.\n */\n private async parseBody(req: Request): Promise<ParsedBody> {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new ParsedBody({}, undefined);\n }\n\n // Read BYTES, not text. Concatenating per-chunk toString() corrupted any multi-byte\n // character that straddled a chunk boundary — invisible on small bodies, and fatal for a\n // signature computed over the bytes.\n const bodyBytes = await this.readRequestBody(req);\n const bodyText = bodyBytes.toString('utf8');\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n let requestDto: unknown;\n let parseError: Error | undefined;\n if (this.formPost) {\n // application/x-www-form-urlencoded → flat key→value. URLSearchParams is lenient\n // (never throws) — right for EXTERNAL webhooks (e.g. Twilio) that post form-encoded.\n requestDto = Object.fromEntries(new URLSearchParams(bodyText));\n } else {\n const json = this.parseJson(bodyText);\n requestDto = json.requestDto;\n parseError = json.parseError;\n }\n\n const raw = this.rawBody\n ? new RawRequest(\n this.absoluteUrl(req),\n bodyBytes,\n req.socket?.remoteAddress,\n parseError,\n )\n : undefined;\n return new ParsedBody(requestDto, raw);\n }\n\n /**\n * JSON (the default, SYMMETRIC with the client's JSON.stringify). A non-JSON body is a CLIENT\n * error → 400, not the raw 500 an unguarded JSON.parse would throw.\n *\n * On a raw-body (webhook) route the failure is HELD, not thrown: AuthFilter must answer 401 to an\n * unauthenticated caller rather than 400, because \"your JSON was bad\" tells that caller it got\n * past auth. Everywhere else, fail now.\n */\n private parseJson(bodyText: string): ParsedBody {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- translate parse failure to a 400 HttpError\n try {\n return new ParsedBody(bodyText ? JSON.parse(bodyText) : {}, undefined);\n } catch (err: unknown) {\n const error = toError(err);\n if (!this.rawBody) {\n throw new BadRequestError(\n 'Request body is not valid JSON',\n undefined,\n undefined,\n error,\n );\n }\n return new ParsedBody({}, undefined, error);\n }\n }\n\n /**\n * Read HTTP headers from Express request.\n * Returns Map of header name (lowercase) -> array of values.\n *\n * HTTP spec allows multiple values for same header name.\n */\n /**\n * express Request -> webpieces {@link HttpRequest}. THE translation layer: below this line the\n * filter chain and controllers never see express, which is what lets the same chain run\n * in-process with no transport at all.\n */\n private toWebpiecesRequest(req: Request, raw?: RawRequest): HttpRequest {\n return new HttpRequest(req.method, this.path, this.readExpressHeaders(req), raw);\n }\n\n /**\n * The absolute url AS THE SENDER ADDRESSED IT — the string a vendor like Twilio signed.\n *\n * `x-forwarded-proto` / `x-forwarded-host` WIN when present, because behind a TLS-terminating\n * proxy (Cloud Run, any load balancer) express's own view is wrong in both halves: `req.protocol`\n * reads `http` and the Host header is the internal one, while the vendor signed the public\n * `https://...` url the customer configured. Reconstructing naively therefore fails 100% of the\n * time in production and works 100% of the time locally — the worst possible pairing, so this is\n * stated here and pinned by a test rather than left to each app.\n *\n * These headers are attacker-controllable when nothing strips them, and that is ACCEPTABLE here\n * precisely because of what the value is used for: a forged url produces a signature that does not\n * verify, i.e. a 401. It grants nothing. (It is used for verification only — never for a redirect.)\n */\n private absoluteUrl(req: Request): string {\n const forwardedProto = req.headers['x-forwarded-proto'];\n const forwardedHost = req.headers['x-forwarded-host'];\n // A proxy chain sends a comma-separated list; the FIRST entry is the original client's hop.\n const proto = this.firstForwarded(forwardedProto) ?? req.protocol;\n const host = this.firstForwarded(forwardedHost) ?? req.get('host') ?? '';\n return `${proto}://${host}${req.originalUrl ?? req.url ?? this.path}`;\n }\n\n private firstForwarded(value: string | string[] | undefined): string | undefined {\n const raw = Array.isArray(value) ? value[0] : value;\n const first = raw?.split(',')[0]?.trim();\n return first === undefined || first === '' ? undefined : first;\n }\n\n private readExpressHeaders(req: Request): Map<string, string[]> {\n const headers = new Map<string, string[]>();\n\n // Express stores headers in req.headers as Record<string, string | string[]>\n for (const [name, value] of Object.entries(req.headers)) {\n const lowerName = name.toLowerCase();\n\n if (typeof value === 'string') {\n headers.set(lowerName, [value]);\n } else if (Array.isArray(value)) {\n headers.set(lowerName, value);\n }\n }\n\n return headers;\n }\n\n /**\n * Read the raw request body as BYTES (we parse manually rather than mounting express.json()).\n *\n * Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that\n * straddles a chunk boundary into two replacement characters, so the body a webhook hook verified\n * would not be the body the vendor signed.\n *\n * REFUSES a body over {@link maxBodyBytes} the moment it crosses the line — the chunks read so far\n * are dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers\n * 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a\n * caller whose request we are refusing to finish reading, and that ordering is the point.\n */\n private async readRequestBody(req: Request): Promise<Buffer> {\n return new Promise((resolve: (body: Buffer) => void, reject: (err: Error) => void) => {\n let chunks: Buffer[] = [];\n let size = 0;\n // A socket emits Buffers; a stream someone put in string mode (or a test's Readable.from)\n // emits strings. Normalize to bytes ONCE, here, so everything downstream counts and\n // concatenates the same units.\n req.on('data', (data: Buffer | string) => {\n const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');\n size += chunk.length;\n if (size > this.maxBodyBytes) {\n chunks = [];\n req.destroy();\n reject(\n new BadRequestError(\n `Request body exceeds the ${this.maxBodyBytes} byte limit`,\n ),\n );\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n resolve(Buffer.concat(chunks));\n });\n req.on('error', (err: Error) => {\n reject(err);\n });\n });\n }\n\n /**\n * Turn a thrown value into the response the caller sees — the SERVER half of webpieces' symmetric\n * error handling (the CLIENT half is `ClientErrorTranslator.translateError`, and the two speak the\n * same {@link HttpResponseDto}).\n *\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n *\n * Two sources, in this order:\n * 1. the app's {@link ErrorTranslators}, if it claims the error — it owns the ENTIRE response;\n * 2. else {@link HttpErrorWireMapper.toResponse}, the webpieces default, which maps every\n * `HttpError` subclass to its status and a CALLER-SAFE body (only `UserError`'s message\n * is written for a human, so only it goes out verbatim; everything else sends the generic\n * reason phrase and logs the real one) and turns anything else into a generic 500.\n *\n * Nothing status-specific is decided here any more — read `HttpErrorWireMapper` for the full rule\n * and the list of statuses, which must stay in step with `ClientErrorTranslator`'s built-in\n * mapping.\n */\n // webpieces-disable no-any-unknown -- a thrown error is genuinely unknown until narrowed below\n public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\n }\n\n // The app's ErrorTranslators own the WHOLE response — status code, reason phrase, headers\n // and body — so an app can publish its own envelope AND its own `Retry-After` /\n // `WWW-Authenticate` / trace header / cookie, which the old (statusCode, protocolError) pair\n // could not express at all. `undefined` means \"not mine\": webpieces' default answers\n // instead. Symmetric with the client's ClientErrorTranslator, which consults\n // tryTranslateFromWire() first, over the identical HttpResponseDto shape.\n const appResponse =\n error instanceof Error ? ClientRegistry.tryTranslateToWire(error) : undefined;\n\n this.send(res, appResponse ?? this.errorWireMapper.toResponse(error));\n }\n\n /**\n * Write an {@link HttpResponseDto} to express — the ONE place a response DTO becomes bytes, used\n * by the app's translators and by webpieces' own default alike.\n *\n * `append`, not `setHeader`, because the DTO's headers are a LIST: HTTP permits repeats\n * (`Set-Cookie` is the everyday one) and `setHeader` would keep only the last of them. That list\n * shape is the whole reason the DTO does not use a Map.\n *\n * `Content-Type: application/json` is INFRASTRUCTURE here, not app policy: webpieces is the one\n * doing the `JSON.stringify`, so it states what it wrote. Express would otherwise default a\n * string body to `text/html`, which is wrong for every response this framework sends. A\n * translator that genuinely wants another type says so in its own header list and wins.\n */\n private send(res: Response, response: HttpResponseDto): void {\n this.stampTransactionId(res);\n const declaresContentType = response.headers.some(\n (header: HttpHeader) => header.name.toLowerCase() === 'content-type',\n );\n if (!declaresContentType) {\n res.setHeader('Content-Type', 'application/json');\n }\n for (const header of response.headers) {\n res.append(header.name, header.value);\n }\n // express writes the reason phrase from `statusMessage`, so a translator that says\n // `new HttpResponseStatus(460, 'Order Not Found')` gets 'Order Not Found' on the status line\n // rather than node's blank default for an unregistered code.\n res.statusMessage = response.status.reason;\n res.status(response.status.code).send(JSON.stringify(response.body));\n }\n\n /**\n * Put the transaction id on EVERY response — success and error, webpieces' default body and an\n * app's own. It is INFRASTRUCTURE, not app policy: an app that overrides what an error looks like\n * must not thereby lose the header its support desk quotes back. That is why this lives here and\n * not in {@link HttpErrorWireMapper.toResponse} or in an app's translators.\n *\n * Silently absent when there is no id to send, which is exactly the accepted known issue recorded\n * at step 0 of {@link executeImpl}: a malformed or oversize body fails before `fillFromRequest`\n * mints one.\n */\n private stampTransactionId(res: Response): void {\n if (!RequestContext.isActive()) {\n return;\n }\n const txId = RequestContext.getUntrusted(WebpiecesCoreHeaders.REQUEST_ID);\n if (txId) {\n res.setHeader(WebpiecesCoreHeaders.REQUEST_ID.httpHeader!, txId);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.ts"],"names":[],"mappings":";;;AACA,oDAO8B;AAC9B,0DAKiC;AACjC,6DAA0D;AAE1D;;;;;;;;;;;;;;;;;GAiBG;AACU,QAAA,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAE/C;;;;;GAKG;AACH,MAAM,UAAU;IAGQ;IACA;IAEA;IALpB;IACI,+FAA+F;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AAI,CAAC,CAAC;QACrE,CAAC;IACL,CAAC;CACJ;AA3WD,wCA2WC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ClientRegistry,\n ApiBadRequestError,\n HttpHeader,\n HttpResponseDto,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport {\n RequestContext,\n HttpRequest,\n RawRequest,\n RequestContextHeaders,\n} from '@webpieces/core-context';\nimport { ApiErrorHttpMapper } from './ApiErrorHttpMapper';\n\n/**\n * The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body\n * crosses it — the bytes already read are dropped, nothing further is buffered.\n *\n * There was NO limit at all before, which was a latent memory DoS on every route and an outright one\n * on a webhook route: `{ rawBody: true }` retains what it reads, and a webhook url is public by\n * construction, so the endpoint most likely to be flooded was also the one that held on to the flood.\n * 10 MiB is comfortably above any api DTO and well under Cloud Run's own 32 MiB request limit.\n *\n * Read this as FRAMEWORK-FIXED, because today an app has no knob for it. The only seam that accepts a\n * different number is the {@link ExpressWrapper} constructor parameter, and nothing production reaches\n * it: `WebpiecesMiddleware.createExpressWrapper` forwards no such argument, and neither\n * `ExpressWrapper` nor this constant is exported from this package's barrel (`src/index.ts`), so the\n * only caller that can vary the cap is a spec inside this package. An app that legitimately needs to\n * accept a larger body therefore cannot unblock itself and has to open an issue. Making it tunable is a\n * code change, not a config one — a follow-up has to thread a value through `createExpressWrapper` and\n * decide where an app declares it (per-route, most likely, since that is the granularity the need has).\n */\nexport const MAX_BODY_BYTES = 10 * 1024 * 1024;\n\n/**\n * What {@link ExpressWrapper.parseBody} produced: the DTO the controller receives, the verbatim\n * {@link RawRequest} when the route asked for one, and the held parse failure on a raw-body route.\n *\n * Data-only, so a class rather than an inline object literal, per the webpieces guidelines.\n */\nclass ParsedBody {\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n public readonly requestDto: unknown,\n public readonly raw: RawRequest | undefined,\n /** Set only on a raw-body route, where the failure is HELD for AuthFilter instead of thrown. */\n public readonly parseError?: Error,\n ) {}\n}\n\nexport class ExpressWrapper {\n /**\n * Decides what an outside caller is allowed to see of a thrown {@link API error}. Stateless —\n * one instance per wrapper is fine, and the class doc there is where the \"only ApiEndUserError's\n * message goes on the wire\" rule is stated.\n */\n private readonly errorWireMapper = new ApiErrorHttpMapper();\n\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n private clientMethod: (requestDto: unknown) => Promise<unknown>,\n private path: string,\n /** Owns the wire<->context transfer, both directions. Stateless framework singleton. */\n private headers: RequestContextHeaders,\n /**\n * True for an @Endpoint(..., { formPost: true }) route: parse the body as\n * application/x-www-form-urlencoded (flat) instead of JSON. Driven by the ANNOTATION, not\n * the request Content-Type header — the annotation is the single source of truth.\n */\n private formPost: boolean = false,\n /**\n * True for an @Endpoint(..., { rawBody: true }) route: RETAIN the verbatim bytes + the\n * absolute url on the published {@link HttpRequest}, so an @WpAuthWebhook hook can verify a\n * vendor signature over what the sender actually transmitted. Also switches the JSON parse\n * failure from \"throw now\" to \"hold it for AuthFilter\" — see {@link RawRequest.bodyParseError}.\n */\n private rawBody: boolean = false,\n /**\n * The inbound body cap for this route. See {@link MAX_BODY_BYTES}.\n *\n * No production caller passes this — `WebpiecesMiddleware.createExpressWrapper` builds every\n * wrapper without it, so every live route runs on the default. The parameter exists so the\n * refusal path can be tested against a small cap instead of a 10 MiB fixture, and the specs in\n * this package are its only callers; it is not an app-facing tuning point, since the class is\n * not exported from `src/index.ts`. If a route ever needs a different cap, thread it through\n * `createExpressWrapper` rather than reaching around the middleware to construct a wrapper.\n */\n private maxBodyBytes: number = MAX_BODY_BYTES,\n ) {}\n\n public async execute(req: Request, res: Response, next: NextFunction): Promise<void> {\n // MOVED: Wrap entire request in RequestContext.run()\n // This establishes AsyncLocalStorage context for the request\n await RequestContext.run(async () => {\n await this.executeTryCatch(req, res, next);\n });\n }\n\n public async executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- ExpressWrapper catches errors to translate to HTTP responses\n try {\n await this.executeImpl(req, res, next);\n } catch (err: unknown) {\n const error = toError(err);\n // 5. Handle errors\n this.handleError(res, error);\n }\n }\n\n public async executeImpl(req: Request, res: Response, next: NextFunction): Promise<void> {\n // 0. PUBLISH the transport-neutral request BEFORE anything that can throw.\n //\n // This is the ordering bug issue #862 was filed for. An app's ErrorTranslators.toWire has\n // to be able to tell WHICH request it is answering for — the surface, the route, the\n // method — and the only place that lives is RequestContext.getRequest(). Publishing it at\n // step 3 (below) meant a body that failed to parse at step 1 reached handleError with an\n // EMPTY scope, so a translator asked \"is this my surface?\" could only answer \"I don't\n // know\" and step aside. The translator was never too late; the context it needs was.\n //\n // No `raw` yet — the bytes have not been read. Step 3 republishes WITH them, below the\n // same request scope and still above the filter chain, so @WpAuthWebhook signature\n // verification sees exactly what it saw before.\n //\n // KNOWN ISSUE, ACCEPTED AND NOT FIXED (issue #862): this publishes the request but does\n // NOT mint the transaction id — that is `fillFromRequest`'s job and it stays at step 3,\n // below the body read. So a caller whose body is malformed or oversize, and who sent no\n // x-request-id of its own, gets an error response with NO transaction id to quote at\n // support. Moving the whole fill up here would drag the raw-body republish into every\n // route, which is the complexity this change deliberately declines. Pinned by a test so a\n // future change to it is a decision rather than an accident.\n RequestContext.setRequest(this.toWebpiecesRequest(req));\n\n // 1. Parse the request body (see parseBody: the PARSER is chosen by the @Endpoint\n // annotation, never by the request Content-Type header).\n const parsed = await this.parseBody(req);\n\n // 2. Translate express's request into the transport-neutral HttpRequest webpieces speaks —\n // now WITH the raw bytes, when the route asked for them.\n const httpRequest = this.toWebpiecesRequest(req, parsed.raw);\n\n // 3. Re-publish the transport-neutral HttpRequest, then move its headers into the context and\n // mint a request id if the caller sent none. BOTH happen above the api boundary, because\n // http-routing requires an already-established, already-filled request scope — it never\n // builds one for you. This is the \"translation layer\" every transport must provide.\n this.headers.fillFromRequest(httpRequest);\n\n // 4. Invoke the api CLIENT method — the SAME proxy tests use. Its filter chain + controller\n // run here, reading the context filled above; the chain never touches express `req`.\n const result = await this.clientMethod(parsed.requestDto);\n\n // 5. Serialize the response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(result);\n this.stampTransactionId(res);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n\n /**\n * Read and parse the request body: the DTO the controller receives, plus the verbatim\n * {@link RawRequest} when the route asked for one.\n *\n * The PARSER is chosen by the `@Endpoint` annotation (`this.formPost`), NOT by the request\n * Content-Type header — the annotation is the single source of truth.\n */\n private async parseBody(req: Request): Promise<ParsedBody> {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new ParsedBody({}, undefined);\n }\n\n // Read BYTES, not text. Concatenating per-chunk toString() corrupted any multi-byte\n // character that straddled a chunk boundary — invisible on small bodies, and fatal for a\n // signature computed over the bytes.\n const bodyBytes = await this.readRequestBody(req);\n const bodyText = bodyBytes.toString('utf8');\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n let requestDto: unknown;\n let parseError: Error | undefined;\n if (this.formPost) {\n // application/x-www-form-urlencoded → flat key→value. URLSearchParams is lenient\n // (never throws) — right for EXTERNAL webhooks (e.g. Twilio) that post form-encoded.\n requestDto = Object.fromEntries(new URLSearchParams(bodyText));\n } else {\n const json = this.parseJson(bodyText);\n requestDto = json.requestDto;\n parseError = json.parseError;\n }\n\n const raw = this.rawBody\n ? new RawRequest(\n this.absoluteUrl(req),\n bodyBytes,\n req.socket?.remoteAddress,\n parseError,\n )\n : undefined;\n return new ParsedBody(requestDto, raw);\n }\n\n /**\n * JSON (the default, SYMMETRIC with the client's JSON.stringify). A non-JSON body is a CLIENT\n * error → 400, not the raw 500 an unguarded JSON.parse would throw.\n *\n * On a raw-body (webhook) route the failure is HELD, not thrown: AuthFilter must answer 401 to an\n * unauthenticated caller rather than 400, because \"your JSON was bad\" tells that caller it got\n * past auth. Everywhere else, fail now.\n */\n private parseJson(bodyText: string): ParsedBody {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- translate parse failure to an ApiBadRequestError\n try {\n return new ParsedBody(bodyText ? JSON.parse(bodyText) : {}, undefined);\n } catch (err: unknown) {\n const error = toError(err);\n if (!this.rawBody) {\n throw new ApiBadRequestError(\n 'Request body is not valid JSON',\n undefined,\n undefined,\n error,\n );\n }\n return new ParsedBody({}, undefined, error);\n }\n }\n\n /**\n * Read HTTP headers from Express request.\n * Returns Map of header name (lowercase) -> array of values.\n *\n * HTTP spec allows multiple values for same header name.\n */\n /**\n * express Request -> webpieces {@link HttpRequest}. THE translation layer: below this line the\n * filter chain and controllers never see express, which is what lets the same chain run\n * in-process with no transport at all.\n */\n private toWebpiecesRequest(req: Request, raw?: RawRequest): HttpRequest {\n return new HttpRequest(req.method, this.path, this.readExpressHeaders(req), raw);\n }\n\n /**\n * The absolute url AS THE SENDER ADDRESSED IT — the string a vendor like Twilio signed.\n *\n * `x-forwarded-proto` / `x-forwarded-host` WIN when present, because behind a TLS-terminating\n * proxy (Cloud Run, any load balancer) express's own view is wrong in both halves: `req.protocol`\n * reads `http` and the Host header is the internal one, while the vendor signed the public\n * `https://...` url the customer configured. Reconstructing naively therefore fails 100% of the\n * time in production and works 100% of the time locally — the worst possible pairing, so this is\n * stated here and pinned by a test rather than left to each app.\n *\n * These headers are attacker-controllable when nothing strips them, and that is ACCEPTABLE here\n * precisely because of what the value is used for: a forged url produces a signature that does not\n * verify, i.e. a 401. It grants nothing. (It is used for verification only — never for a redirect.)\n */\n private absoluteUrl(req: Request): string {\n const forwardedProto = req.headers['x-forwarded-proto'];\n const forwardedHost = req.headers['x-forwarded-host'];\n // A proxy chain sends a comma-separated list; the FIRST entry is the original client's hop.\n const proto = this.firstForwarded(forwardedProto) ?? req.protocol;\n const host = this.firstForwarded(forwardedHost) ?? req.get('host') ?? '';\n return `${proto}://${host}${req.originalUrl ?? req.url ?? this.path}`;\n }\n\n private firstForwarded(value: string | string[] | undefined): string | undefined {\n const raw = Array.isArray(value) ? value[0] : value;\n const first = raw?.split(',')[0]?.trim();\n return first === undefined || first === '' ? undefined : first;\n }\n\n private readExpressHeaders(req: Request): Map<string, string[]> {\n const headers = new Map<string, string[]>();\n\n // Express stores headers in req.headers as Record<string, string | string[]>\n for (const [name, value] of Object.entries(req.headers)) {\n const lowerName = name.toLowerCase();\n\n if (typeof value === 'string') {\n headers.set(lowerName, [value]);\n } else if (Array.isArray(value)) {\n headers.set(lowerName, value);\n }\n }\n\n return headers;\n }\n\n /**\n * Read the raw request body as BYTES (we parse manually rather than mounting express.json()).\n *\n * Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that\n * straddles a chunk boundary into two replacement characters, so the body a webhook hook verified\n * would not be the body the vendor signed.\n *\n * REFUSES a body over {@link maxBodyBytes} the moment it crosses the line — the chunks read so far\n * are dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers\n * 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a\n * caller whose request we are refusing to finish reading, and that ordering is the point.\n */\n private async readRequestBody(req: Request): Promise<Buffer> {\n return new Promise((resolve: (body: Buffer) => void, reject: (err: Error) => void) => {\n let chunks: Buffer[] = [];\n let size = 0;\n // A socket emits Buffers; a stream someone put in string mode (or a test's Readable.from)\n // emits strings. Normalize to bytes ONCE, here, so everything downstream counts and\n // concatenates the same units.\n req.on('data', (data: Buffer | string) => {\n const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');\n size += chunk.length;\n if (size > this.maxBodyBytes) {\n chunks = [];\n req.destroy();\n reject(\n new ApiBadRequestError(\n `Request body exceeds the ${this.maxBodyBytes} byte limit`,\n ),\n );\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n resolve(Buffer.concat(chunks));\n });\n req.on('error', (err: Error) => {\n reject(err);\n });\n });\n }\n\n /**\n * Turn a thrown value into the response the caller sees — the SERVER half of webpieces' symmetric\n * error handling (the CLIENT half is `ClientErrorTranslator.translateError`, and the two speak the\n * same {@link HttpResponseDto}).\n *\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n *\n * Two sources, in this order:\n * 1. the app's {@link ErrorTranslators}, if it claims the error — it owns the ENTIRE response;\n * 2. else {@link ApiErrorHttpMapper.toResponse}, the webpieces default, which maps every\n * `ApiError` subclass to its status and a CALLER-SAFE body (only `ApiEndUserError`'s message\n * is written for a human, so only it goes out verbatim; everything else sends the generic\n * reason phrase and logs the real one) and turns anything else into a generic 500.\n *\n * Nothing status-specific is decided here any more — read `ApiErrorHttpMapper` for the full rule\n * and the list of statuses, which must stay in step with `ClientErrorTranslator`'s built-in\n * mapping.\n */\n // webpieces-disable no-any-unknown -- a thrown error is genuinely unknown until narrowed below\n public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\n }\n\n // The app's ErrorTranslators own the WHOLE response — status code, reason phrase, headers\n // and body — so an app can publish its own envelope AND its own `Retry-After` /\n // `WWW-Authenticate` / trace header / cookie, which the old (statusCode, protocolError) pair\n // could not express at all. `undefined` means \"not mine\": webpieces' default answers\n // instead. Symmetric with the client's ClientErrorTranslator, which consults\n // tryTranslateFromWire() first, over the identical HttpResponseDto shape.\n const appResponse =\n error instanceof Error ? ClientRegistry.tryTranslateToWire(error) : undefined;\n\n this.send(res, appResponse ?? this.errorWireMapper.toResponse(error));\n }\n\n /**\n * Write an {@link HttpResponseDto} to express — the ONE place a response DTO becomes bytes, used\n * by the app's translators and by webpieces' own default alike.\n *\n * `append`, not `setHeader`, because the DTO's headers are a LIST: HTTP permits repeats\n * (`Set-Cookie` is the everyday one) and `setHeader` would keep only the last of them. That list\n * shape is the whole reason the DTO does not use a Map.\n *\n * `Content-Type: application/json` is INFRASTRUCTURE here, not app policy: webpieces is the one\n * doing the `JSON.stringify`, so it states what it wrote. Express would otherwise default a\n * string body to `text/html`, which is wrong for every response this framework sends. A\n * translator that genuinely wants another type says so in its own header list and wins.\n */\n private send(res: Response, response: HttpResponseDto): void {\n this.stampTransactionId(res);\n const declaresContentType = response.headers.some(\n (header: HttpHeader) => header.name.toLowerCase() === 'content-type',\n );\n if (!declaresContentType) {\n res.setHeader('Content-Type', 'application/json');\n }\n for (const header of response.headers) {\n res.append(header.name, header.value);\n }\n // express writes the reason phrase from `statusMessage`, so a translator that says\n // `new HttpResponseStatus(460, 'Order Not Found')` gets 'Order Not Found' on the status line\n // rather than node's blank default for an unregistered code.\n res.statusMessage = response.status.reason;\n res.status(response.status.code).send(JSON.stringify(response.body));\n }\n\n /**\n * Put the transaction id on EVERY response — success and error, webpieces' default body and an\n * app's own. It is INFRASTRUCTURE, not app policy: an app that overrides what an error looks like\n * must not thereby lose the header its support desk quotes back. That is why this lives here and\n * not in {@link ApiErrorHttpMapper.toResponse} or in an app's translators.\n *\n * Silently absent when there is no id to send, which is exactly the accepted known issue recorded\n * at step 0 of {@link executeImpl}: a malformed or oversize body fails before `fillFromRequest`\n * mints one.\n */\n private stampTransactionId(res: Response): void {\n if (!RequestContext.isActive()) {\n return;\n }\n const txId = RequestContext.getUntrusted(WebpiecesCoreHeaders.REQUEST_ID);\n if (txId) {\n res.setHeader(WebpiecesCoreHeaders.REQUEST_ID.httpHeader!, txId);\n }\n }\n}\n"]}
@@ -53,7 +53,7 @@ export declare class WebpiecesExpressRouter {
53
53
  /**
54
54
  * Bind EACH method of one ApiClient. The api's @ApiPath/@Endpoint decorators give the paths;
55
55
  * for each we wrap the matching client method (the proxy — RequestContext.run + header read +
56
- * JSON body parse + error→ProtocolError all live in the wrapper/chain) and register the route.
56
+ * JSON body parse + error→ApiErrorPayload all live in the wrapper/chain) and register the route.
57
57
  * This is one-to-one with a test: an HTTP POST maps straight to `client[method](dto)`.
58
58
  *
59
59
  * @returns the number of routes mounted for this api.
@@ -108,7 +108,7 @@ class WebpiecesExpressRouter {
108
108
  /**
109
109
  * Bind EACH method of one ApiClient. The api's @ApiPath/@Endpoint decorators give the paths;
110
110
  * for each we wrap the matching client method (the proxy — RequestContext.run + header read +
111
- * JSON body parse + error→ProtocolError all live in the wrapper/chain) and register the route.
111
+ * JSON body parse + error→ApiErrorPayload all live in the wrapper/chain) and register the route.
112
112
  * This is one-to-one with a test: an HTTP POST maps straight to `client[method](dto)`.
113
113
  *
114
114
  * @returns the number of routes mounted for this api.
@@ -1 +1 @@
1
- {"version":3,"file":"WebpiecesExpressRouter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesExpressRouter.ts"],"names":[],"mappings":";;;AACA,0DAQiC;AACjC,oDAAkD;AAClD,+DAAiF;AAEjF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAK3D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,sBAAsB;IAGF;IAFZ,UAAU,GAAG,IAAI,yCAAmB,EAAE,CAAC;IAExD,YAA6B,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;IAAG,CAAC;IAEvD;;;;;;OAMG;IACH,WAAW,CAAC,GAAY;QACpB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,EAAE,CAAC;YACnD,KAAK,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QACjD,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,WAAW,KAAK,kCAAkC,CAAC,CAAC;IACjE,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,mBAAmB,CACrB,GAAY,EACZ,OAAe,IAAI,EACnB,MAAwB;QAExB,+EAA+E;QAC/E,6FAA6F;QAC7F,0FAA0F;QAC1F,4FAA4F;QAC5F,6FAA6F;QAC7F,iEAAiE;QACjE,MAAM,WAAW,GAAG,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC;QAC9C,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,MAAM,C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AAC,IAAI,CAAC,wBAAwB,UAAU,EAAE,CAAC,CAAC;QACvD,CAAC;IACL,CAAC;CACJ;AAjJD,wDAiJC","sourcesContent":["import { Express } from 'express';\nimport {\n ApiFactory,\n ApiClient,\n getApiPath,\n getEndpoints,\n isFormPost,\n isRawBody,\n WebpiecesConfig,\n} from '@webpieces/http-routing';\nimport { LogManager } from '@webpieces/core-util';\nimport { WebpiecesMiddleware, ExpressRouteHandler } from './WebpiecesMiddleware';\n\nconst log = LogManager.getLogger('WebpiecesExpressRouter');\n\n/** The value returned by express `app.listen(...)` (a node http.Server). */\ntype HttpServer = ReturnType<Express['listen']>;\n\n/**\n * WebpiecesExpressRouter - the express layer that sits ON TOP of a node-only\n * {@link ApiFactory} (a WebpiecesRouter). It is the ONLY place express lifecycle lives.\n *\n * It never reaches into routing internals: it asks the ApiFactory for `apiClients()` — each\n * an api + routeMeta + composed filter-chain→controller impl — and binds each to an express\n * route (`app.<verb>(path, handler)`) invoked when the matching HTTP request arrives. The\n * RouteBuilder stays hidden inside the ApiFactory.\n *\n * ```typescript\n * const apiFactory = await WebpiecesRouterFactory.create(config, { appBindings });\n * apiFactory.addRoutes(SaveApi, SaveController);\n * const express = new WebpiecesExpressRouter(apiFactory);\n *\n * // legacy / side-by-side: mount onto an existing app; you own listen + your middleware\n * express.bindExpress(existingApp);\n *\n * // non-legacy: add webpieces global middleware + listen for you\n * await express.bindAndStartExpress(express(), 8080);\n * ```\n */\nexport class WebpiecesExpressRouter {\n private readonly middleware = new WebpiecesMiddleware();\n\n constructor(private readonly apiFactory: ApiFactory) {}\n\n /**\n * Mount the webpieces routes (each fully self-contained: own body parse, RequestContext,\n * express-tier + api-tier filter chain, error→JSON) onto the caller's express app.\n *\n * Adds NO global app.use() middleware, so it is safe to attach to a legacy app whose other\n * routes must stay untouched. The caller owns app.listen() and any global middleware.\n */\n bindExpress(app: Express): void {\n let count = 0;\n for (const apiClient of this.apiFactory.apiClients()) {\n count += this.mountApiClient(app, apiClient);\n }\n log.info(`Mounted ${count} webpieces route(s) onto express`);\n }\n\n /**\n * Add the webpieces global middleware (optional CORS), bind the routes, mount the top-level\n * error handler AFTER them, then app.listen(port). Convenience for a non-legacy webpieces server where\n * webpieces owns the whole express app. Resolves with the http.Server once listening.\n *\n * CORS is mounted ONLY when `config.corsOrigins` is non-empty — see the note below and\n * {@link WebpiecesMiddleware.corsMiddleware}.\n */\n async bindAndStartExpress(\n app: Express,\n port: number = 8080,\n config?: WebpiecesConfig,\n ): Promise<HttpServer> {\n // Global middleware layers (outermost first) — only for a webpieces-owned app.\n // CORS is OPT-IN, and stays OFF in production. A server that serves its own browser app does\n // not need it — a browser applies no cors check to a same-origin request — so mounting it\n // would only hand credentialed cross-origin read access to whatever it allows, for nothing.\n // It is needed solely when a browser on ANOTHER origin calls this api: `ng serve` in dev, or\n // a UI hosted on a different host. Those say so via corsOrigins.\n const corsOrigins = config?.corsOrigins ?? [];\n if (corsOrigins.length > 0) {\n app.use(this.middleware.corsMiddleware(config));\n }\n\n this.bindExpress(app);\n\n // Top-level error handler is mounted LAST (AFTER the routes). Express only forwards a\n // downstream failure to a 4-arg error middleware that sits BELOW the failing route — it does\n // NOT bubble errors back up through next(). See WebpiecesMiddleware.errorHandler.\n app.use(this.middleware.errorHandler.bind(this.middleware));\n\n return new Promise<HttpServer>(\n (resolve: (server: HttpServer) => void, reject: (err: Error) => void) => {\n const server: HttpServer = app.listen(port, (error?: Error) => {\n if (error) {\n log.error(`Failed to start on port ${port}:`, error);\n reject(error);\n return;\n }\n log.info(`Listening on http://localhost:${port}`);\n this.logStartupBanner(port);\n resolve(server);\n });\n },\n );\n }\n\n /**\n * The \"Svr Ready!!\" ASCII banner, LOCAL DEV ONLY (skipped on Cloud Run, where `K_SERVICE` is set and\n * every line becomes its own structured log entry — a multi-line banner there is pure noise). Copied\n * verbatim from the production service it was ported from, so a familiar splash marks \"the server is up and reachable\".\n */\n private logStartupBanner(port: number): void {\n if (process.env['K_SERVICE']) {\n return;\n }\n log.info(`\n ___ _____ _\n/ _| | _ \\\\ | |\n\\\\ \\`--. _ _ ___ ___ _ _ | |_/ /_ _ _ _| |_ _\n \\`--. \\\\/ _ \\\\ '_\\\\ \\\\ / / _ \\\\ '_| | // _ \\\\/ _\\` |/ _\\` | | | |\n/\\\\_/ / _/ | \\\\ V / _/ | | |\\\\ \\\\ _/ (_| | (_| | |_| |\n\\\\___/ \\\\_|_| \\\\_/ \\\\_|_| \\\\_| \\\\_\\\\_|\\\\_,_|\\\\_,_|\\\\_, |\n _/ |\n |_/\n\n Svr Ready!! port=${port}\n`);\n }\n\n /**\n * Bind EACH method of one ApiClient. The api's @ApiPath/@Endpoint decorators give the paths;\n * for each we wrap the matching client method (the proxy — RequestContext.run + header read +\n * JSON body parse + error→ProtocolError all live in the wrapper/chain) and register the route.\n * This is one-to-one with a test: an HTTP POST maps straight to `client[method](dto)`.\n *\n * @returns the number of routes mounted for this api.\n */\n private mountApiClient(app: Express, apiClient: ApiClient): number {\n const basePath = getApiPath(apiClient.api) || '';\n const endpoints = getEndpoints(apiClient.api) || {};\n let count = 0;\n for (const [methodName, endpointPath] of Object.entries(endpoints)) {\n const path = basePath + endpointPath;\n // The parser is chosen by the @Endpoint annotation, not the request Content-Type — and\n // so is whether the verbatim bytes survive the parse for an @WpAuthWebhook hook to verify.\n const wrapper = this.middleware.createExpressWrapper(\n apiClient.client[methodName],\n path,\n isFormPost(apiClient.api, methodName),\n isRawBody(apiClient.api, methodName),\n );\n // All webpieces routes are POST (the api-tier convention).\n this.registerHandler(app, 'POST', path, wrapper.execute.bind(wrapper));\n count++;\n }\n return count;\n }\n\n private registerHandler(\n app: Express,\n httpMethod: string,\n path: string,\n expressHandler: ExpressRouteHandler,\n ): void {\n switch (httpMethod.toLowerCase()) {\n case 'get':\n app.get(path, expressHandler);\n break;\n case 'post':\n app.post(path, expressHandler);\n break;\n case 'put':\n app.put(path, expressHandler);\n break;\n case 'delete':\n app.delete(path, expressHandler);\n break;\n case 'patch':\n app.patch(path, expressHandler);\n break;\n default:\n log.warn(`Unknown HTTP method: ${httpMethod}`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"WebpiecesExpressRouter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesExpressRouter.ts"],"names":[],"mappings":";;;AACA,0DAQiC;AACjC,oDAAkD;AAClD,+DAAiF;AAEjF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAK3D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,sBAAsB;IAGF;IAFZ,UAAU,GAAG,IAAI,yCAAmB,EAAE,CAAC;IAExD,YAA6B,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;IAAG,CAAC;IAEvD;;;;;;OAMG;IACH,WAAW,CAAC,GAAY;QACpB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,EAAE,CAAC;YACnD,KAAK,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QACjD,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,WAAW,KAAK,kCAAkC,CAAC,CAAC;IACjE,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,mBAAmB,CACrB,GAAY,EACZ,OAAe,IAAI,EACnB,MAAwB;QAExB,+EAA+E;QAC/E,6FAA6F;QAC7F,0FAA0F;QAC1F,4FAA4F;QAC5F,6FAA6F;QAC7F,iEAAiE;QACjE,MAAM,WAAW,GAAG,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC;QAC9C,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC;QACpD,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QAEtB,sF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wDAiJC","sourcesContent":["import { Express } from 'express';\nimport {\n ApiFactory,\n ApiClient,\n getApiPath,\n getEndpoints,\n isFormPost,\n isRawBody,\n WebpiecesConfig,\n} from '@webpieces/http-routing';\nimport { LogManager } from '@webpieces/core-util';\nimport { WebpiecesMiddleware, ExpressRouteHandler } from './WebpiecesMiddleware';\n\nconst log = LogManager.getLogger('WebpiecesExpressRouter');\n\n/** The value returned by express `app.listen(...)` (a node http.Server). */\ntype HttpServer = ReturnType<Express['listen']>;\n\n/**\n * WebpiecesExpressRouter - the express layer that sits ON TOP of a node-only\n * {@link ApiFactory} (a WebpiecesRouter). It is the ONLY place express lifecycle lives.\n *\n * It never reaches into routing internals: it asks the ApiFactory for `apiClients()` — each\n * an api + routeMeta + composed filter-chain→controller impl — and binds each to an express\n * route (`app.<verb>(path, handler)`) invoked when the matching HTTP request arrives. The\n * RouteBuilder stays hidden inside the ApiFactory.\n *\n * ```typescript\n * const apiFactory = await WebpiecesRouterFactory.create(config, { appBindings });\n * apiFactory.addRoutes(SaveApi, SaveController);\n * const express = new WebpiecesExpressRouter(apiFactory);\n *\n * // legacy / side-by-side: mount onto an existing app; you own listen + your middleware\n * express.bindExpress(existingApp);\n *\n * // non-legacy: add webpieces global middleware + listen for you\n * await express.bindAndStartExpress(express(), 8080);\n * ```\n */\nexport class WebpiecesExpressRouter {\n private readonly middleware = new WebpiecesMiddleware();\n\n constructor(private readonly apiFactory: ApiFactory) {}\n\n /**\n * Mount the webpieces routes (each fully self-contained: own body parse, RequestContext,\n * express-tier + api-tier filter chain, error→JSON) onto the caller's express app.\n *\n * Adds NO global app.use() middleware, so it is safe to attach to a legacy app whose other\n * routes must stay untouched. The caller owns app.listen() and any global middleware.\n */\n bindExpress(app: Express): void {\n let count = 0;\n for (const apiClient of this.apiFactory.apiClients()) {\n count += this.mountApiClient(app, apiClient);\n }\n log.info(`Mounted ${count} webpieces route(s) onto express`);\n }\n\n /**\n * Add the webpieces global middleware (optional CORS), bind the routes, mount the top-level\n * error handler AFTER them, then app.listen(port). Convenience for a non-legacy webpieces server where\n * webpieces owns the whole express app. Resolves with the http.Server once listening.\n *\n * CORS is mounted ONLY when `config.corsOrigins` is non-empty — see the note below and\n * {@link WebpiecesMiddleware.corsMiddleware}.\n */\n async bindAndStartExpress(\n app: Express,\n port: number = 8080,\n config?: WebpiecesConfig,\n ): Promise<HttpServer> {\n // Global middleware layers (outermost first) — only for a webpieces-owned app.\n // CORS is OPT-IN, and stays OFF in production. A server that serves its own browser app does\n // not need it — a browser applies no cors check to a same-origin request — so mounting it\n // would only hand credentialed cross-origin read access to whatever it allows, for nothing.\n // It is needed solely when a browser on ANOTHER origin calls this api: `ng serve` in dev, or\n // a UI hosted on a different host. Those say so via corsOrigins.\n const corsOrigins = config?.corsOrigins ?? [];\n if (corsOrigins.length > 0) {\n app.use(this.middleware.corsMiddleware(config));\n }\n\n this.bindExpress(app);\n\n // Top-level error handler is mounted LAST (AFTER the routes). Express only forwards a\n // downstream failure to a 4-arg error middleware that sits BELOW the failing route — it does\n // NOT bubble errors back up through next(). See WebpiecesMiddleware.errorHandler.\n app.use(this.middleware.errorHandler.bind(this.middleware));\n\n return new Promise<HttpServer>(\n (resolve: (server: HttpServer) => void, reject: (err: Error) => void) => {\n const server: HttpServer = app.listen(port, (error?: Error) => {\n if (error) {\n log.error(`Failed to start on port ${port}:`, error);\n reject(error);\n return;\n }\n log.info(`Listening on http://localhost:${port}`);\n this.logStartupBanner(port);\n resolve(server);\n });\n },\n );\n }\n\n /**\n * The \"Svr Ready!!\" ASCII banner, LOCAL DEV ONLY (skipped on Cloud Run, where `K_SERVICE` is set and\n * every line becomes its own structured log entry — a multi-line banner there is pure noise). Copied\n * verbatim from the production service it was ported from, so a familiar splash marks \"the server is up and reachable\".\n */\n private logStartupBanner(port: number): void {\n if (process.env['K_SERVICE']) {\n return;\n }\n log.info(`\n ___ _____ _\n/ _| | _ \\\\ | |\n\\\\ \\`--. _ _ ___ ___ _ _ | |_/ /_ _ _ _| |_ _\n \\`--. \\\\/ _ \\\\ '_\\\\ \\\\ / / _ \\\\ '_| | // _ \\\\/ _\\` |/ _\\` | | | |\n/\\\\_/ / _/ | \\\\ V / _/ | | |\\\\ \\\\ _/ (_| | (_| | |_| |\n\\\\___/ \\\\_|_| \\\\_/ \\\\_|_| \\\\_| \\\\_\\\\_|\\\\_,_|\\\\_,_|\\\\_, |\n _/ |\n |_/\n\n Svr Ready!! port=${port}\n`);\n }\n\n /**\n * Bind EACH method of one ApiClient. The api's @ApiPath/@Endpoint decorators give the paths;\n * for each we wrap the matching client method (the proxy — RequestContext.run + header read +\n * JSON body parse + error→ApiErrorPayload all live in the wrapper/chain) and register the route.\n * This is one-to-one with a test: an HTTP POST maps straight to `client[method](dto)`.\n *\n * @returns the number of routes mounted for this api.\n */\n private mountApiClient(app: Express, apiClient: ApiClient): number {\n const basePath = getApiPath(apiClient.api) || '';\n const endpoints = getEndpoints(apiClient.api) || {};\n let count = 0;\n for (const [methodName, endpointPath] of Object.entries(endpoints)) {\n const path = basePath + endpointPath;\n // The parser is chosen by the @Endpoint annotation, not the request Content-Type — and\n // so is whether the verbatim bytes survive the parse for an @WpAuthWebhook hook to verify.\n const wrapper = this.middleware.createExpressWrapper(\n apiClient.client[methodName],\n path,\n isFormPost(apiClient.api, methodName),\n isRawBody(apiClient.api, methodName),\n );\n // All webpieces routes are POST (the api-tier convention).\n this.registerHandler(app, 'POST', path, wrapper.execute.bind(wrapper));\n count++;\n }\n return count;\n }\n\n private registerHandler(\n app: Express,\n httpMethod: string,\n path: string,\n expressHandler: ExpressRouteHandler,\n ): void {\n switch (httpMethod.toLowerCase()) {\n case 'get':\n app.get(path, expressHandler);\n break;\n case 'post':\n app.post(path, expressHandler);\n break;\n case 'put':\n app.put(path, expressHandler);\n break;\n case 'delete':\n app.delete(path, expressHandler);\n break;\n case 'patch':\n app.patch(path, expressHandler);\n break;\n default:\n log.warn(`Unknown HTTP method: ${httpMethod}`);\n }\n }\n}\n"]}
@@ -51,7 +51,7 @@ export declare class WebpiecesMiddleware {
51
51
  * (body parsing, unmatched paths, a bug in the wrapper itself).
52
52
  *
53
53
  * The page carries NO `error.message`. It used to render one into a `<pre>` block, which is the
54
- * same leak `HttpErrorWireMapper` closes on the JSON side and a worse one here: the errors that
54
+ * same leak `ApiErrorHttpMapper` closes on the JSON side and a worse one here: the errors that
55
55
  * reach THIS handler are the unhandled ones, whose messages are stack-adjacent internals nobody
56
56
  * wrote for a caller to read. The message is logged one line above, which is where it belongs.
57
57
  */
@@ -56,7 +56,7 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
56
56
  * (body parsing, unmatched paths, a bug in the wrapper itself).
57
57
  *
58
58
  * The page carries NO `error.message`. It used to render one into a `<pre>` block, which is the
59
- * same leak `HttpErrorWireMapper` closes on the JSON side and a worse one here: the errors that
59
+ * same leak `ApiErrorHttpMapper` closes on the JSON side and a worse one here: the errors that
60
60
  * reach THIS handler are the unhandled ones, whose messages are stack-adjacent internals nobody
61
61
  * wrote for a caller to read. The message is logged one line above, which is where it belongs.
62
62
  */
@@ -1 +1 @@
1
- {"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,0DAAqF;AACrF,oDAA+C;AAC/C,0DAAgE;AAChE,oDAAkD;AAClD,qDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AACxD,iGAAiG;AACjG,+FAA+F;AAC/F,MAAM,OAAO,GAAG,sBAAU,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAa7C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAC5B,0FAA0F;IACzE,OAAO,GAAG,IAAI,oCAAqB,EAAE,CAAC;IAEvD;;;;;;;;;;;;;;;;;;OAkBG;IACH,2GAA2G;IAC3G,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AAC,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;YACpC,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC;YACnC,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC7C,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,oBAAoB;IAChB,+FAA+F;IAC/F,YAAuD,EACvD,IAAY,EACZ,WAAoB,KAAK,EACzB,UAAmB,KAAK;QAExB,OAAO,IAAI,+BAAc,CAAC,YAAY,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACnF,CAAC;CACJ,CAAA;AAvLY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;GACf,mBAAmB,CAuL/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { ExpressWrapper } from './ExpressWrapper';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n// CORS mount/allow/block lines log under their own name (not [WebpiecesMiddleware]); the backend\n// prepends \"[CORS]\" for us, so the message strings below carry no literal prefix of their own.\nconst corsLog = LogManager.getLogger('CORS');\n\n/**\n * Express route handler function type. Lives in http-server (the express adapter),\n * NOT in the node-only http-routing package, so http-routing stays express-free.\n * Used by WebpiecesExpressRouter to register handlers Express can call.\n */\nexport type ExpressRouteHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => Promise<void>;\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. errorHandler - Top-level 4-arg error middleware, returns HTML 500 page. Mounted AFTER the\n * routes so express can forward downstream failures to it (express routes errors DOWN a\n * separate pipeline, it does not bubble them back up through next()). Last-resort net only:\n * api routes translate their own errors to JSON inside the filter chain (ExpressWrapper).\n * 2. corsMiddleware - Opt-in CORS (mounted only when corsOrigins is non-empty).\n *\n * Per-request logging is intentionally NOT here — the api filter chain's LogApiCall already logs\n * every request/response with full context (requestId, method, path, body), so a plain express\n * START/END line would only duplicate it with less information.\n *\n * Route dispatch happens via Express's registered route handlers (the per-route ExpressWrapper),\n * NOT via this middleware.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideFrameworkSingleton()\nexport class WebpiecesMiddleware {\n /** The ONE wire<->context transfer, handed to every route's ExpressWrapper. Stateless. */\n private readonly headers = new RequestContextHeaders();\n\n /**\n * Top-level error handler — the last-ditch catch-all. MUST be mounted AFTER all routes (see\n * {@link WebpiecesExpressRouter}). The 4-argument `(err, req, res, next)` signature is what\n * tells express this is an error-handling middleware: express's router forwards ANY downstream\n * failure to it — synchronous throws AND rejected async-handler promises alike (the router does\n * `promise.then(null, err => next(err))`, and a `next(err)` with a truthy arg jumps straight to\n * the first 4-arg middleware). This is why a `try { await next() } catch` wrapper is NOT needed\n * (and would not work) — express `next()` is not promise-aware, so it never hands the parent the\n * downstream promise; errors travel down this separate pipeline instead of bubbling back up.\n *\n * Returns an HTML 500 page. Api routes translate their own errors to JSON inside the filter\n * chain (JsonFilter/ExpressWrapper), so this normally only fires for failures OUTSIDE a route\n * (body parsing, unmatched paths, a bug in the wrapper itself).\n *\n * The page carries NO `error.message`. It used to render one into a `<pre>` block, which is the\n * same leak `HttpErrorWireMapper` closes on the JSON side and a worse one here: the errors that\n * reach THIS handler are the unhandled ones, whose messages are stack-adjacent internals nobody\n * wrote for a caller to read. The message is logged one line above, which is where it belongs.\n */\n // webpieces-disable no-any-unknown -- a thrown/forwarded express error is genuinely unknown until narrowed\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- express needs the 4-arg (err,req,res,next) arity to recognize this as error-handling middleware\n errorHandler(err: unknown, req: Request, res: Response, next: NextFunction): void {\n const error = toError(err);\n log.error(`Unhandled error: ${req.method} ${req.path}`, error);\n if (res.headersSent) {\n return;\n }\n // Return HTML error page (not JSON - api routes translate JSON errors in their filter chain)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n </body>\n </html>\n `);\n }\n\n /**\n * CORS middleware. DO NOT MOUNT UNCONDITIONALLY — {@link WebpiecesExpressRouter.bindAndStartExpress}\n * mounts it ONLY when {@link WebpiecesConfig.corsOrigins} is non-empty, and that is the point.\n *\n * CORS exists solely to let a browser on a DIFFERENT origin call this api — in practice\n * `ng serve` on :4200 hitting an api on :8080 during development, or a UI hosted on a different\n * host than the api. A server that serves its own browser app needs NO cors at all, because a\n * browser does not apply cors to a same-origin request. So in production this middleware is\n * normally ABSENT, and absent is the safe state: every origin it allows gains the right to make\n * CREDENTIALED cross-origin calls and READ the responses. Mounting it unconditionally (as the\n * old corsForLocalhost did) handed that right to anything on the victim's localhost, in prod,\n * for no benefit whatsoever.\n *\n * When mounted, allows: a request with NO Origin (curl, server-to-server, a CLI); the server's\n * OWN origin; and EXACTLY the origins in `corsOrigins` — nothing is implicit. Anything else gets\n * a clean 403, never the HTML 500 the old `callback(new Error(...))` produced.\n *\n * SAME-ORIGIN MUST STAY ALLOWED even though a same-origin request needs no cors headers, because\n * a browser attaches an `Origin` header to EVERY POST — including a same-origin POST — and every\n * webpieces route is a POST. Once mounted, this middleware SEES that origin, so if it did not\n * allow it, it would 403 the server's own UI. That was the production bug.\n *\n * The same-origin test compares HOST ONLY, deliberately. Behind a TLS-terminating proxy (Cloud\n * Run, any load balancer) `req.protocol` is `http` while the browser's `Origin` says `https`, so\n * comparing full origins would reject the server's own origin on every deploy.\n *\n * @returns Express middleware handler for CORS\n */\n corsMiddleware(config?: WebpiecesConfig): RequestHandler {\n const allowedOrigins = config?.corsOrigins ?? [];\n corsLog.info(\n `CORS MOUNTED. Allowing same-origin + [${allowedOrigins.join(', ')}]. ` +\n `Every other browser origin gets a 403.`,\n );\n\n const handler = cors({\n origin: true, // reflect the request origin — we have already vetted it below\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*',\n exposedHeaders: '*',\n maxAge: 3600,\n });\n\n return (req: Request, res: Response, next: NextFunction): void => {\n const origin = req.headers.origin;\n if (!origin) {\n // No Origin -> not a browser cross-origin request; nothing to negotiate.\n next();\n return;\n }\n if (this.isOriginAllowed(origin, req.get('host'), allowedOrigins)) {\n handler(req, res, next);\n return;\n }\n corsLog.info(`Blocked origin: ${origin}`);\n res.status(403).json({\n name: 'CorsError',\n message: `CORS not allowed for origin: ${origin}`,\n });\n };\n }\n\n /**\n * Same-origin (HOST ONLY — see corsMiddleware() on why the scheme is deliberately ignored), or an\n * explicit entry in corsOrigins. NOTHING is implicit: localhost is allowed only if the config\n * asked for it, so a production server that enables cors for a cross-host UI does not silently\n * open the door to localhost as well.\n */\n private isOriginAllowed(\n origin: string,\n host: string | undefined,\n allowedOrigins: string[],\n ): boolean {\n let originHost: string;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a malformed Origin is untrusted browser input, not a server fault; it must become a 403 here, never bubble to the 500 chokepoint\n try {\n originHost = new URL(origin).host;\n } catch (err: unknown) {\n const error = toError(err);\n corsLog.info(`Malformed Origin header '${origin}': ${error.message}`);\n return false;\n }\n if (host !== undefined && originHost === host) {\n return true; // same-origin: the server's own UI calling its own api\n }\n return allowedOrigins.some((allowed: string): boolean =>\n this.matchesOrigin(origin, allowed),\n );\n }\n\n /**\n * Exact origin match, except a `*` in the PORT position matches any port: `http://localhost:*`\n * is what a developer writes, because the angular dev-server port moves around.\n *\n * The `*` is deliberately NOT a general wildcard — it never spans a host, and what follows the\n * prefix must be a real (digits-only) port. So `http://localhost:*` cannot be tricked into\n * matching `http://localhost.evil.com`, and a bare `*` matches nothing at all.\n */\n private matchesOrigin(origin: string, allowed: string): boolean {\n if (allowed === origin) {\n return true;\n }\n const wildcardSuffix = ':*';\n if (!allowed.endsWith(wildcardSuffix)) {\n return false;\n }\n const prefix = allowed.slice(0, -wildcardSuffix.length);\n if (!origin.startsWith(`${prefix}:`)) {\n return false;\n }\n const port = origin.slice(prefix.length + 1);\n return /^\\d+$/.test(port);\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design): it publishes the\n * HttpRequest + fills the context, then invokes the api client method (the proxy).\n *\n * @param clientMethod - The api client's method for this route (dto → response); the proxy\n * runs the filter chain + controller.\n * @param path - The route path (used to build the HttpRequest).\n * @param formPost - True for an @Endpoint(..., { formPost: true }) route (parse body as\n * urlencoded, not JSON). Default false = JSON.\n * @param rawBody - True for an @Endpoint(..., { rawBody: true }) route: retain the verbatim\n * bytes + absolute url on the HttpRequest so an @WpAuthWebhook hook can verify a vendor\n * signature over them. Default false = the bytes are dropped once parsed.\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n clientMethod: (requestDto: unknown) => Promise<unknown>,\n path: string,\n formPost: boolean = false,\n rawBody: boolean = false,\n ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path, this.headers, formPost, rawBody);\n }\n}\n"]}
1
+ {"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,0DAAqF;AACrF,oDAA+C;AAC/C,0DAAgE;AAChE,oDAAkD;AAClD,qDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AACxD,iGAAiG;AACjG,+FAA+F;AAC/F,MAAM,OAAO,GAAG,sBAAU,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAa7C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAC5B,0FAA0F;IACzE,OAAO,GAAG,IAAI,oCAAqB,EAAE,CAAC;IAEvD;;;;;;;;;;;;;;;;;;OAkBG;IACH,2GAA2G;IAC3G,gKAAgK;IAChK,YAAY,CAAC,GAAY,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB;QACtE,MAAM,KAAK,GAAG,IAAA,mBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,GAAG,CAAC,KAAK,CAAC,oBAAoB,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;QAC/D,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;YAClB,OAAO;QACX,CAAC;QACD,6FAA6F;QAC7F,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;;;;;;;;;SASpB,CAAC,CAAC;IACP,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,cAAc,CAAC,MAAwB;QACnC,MAAM,cAAc,GAAG,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC;QACjD,OAAO,CAAC,IAAI,CACR,yCAAyC,cAAc,CAAC,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Y,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACnF,CAAC;CACJ,CAAA;AAvLY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;GACf,mBAAmB,CAuL/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { ExpressWrapper } from './ExpressWrapper';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n// CORS mount/allow/block lines log under their own name (not [WebpiecesMiddleware]); the backend\n// prepends \"[CORS]\" for us, so the message strings below carry no literal prefix of their own.\nconst corsLog = LogManager.getLogger('CORS');\n\n/**\n * Express route handler function type. Lives in http-server (the express adapter),\n * NOT in the node-only http-routing package, so http-routing stays express-free.\n * Used by WebpiecesExpressRouter to register handlers Express can call.\n */\nexport type ExpressRouteHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => Promise<void>;\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. errorHandler - Top-level 4-arg error middleware, returns HTML 500 page. Mounted AFTER the\n * routes so express can forward downstream failures to it (express routes errors DOWN a\n * separate pipeline, it does not bubble them back up through next()). Last-resort net only:\n * api routes translate their own errors to JSON inside the filter chain (ExpressWrapper).\n * 2. corsMiddleware - Opt-in CORS (mounted only when corsOrigins is non-empty).\n *\n * Per-request logging is intentionally NOT here — the api filter chain's LogApiCall already logs\n * every request/response with full context (requestId, method, path, body), so a plain express\n * START/END line would only duplicate it with less information.\n *\n * Route dispatch happens via Express's registered route handlers (the per-route ExpressWrapper),\n * NOT via this middleware.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideFrameworkSingleton()\nexport class WebpiecesMiddleware {\n /** The ONE wire<->context transfer, handed to every route's ExpressWrapper. Stateless. */\n private readonly headers = new RequestContextHeaders();\n\n /**\n * Top-level error handler — the last-ditch catch-all. MUST be mounted AFTER all routes (see\n * {@link WebpiecesExpressRouter}). The 4-argument `(err, req, res, next)` signature is what\n * tells express this is an error-handling middleware: express's router forwards ANY downstream\n * failure to it — synchronous throws AND rejected async-handler promises alike (the router does\n * `promise.then(null, err => next(err))`, and a `next(err)` with a truthy arg jumps straight to\n * the first 4-arg middleware). This is why a `try { await next() } catch` wrapper is NOT needed\n * (and would not work) — express `next()` is not promise-aware, so it never hands the parent the\n * downstream promise; errors travel down this separate pipeline instead of bubbling back up.\n *\n * Returns an HTML 500 page. Api routes translate their own errors to JSON inside the filter\n * chain (JsonFilter/ExpressWrapper), so this normally only fires for failures OUTSIDE a route\n * (body parsing, unmatched paths, a bug in the wrapper itself).\n *\n * The page carries NO `error.message`. It used to render one into a `<pre>` block, which is the\n * same leak `ApiErrorHttpMapper` closes on the JSON side and a worse one here: the errors that\n * reach THIS handler are the unhandled ones, whose messages are stack-adjacent internals nobody\n * wrote for a caller to read. The message is logged one line above, which is where it belongs.\n */\n // webpieces-disable no-any-unknown -- a thrown/forwarded express error is genuinely unknown until narrowed\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- express needs the 4-arg (err,req,res,next) arity to recognize this as error-handling middleware\n errorHandler(err: unknown, req: Request, res: Response, next: NextFunction): void {\n const error = toError(err);\n log.error(`Unhandled error: ${req.method} ${req.path}`, error);\n if (res.headersSent) {\n return;\n }\n // Return HTML error page (not JSON - api routes translate JSON errors in their filter chain)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n </body>\n </html>\n `);\n }\n\n /**\n * CORS middleware. DO NOT MOUNT UNCONDITIONALLY — {@link WebpiecesExpressRouter.bindAndStartExpress}\n * mounts it ONLY when {@link WebpiecesConfig.corsOrigins} is non-empty, and that is the point.\n *\n * CORS exists solely to let a browser on a DIFFERENT origin call this api — in practice\n * `ng serve` on :4200 hitting an api on :8080 during development, or a UI hosted on a different\n * host than the api. A server that serves its own browser app needs NO cors at all, because a\n * browser does not apply cors to a same-origin request. So in production this middleware is\n * normally ABSENT, and absent is the safe state: every origin it allows gains the right to make\n * CREDENTIALED cross-origin calls and READ the responses. Mounting it unconditionally (as the\n * old corsForLocalhost did) handed that right to anything on the victim's localhost, in prod,\n * for no benefit whatsoever.\n *\n * When mounted, allows: a request with NO Origin (curl, server-to-server, a CLI); the server's\n * OWN origin; and EXACTLY the origins in `corsOrigins` — nothing is implicit. Anything else gets\n * a clean 403, never the HTML 500 the old `callback(new Error(...))` produced.\n *\n * SAME-ORIGIN MUST STAY ALLOWED even though a same-origin request needs no cors headers, because\n * a browser attaches an `Origin` header to EVERY POST — including a same-origin POST — and every\n * webpieces route is a POST. Once mounted, this middleware SEES that origin, so if it did not\n * allow it, it would 403 the server's own UI. That was the production bug.\n *\n * The same-origin test compares HOST ONLY, deliberately. Behind a TLS-terminating proxy (Cloud\n * Run, any load balancer) `req.protocol` is `http` while the browser's `Origin` says `https`, so\n * comparing full origins would reject the server's own origin on every deploy.\n *\n * @returns Express middleware handler for CORS\n */\n corsMiddleware(config?: WebpiecesConfig): RequestHandler {\n const allowedOrigins = config?.corsOrigins ?? [];\n corsLog.info(\n `CORS MOUNTED. Allowing same-origin + [${allowedOrigins.join(', ')}]. ` +\n `Every other browser origin gets a 403.`,\n );\n\n const handler = cors({\n origin: true, // reflect the request origin — we have already vetted it below\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*',\n exposedHeaders: '*',\n maxAge: 3600,\n });\n\n return (req: Request, res: Response, next: NextFunction): void => {\n const origin = req.headers.origin;\n if (!origin) {\n // No Origin -> not a browser cross-origin request; nothing to negotiate.\n next();\n return;\n }\n if (this.isOriginAllowed(origin, req.get('host'), allowedOrigins)) {\n handler(req, res, next);\n return;\n }\n corsLog.info(`Blocked origin: ${origin}`);\n res.status(403).json({\n name: 'CorsError',\n message: `CORS not allowed for origin: ${origin}`,\n });\n };\n }\n\n /**\n * Same-origin (HOST ONLY — see corsMiddleware() on why the scheme is deliberately ignored), or an\n * explicit entry in corsOrigins. NOTHING is implicit: localhost is allowed only if the config\n * asked for it, so a production server that enables cors for a cross-host UI does not silently\n * open the door to localhost as well.\n */\n private isOriginAllowed(\n origin: string,\n host: string | undefined,\n allowedOrigins: string[],\n ): boolean {\n let originHost: string;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a malformed Origin is untrusted browser input, not a server fault; it must become a 403 here, never bubble to the 500 chokepoint\n try {\n originHost = new URL(origin).host;\n } catch (err: unknown) {\n const error = toError(err);\n corsLog.info(`Malformed Origin header '${origin}': ${error.message}`);\n return false;\n }\n if (host !== undefined && originHost === host) {\n return true; // same-origin: the server's own UI calling its own api\n }\n return allowedOrigins.some((allowed: string): boolean =>\n this.matchesOrigin(origin, allowed),\n );\n }\n\n /**\n * Exact origin match, except a `*` in the PORT position matches any port: `http://localhost:*`\n * is what a developer writes, because the angular dev-server port moves around.\n *\n * The `*` is deliberately NOT a general wildcard — it never spans a host, and what follows the\n * prefix must be a real (digits-only) port. So `http://localhost:*` cannot be tricked into\n * matching `http://localhost.evil.com`, and a bare `*` matches nothing at all.\n */\n private matchesOrigin(origin: string, allowed: string): boolean {\n if (allowed === origin) {\n return true;\n }\n const wildcardSuffix = ':*';\n if (!allowed.endsWith(wildcardSuffix)) {\n return false;\n }\n const prefix = allowed.slice(0, -wildcardSuffix.length);\n if (!origin.startsWith(`${prefix}:`)) {\n return false;\n }\n const port = origin.slice(prefix.length + 1);\n return /^\\d+$/.test(port);\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design): it publishes the\n * HttpRequest + fills the context, then invokes the api client method (the proxy).\n *\n * @param clientMethod - The api client's method for this route (dto → response); the proxy\n * runs the filter chain + controller.\n * @param path - The route path (used to build the HttpRequest).\n * @param formPost - True for an @Endpoint(..., { formPost: true }) route (parse body as\n * urlencoded, not JSON). Default false = JSON.\n * @param rawBody - True for an @Endpoint(..., { rawBody: true }) route: retain the verbatim\n * bytes + absolute url on the HttpRequest so an @WpAuthWebhook hook can verify a vendor\n * signature over them. Default false = the bytes are dropped once parsed.\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n clientMethod: (requestDto: unknown) => Promise<unknown>,\n path: string,\n formPost: boolean = false,\n rawBody: boolean = false,\n ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path, this.headers, formPost, rawBody);\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { WebpiecesExpressRouter } from './WebpiecesExpressRouter';
2
2
  export { WebpiecesMiddleware } from './WebpiecesMiddleware';
3
3
  export { RecordingFilter } from './filters/RecordingFilter';
4
- export { HttpErrorWireMapper } from './HttpErrorWireMapper';
4
+ export { ApiErrorHttpMapper } from './ApiErrorHttpMapper';
5
5
  export { TestCaseRecorderImpl } from './recorder/TestCaseRecorderImpl';
6
6
  export { SpecGenerator } from './recorder/SpecGenerator';
7
7
  export { recordable } from './recorder/recordable';
package/src/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SharedSecrets = exports.AuthenticatedCaller = exports.AuthConfig = exports.HttpRequest = exports.ApiClient = exports.FilterDefinition = exports.FilterMatcher = exports.MethodMeta = exports.RouteHandler = exports.HeaderRegistry = exports.WebpiecesCoreHeaders = exports.recordable = exports.SpecGenerator = exports.TestCaseRecorderImpl = exports.HttpErrorWireMapper = exports.RecordingFilter = exports.WebpiecesMiddleware = exports.WebpiecesExpressRouter = void 0;
3
+ exports.SharedSecrets = exports.AuthenticatedCaller = exports.AuthConfig = exports.HttpRequest = exports.ApiClient = exports.FilterDefinition = exports.FilterMatcher = exports.MethodMeta = exports.RouteHandler = exports.HeaderRegistry = exports.WebpiecesCoreHeaders = exports.recordable = exports.SpecGenerator = exports.TestCaseRecorderImpl = exports.ApiErrorHttpMapper = exports.RecordingFilter = exports.WebpiecesMiddleware = exports.WebpiecesExpressRouter = void 0;
4
4
  // Express adapter (the only place express lifecycle lives) over the node-only ApiFactory
5
5
  var WebpiecesExpressRouter_1 = require("./WebpiecesExpressRouter");
6
6
  Object.defineProperty(exports, "WebpiecesExpressRouter", { enumerable: true, get: function () { return WebpiecesExpressRouter_1.WebpiecesExpressRouter; } });
@@ -14,8 +14,8 @@ Object.defineProperty(exports, "RecordingFilter", { enumerable: true, get: funct
14
14
  // The webpieces DEFAULT error response, exported as a DELEGABLE object: it returns the same
15
15
  // HttpResponseDto an app's ErrorTranslators.toWire returns, so an app wraps it ("webpieces' answer,
16
16
  // plus one header") rather than copying its status-to-message table.
17
- var HttpErrorWireMapper_1 = require("./HttpErrorWireMapper");
18
- Object.defineProperty(exports, "HttpErrorWireMapper", { enumerable: true, get: function () { return HttpErrorWireMapper_1.HttpErrorWireMapper; } });
17
+ var ApiErrorHttpMapper_1 = require("./ApiErrorHttpMapper");
18
+ Object.defineProperty(exports, "ApiErrorHttpMapper", { enumerable: true, get: function () { return ApiErrorHttpMapper_1.ApiErrorHttpMapper; } });
19
19
  // Test-case recording (contract lives in @webpieces/core-util)
20
20
  var TestCaseRecorderImpl_1 = require("./recorder/TestCaseRecorderImpl");
21
21
  Object.defineProperty(exports, "TestCaseRecorderImpl", { enumerable: true, get: function () { return TestCaseRecorderImpl_1.TestCaseRecorderImpl; } });
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/index.ts"],"names":[],"mappings":";;;AAAA,yFAAyF;AACzF,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,gGAAgG;AAChG,+FAA+F;AAC/F,+FAA+F;AAC/F,6DAA4D;AAAnD,kHAAA,eAAe,OAAA;AAExB,4FAA4F;AAC5F,oGAAoG;AACpG,qEAAqE;AACrE,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAE5B,+DAA+D;AAC/D,wEAAuE;AAA9D,4HAAA,oBAAoB,OAAA;AAC7B,0DAAyD;AAAhD,8GAAA,aAAa,OAAA;AACtB,oDAAmD;AAA1C,wGAAA,UAAU,OAAA;AAEnB,mEAAmE;AACnE,uEAAsE;AAA7D,4HAAA,oBAAoB,OAAA;AAC7B,kDAAsD;AAA7C,2GAAA,cAAc,OAAA;AAEvB,gEAAgE;AAChE,wDAYiC;AAX7B,4GAAA,YAAY,OAAA;AACZ,0GAAA,UAAU,OAAA;AAEV,6GAAA,aAAa,OAAA;AACb,gHAAA,gBAAgB,OAAA;AAEhB,yGAAA,SAAS,OAAA;AACT,2GAAA,WAAW,OAAA;AACX,0GAAA,UAAU,OAAA;AACV,mHAAA,mBAAmB,OAAA;AACnB,6GAAA,aAAa,OAAA","sourcesContent":["// Express adapter (the only place express lifecycle lives) over the node-only ApiFactory\nexport { WebpiecesExpressRouter } from './WebpiecesExpressRouter';\nexport { WebpiecesMiddleware } from './WebpiecesMiddleware';\n// LogApiFilter is now a FIXED framework filter auto-installed by WebpiecesRouter (outermost, at\n// priority 1,000,000, above AuthFilter). Apps must NOT install it themselves — it is no longer\n// exported here. Remove any `router.addFilter(new FilterDefinition(1800, LogApiFilter, '*'))`.\nexport { RecordingFilter } from './filters/RecordingFilter';\n\n// The webpieces DEFAULT error response, exported as a DELEGABLE object: it returns the same\n// HttpResponseDto an app's ErrorTranslators.toWire returns, so an app wraps it (\"webpieces' answer,\n// plus one header\") rather than copying its status-to-message table.\nexport { HttpErrorWireMapper } from './HttpErrorWireMapper';\n\n// Test-case recording (contract lives in @webpieces/core-util)\nexport { TestCaseRecorderImpl } from './recorder/TestCaseRecorderImpl';\nexport { SpecGenerator } from './recorder/SpecGenerator';\nexport { recordable } from './recorder/recordable';\n\n// Context keys + registry (the global magic-context header system)\nexport { WebpiecesCoreHeaders } from './headers/WebpiecesCoreHeaders';\nexport { HeaderRegistry } from '@webpieces/core-util';\n\n// Re-export from http-routing for one-import adapter ergonomics\nexport {\n RouteHandler,\n MethodMeta,\n HttpFilter,\n FilterMatcher,\n FilterDefinition,\n ApiFactory,\n ApiClient,\n HttpRequest,\n AuthConfig,\n AuthenticatedCaller,\n SharedSecrets,\n} from '@webpieces/http-routing';\n// ExpressRouteHandler now lives in http-server (express adapter), not node-only http-routing\nexport { ExpressRouteHandler } from './WebpiecesMiddleware';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/index.ts"],"names":[],"mappings":";;;AAAA,yFAAyF;AACzF,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,gGAAgG;AAChG,+FAA+F;AAC/F,+FAA+F;AAC/F,6DAA4D;AAAnD,kHAAA,eAAe,OAAA;AAExB,4FAA4F;AAC5F,oGAAoG;AACpG,qEAAqE;AACrE,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAE3B,+DAA+D;AAC/D,wEAAuE;AAA9D,4HAAA,oBAAoB,OAAA;AAC7B,0DAAyD;AAAhD,8GAAA,aAAa,OAAA;AACtB,oDAAmD;AAA1C,wGAAA,UAAU,OAAA;AAEnB,mEAAmE;AACnE,uEAAsE;AAA7D,4HAAA,oBAAoB,OAAA;AAC7B,kDAAsD;AAA7C,2GAAA,cAAc,OAAA;AAEvB,gEAAgE;AAChE,wDAYiC;AAX7B,4GAAA,YAAY,OAAA;AACZ,0GAAA,UAAU,OAAA;AAEV,6GAAA,aAAa,OAAA;AACb,gHAAA,gBAAgB,OAAA;AAEhB,yGAAA,SAAS,OAAA;AACT,2GAAA,WAAW,OAAA;AACX,0GAAA,UAAU,OAAA;AACV,mHAAA,mBAAmB,OAAA;AACnB,6GAAA,aAAa,OAAA","sourcesContent":["// Express adapter (the only place express lifecycle lives) over the node-only ApiFactory\nexport { WebpiecesExpressRouter } from './WebpiecesExpressRouter';\nexport { WebpiecesMiddleware } from './WebpiecesMiddleware';\n// LogApiFilter is now a FIXED framework filter auto-installed by WebpiecesRouter (outermost, at\n// priority 1,000,000, above AuthFilter). Apps must NOT install it themselves — it is no longer\n// exported here. Remove any `router.addFilter(new FilterDefinition(1800, LogApiFilter, '*'))`.\nexport { RecordingFilter } from './filters/RecordingFilter';\n\n// The webpieces DEFAULT error response, exported as a DELEGABLE object: it returns the same\n// HttpResponseDto an app's ErrorTranslators.toWire returns, so an app wraps it (\"webpieces' answer,\n// plus one header\") rather than copying its status-to-message table.\nexport { ApiErrorHttpMapper } from './ApiErrorHttpMapper';\n\n// Test-case recording (contract lives in @webpieces/core-util)\nexport { TestCaseRecorderImpl } from './recorder/TestCaseRecorderImpl';\nexport { SpecGenerator } from './recorder/SpecGenerator';\nexport { recordable } from './recorder/recordable';\n\n// Context keys + registry (the global magic-context header system)\nexport { WebpiecesCoreHeaders } from './headers/WebpiecesCoreHeaders';\nexport { HeaderRegistry } from '@webpieces/core-util';\n\n// Re-export from http-routing for one-import adapter ergonomics\nexport {\n RouteHandler,\n MethodMeta,\n HttpFilter,\n FilterMatcher,\n FilterDefinition,\n ApiFactory,\n ApiClient,\n HttpRequest,\n AuthConfig,\n AuthenticatedCaller,\n SharedSecrets,\n} from '@webpieces/http-routing';\n// ExpressRouteHandler now lives in http-server (express adapter), not node-only http-routing\nexport { ExpressRouteHandler } from './WebpiecesMiddleware';\n"]}
@@ -1,120 +0,0 @@
1
- import { HttpResponseDto } from '@webpieces/core-util';
2
- /**
3
- * Turns a thrown {@link HttpError} into the {@link ProtocolError} that goes on the wire — and, just
4
- * as importantly, decides what does NOT go on the wire.
5
- *
6
- * # The rule: only {@link UserError}'s `message` is caller-facing
7
- *
8
- * `Error.message` is an OPERATOR-facing field everywhere else in this framework. It is written for
9
- * whoever reads the logs, and it routinely quotes internal detail: a downstream service url, an HTTP
10
- * method and content-type, a body snippet, a table name, an internal id. `http-client-node` builds
11
- * exactly such a message when a downstream dependency answers a 4xx — `ResponseBodyReader`'s
12
- * foreign-body description names the url it called and embeds the html it got back — and that error
13
- * arrives here as an `InternalError`. Copying `error.message` onto the response body handed
14
- * every one of those strings to an external, possibly partner-facing consumer.
15
- *
16
- * {@link UserError} is the ONE type whose message was written for a human to read. That is what
17
- * it is FOR: it is deliberately a 266 (a 2xx code, so it is not lumped in with failures), it carries
18
- * an `errorCode` the caller branches on, and an app throws it on purpose to say something like
19
- * "Email already exists". Its message goes out verbatim.
20
- *
21
- * Every other subclass sends a GENERIC, status-appropriate message (see {@link genericMessage}); the
22
- * real message goes to the LOG only. The behaviour used to be exactly backwards — an unexpected crash
23
- * was safely generic while a DELIBERATE `InternalError` shipped its full message outward.
24
- *
25
- * # What still goes out, and why
26
- *
27
- * - `errorCode` ({@link UserError}) and `waitSeconds` ({@link VendorError}) are structured
28
- * CONTRACT data the client is meant to branch on, not prose. They carry no internal detail.
29
- * - `field` and `guiAlertMessage` ({@link BadRequestError}) stay. `guiMessage` exists precisely
30
- * to be the human-safe half of a bad request — its existence is the admission that `message` is the
31
- * operator-facing half — and a form field name is not internal detail. The `message` itself is
32
- * genericised like every other non-user error.
33
- * - `subType` stays. It is NOT derived from a class name: it is an explicit constructor argument an
34
- * app passes on purpose (`WRONG_LOGIN`, `NOT_APPROVED`, `EMAIL_NOT_CONFIRMED`, … from
35
- * `core-util/src/http/errors.ts`), which makes it structured contract data of the same kind as
36
- * `errorCode`. `ClientErrorTranslator` reads it back when reconstructing `UnauthorizedError`
37
- * and the generic `HttpError`, so dropping it would break that reconstruction for the one case —
38
- * login failure reasons — where the caller genuinely has to branch on WHY.
39
- * - `name` is GONE from this ladder. Nothing in `ClientErrorTranslator` ever read it, so it is not
40
- * contract data. For a built-in it was a constant string 1:1 with the status code (`'BadRequest'`,
41
- * `'InternalServerError'`), i.e. it told the caller nothing the status had not already told it —
42
- * and for any SUBCLASS reaching this ladder it was literally an internal class name
43
- * (`'EndpointNotFoundError'`, or whatever an app happened to name its type). That is a free read of
44
- * the server's internals for zero caller benefit, so it is not sent. It is logged instead.
45
- *
46
- * An app that WANTS a different wire shape has an explicit opt-out on both sides:
47
- * `ClientRegistry.setErrorTranslators()`. `ExpressWrapper.handleError` consults
48
- * `tryTranslateToWire()` BEFORE reaching this class, and whatever that returns is sent verbatim —
49
- * that is the app's own deliberate choice about what it publishes.
50
- *
51
- * # This class IS the webpieces default, and it is DELEGABLE
52
- *
53
- * {@link toResponse} produces the same {@link HttpResponseDto} an app's `ErrorTranslators.toWire`
54
- * produces, so an app that wants "webpieces' answer, plus one header" or "webpieces' answer for
55
- * everything except MY type" WRAPS this instead of reimplementing it. That is not hypothetical:
56
- * a consumer's envelope class carried a status-to-message table with the comment "copied verbatim
57
- * from HttpErrorWireMapper's own table". Copying framework internals is the symptom of a missing
58
- * export, so the class and {@link genericMessage} are both public and both exported from this
59
- * package's barrel.
60
- */
61
- export declare class HttpErrorWireMapper {
62
- /**
63
- * status code → the generic, caller-safe text sent in its place. These are the standard HTTP
64
- * reason phrases (plus 266 and 598, webpieces' own user/vendor codes), so a caller reading the
65
- * body learns exactly what the status line already told it and nothing more.
66
- *
67
- * The SAME string is the response's reason phrase in {@link toResponse}. One table, because a
68
- * status line that disagrees with the body it introduces helps nobody.
69
- */
70
- private readonly genericMessages;
71
- /**
72
- * Build the wire BODY for `error`, and LOG the operator-facing detail that is being withheld from
73
- * it. Both halves happen here on purpose: the log line is the only remaining place the real
74
- * message exists, so it must never be optional or skippable.
75
- *
76
- * PRIVATE, deliberately. {@link toResponse} is the one public spelling of "webpieces' default
77
- * answer" — a public body-only producer alongside it would be a second spelling of the same
78
- * decision, and the caller who picked it would then hand-wrap a status and headers around the
79
- * body, re-implementing exactly what `toResponse` exists to hand them.
80
- */
81
- private toWire;
82
- /**
83
- * Build the WHOLE default response for a thrown value — status code, reason phrase, headers and
84
- * body. This is webpieces' own answer expressed in the SAME {@link HttpResponseDto} an app's
85
- * `ErrorTranslators.toWire` returns, which is what makes the default delegable: an app wraps it
86
- * and edits the parts it cares about.
87
- *
88
- * Takes `unknown`, not `HttpError`, because the non-HttpError case is part of the default and an
89
- * app delegating here must get it too: an unexpected throw is a GENERIC 500 whose real message
90
- * goes to the log only.
91
- *
92
- * Note what is NOT here: the `Content-Type` and the transaction-id response header. Both are
93
- * INFRASTRUCTURE that `ExpressWrapper` writes for every response — success and error, default and
94
- * app-translated alike — so an app that overrides the error body never has to remember to
95
- * re-emit them (and, for the content type, can still override it by naming it in its own header
96
- * list).
97
- */
98
- toResponse(error: unknown): HttpResponseDto;
99
- /**
100
- * The generic text for a status, or a code-free fallback for an app's own custom status. PUBLIC
101
- * so an app can reuse the table rather than copy it — see the class doc.
102
- */
103
- genericMessage(code: number): string;
104
- /**
105
- * The full operator-facing string. `name` and `subType` are in here because `name` used to be
106
- * visible ONLY on the wire — removing it from the body without adding it to the log would lose it
107
- * entirely.
108
- */
109
- private operatorDetail;
110
- /**
111
- * Log at the level that matches who is at fault: `info` where the CALLER made a mistake (a 4xx is
112
- * the server behaving correctly), `error` where the server or a dependency is broken.
113
- */
114
- private logOperatorDetail;
115
- /**
116
- * The structured, caller-facing fields — the ones a client BRANCHES on rather than displays as
117
- * server prose. MUST match ClientErrorTranslator's built-in status mapping.
118
- */
119
- private addContractFields;
120
- }
@@ -1,214 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpErrorWireMapper = void 0;
4
- const core_util_1 = require("@webpieces/core-util");
5
- // The logging backend prepends this logger name to every line, so messages below carry NO
6
- // "[HttpErrorWireMapper]" literal of their own — that would print the name twice.
7
- const log = core_util_1.LogManager.getLogger('HttpErrorWireMapper');
8
- /**
9
- * Turns a thrown {@link HttpError} into the {@link ProtocolError} that goes on the wire — and, just
10
- * as importantly, decides what does NOT go on the wire.
11
- *
12
- * # The rule: only {@link UserError}'s `message` is caller-facing
13
- *
14
- * `Error.message` is an OPERATOR-facing field everywhere else in this framework. It is written for
15
- * whoever reads the logs, and it routinely quotes internal detail: a downstream service url, an HTTP
16
- * method and content-type, a body snippet, a table name, an internal id. `http-client-node` builds
17
- * exactly such a message when a downstream dependency answers a 4xx — `ResponseBodyReader`'s
18
- * foreign-body description names the url it called and embeds the html it got back — and that error
19
- * arrives here as an `InternalError`. Copying `error.message` onto the response body handed
20
- * every one of those strings to an external, possibly partner-facing consumer.
21
- *
22
- * {@link UserError} is the ONE type whose message was written for a human to read. That is what
23
- * it is FOR: it is deliberately a 266 (a 2xx code, so it is not lumped in with failures), it carries
24
- * an `errorCode` the caller branches on, and an app throws it on purpose to say something like
25
- * "Email already exists". Its message goes out verbatim.
26
- *
27
- * Every other subclass sends a GENERIC, status-appropriate message (see {@link genericMessage}); the
28
- * real message goes to the LOG only. The behaviour used to be exactly backwards — an unexpected crash
29
- * was safely generic while a DELIBERATE `InternalError` shipped its full message outward.
30
- *
31
- * # What still goes out, and why
32
- *
33
- * - `errorCode` ({@link UserError}) and `waitSeconds` ({@link VendorError}) are structured
34
- * CONTRACT data the client is meant to branch on, not prose. They carry no internal detail.
35
- * - `field` and `guiAlertMessage` ({@link BadRequestError}) stay. `guiMessage` exists precisely
36
- * to be the human-safe half of a bad request — its existence is the admission that `message` is the
37
- * operator-facing half — and a form field name is not internal detail. The `message` itself is
38
- * genericised like every other non-user error.
39
- * - `subType` stays. It is NOT derived from a class name: it is an explicit constructor argument an
40
- * app passes on purpose (`WRONG_LOGIN`, `NOT_APPROVED`, `EMAIL_NOT_CONFIRMED`, … from
41
- * `core-util/src/http/errors.ts`), which makes it structured contract data of the same kind as
42
- * `errorCode`. `ClientErrorTranslator` reads it back when reconstructing `UnauthorizedError`
43
- * and the generic `HttpError`, so dropping it would break that reconstruction for the one case —
44
- * login failure reasons — where the caller genuinely has to branch on WHY.
45
- * - `name` is GONE from this ladder. Nothing in `ClientErrorTranslator` ever read it, so it is not
46
- * contract data. For a built-in it was a constant string 1:1 with the status code (`'BadRequest'`,
47
- * `'InternalServerError'`), i.e. it told the caller nothing the status had not already told it —
48
- * and for any SUBCLASS reaching this ladder it was literally an internal class name
49
- * (`'EndpointNotFoundError'`, or whatever an app happened to name its type). That is a free read of
50
- * the server's internals for zero caller benefit, so it is not sent. It is logged instead.
51
- *
52
- * An app that WANTS a different wire shape has an explicit opt-out on both sides:
53
- * `ClientRegistry.setErrorTranslators()`. `ExpressWrapper.handleError` consults
54
- * `tryTranslateToWire()` BEFORE reaching this class, and whatever that returns is sent verbatim —
55
- * that is the app's own deliberate choice about what it publishes.
56
- *
57
- * # This class IS the webpieces default, and it is DELEGABLE
58
- *
59
- * {@link toResponse} produces the same {@link HttpResponseDto} an app's `ErrorTranslators.toWire`
60
- * produces, so an app that wants "webpieces' answer, plus one header" or "webpieces' answer for
61
- * everything except MY type" WRAPS this instead of reimplementing it. That is not hypothetical:
62
- * a consumer's envelope class carried a status-to-message table with the comment "copied verbatim
63
- * from HttpErrorWireMapper's own table". Copying framework internals is the symptom of a missing
64
- * export, so the class and {@link genericMessage} are both public and both exported from this
65
- * package's barrel.
66
- */
67
- class HttpErrorWireMapper {
68
- /**
69
- * status code → the generic, caller-safe text sent in its place. These are the standard HTTP
70
- * reason phrases (plus 266 and 598, webpieces' own user/vendor codes), so a caller reading the
71
- * body learns exactly what the status line already told it and nothing more.
72
- *
73
- * The SAME string is the response's reason phrase in {@link toResponse}. One table, because a
74
- * status line that disagrees with the body it introduces helps nobody.
75
- */
76
- genericMessages = new Map([
77
- [266, 'User Error'],
78
- [400, 'Bad Request'],
79
- [401, 'Unauthorized'],
80
- [403, 'Forbidden'],
81
- [404, 'Not Found'],
82
- [408, 'Request Timeout'],
83
- [429, 'Too Many Requests'],
84
- [500, 'Internal Server Error'],
85
- [502, 'Bad Gateway'],
86
- [503, 'Service Unavailable'],
87
- [504, 'Gateway Timeout'],
88
- [598, 'Vendor Error'],
89
- ]);
90
- /**
91
- * Build the wire BODY for `error`, and LOG the operator-facing detail that is being withheld from
92
- * it. Both halves happen here on purpose: the log line is the only remaining place the real
93
- * message exists, so it must never be optional or skippable.
94
- *
95
- * PRIVATE, deliberately. {@link toResponse} is the one public spelling of "webpieces' default
96
- * answer" — a public body-only producer alongside it would be a second spelling of the same
97
- * decision, and the caller who picked it would then hand-wrap a status and headers around the
98
- * body, re-implementing exactly what `toResponse` exists to hand them.
99
- */
100
- toWire(error) {
101
- const protocolError = new core_util_1.ProtocolError();
102
- // The ONE type whose message was written for a human to read — see the class doc.
103
- if (error instanceof core_util_1.UserError) {
104
- log.info(`User Error: ${this.operatorDetail(error)}`);
105
- protocolError.message = error.message;
106
- protocolError.subType = error.subType;
107
- protocolError.errorCode = error.errorCode;
108
- return protocolError;
109
- }
110
- protocolError.message = this.genericMessage(core_util_1.HttpErrorStatus.code(error));
111
- protocolError.subType = error.subType;
112
- this.logOperatorDetail(error);
113
- this.addContractFields(error, protocolError);
114
- return protocolError;
115
- }
116
- /**
117
- * Build the WHOLE default response for a thrown value — status code, reason phrase, headers and
118
- * body. This is webpieces' own answer expressed in the SAME {@link HttpResponseDto} an app's
119
- * `ErrorTranslators.toWire` returns, which is what makes the default delegable: an app wraps it
120
- * and edits the parts it cares about.
121
- *
122
- * Takes `unknown`, not `HttpError`, because the non-HttpError case is part of the default and an
123
- * app delegating here must get it too: an unexpected throw is a GENERIC 500 whose real message
124
- * goes to the log only.
125
- *
126
- * Note what is NOT here: the `Content-Type` and the transaction-id response header. Both are
127
- * INFRASTRUCTURE that `ExpressWrapper` writes for every response — success and error, default and
128
- * app-translated alike — so an app that overrides the error body never has to remember to
129
- * re-emit them (and, for the content type, can still override it by naming it in its own header
130
- * list).
131
- */
132
- // webpieces-disable no-any-unknown -- a thrown value is genuinely unknown until narrowed below
133
- toResponse(error) {
134
- if (error instanceof core_util_1.ApiError) {
135
- return new core_util_1.HttpResponseDto(new core_util_1.HttpResponseStatus(core_util_1.HttpErrorStatus.code(error), this.genericMessage(core_util_1.HttpErrorStatus.code(error))), [], this.toWire(error));
136
- }
137
- // Already generic before this class existed, and deliberately so: an unexpected crash must
138
- // leak nothing. The real error goes to the log.
139
- log.error('Unexpected error:', (0, core_util_1.toError)(error));
140
- const protocolError = new core_util_1.ProtocolError();
141
- protocolError.message = 'Internal Server Error';
142
- return new core_util_1.HttpResponseDto(new core_util_1.HttpResponseStatus(500, 'Internal Server Error'), [], protocolError);
143
- }
144
- /**
145
- * The generic text for a status, or a code-free fallback for an app's own custom status. PUBLIC
146
- * so an app can reuse the table rather than copy it — see the class doc.
147
- */
148
- genericMessage(code) {
149
- return this.genericMessages.get(code) ?? 'Request Failed';
150
- }
151
- /**
152
- * The full operator-facing string. `name` and `subType` are in here because `name` used to be
153
- * visible ONLY on the wire — removing it from the body without adding it to the log would lose it
154
- * entirely.
155
- */
156
- operatorDetail(error) {
157
- const cause = error.cause instanceof Error ? ` cause=${error.cause.message}` : '';
158
- return `[name=${error.name} subType=${error.subType ?? 'none'}] ${error.message}${cause}`;
159
- }
160
- /**
161
- * Log at the level that matches who is at fault: `info` where the CALLER made a mistake (a 4xx is
162
- * the server behaving correctly), `error` where the server or a dependency is broken.
163
- */
164
- logOperatorDetail(error) {
165
- const detail = this.operatorDetail(error);
166
- if (error instanceof core_util_1.BadRequestError) {
167
- log.info(`Bad Request: ${detail}`);
168
- }
169
- else if (error instanceof core_util_1.NotFoundError) {
170
- log.info(`Not Found: ${detail}`);
171
- }
172
- else if (error instanceof core_util_1.RequestTimeoutError) {
173
- log.error(`Timeout Error: ${detail}`);
174
- }
175
- else if (error instanceof core_util_1.VendorError) {
176
- log.error(`Vendor Error: ${detail}`);
177
- }
178
- else if (error instanceof core_util_1.UnauthorizedError) {
179
- log.info(`Unauthorized: ${detail}`);
180
- }
181
- else if (error instanceof core_util_1.ForbiddenError) {
182
- log.info(`Forbidden: ${detail}`);
183
- }
184
- else if (error instanceof core_util_1.InternalError) {
185
- log.error(`Internal Server Error: ${detail}`);
186
- }
187
- else if (error instanceof core_util_1.BadGatewayError) {
188
- log.error(`Bad Gateway: ${detail}`);
189
- }
190
- else if (error instanceof core_util_1.GatewayTimeoutError) {
191
- log.error(`Gateway Timeout: ${detail}`);
192
- }
193
- else {
194
- log.info(`Generic HttpError: ${detail}`);
195
- }
196
- }
197
- /**
198
- * The structured, caller-facing fields — the ones a client BRANCHES on rather than displays as
199
- * server prose. MUST match ClientErrorTranslator's built-in status mapping.
200
- */
201
- addContractFields(error, protocolError) {
202
- if (error instanceof core_util_1.BadRequestError) {
203
- protocolError.field = error.field;
204
- // The human-safe half of a bad request. `error.message` is the operator half and is NOT
205
- // sent — the generic 'Bad Request' went out above instead.
206
- protocolError.guiAlertMessage = error.guiMessage;
207
- }
208
- else if (error instanceof core_util_1.VendorError) {
209
- protocolError.waitSeconds = error.waitSeconds;
210
- }
211
- }
212
- }
213
- exports.HttpErrorWireMapper = HttpErrorWireMapper;
214
- //# sourceMappingURL=HttpErrorWireMapper.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"HttpErrorWireMapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/HttpErrorWireMapper.ts"],"names":[],"mappings":";;;AAAA,oDAkB8B;AAE9B,0FAA0F;AAC1F,kFAAkF;AAClF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,MAAa,mBAAmB;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OAGG;IACK,iBAAiB,CAAC,KAAe,EAAE,aAA4B;QACnE,IAAI,KAAK,YAAY,2BAAe,EAAE,CAAC;YACnC,aAAa,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;YAClC,wFAAwF;YACxF,2DAA2D;YAC3D,aAAa,CAAC,eAAe,GAAG,KAAK,CAAC,UAAU,CAAC;QACrD,CAAC;aAAM,IAAI,KAAK,YAAY,uBAAW,EAAE,CAAC;YACtC,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAClD,CAAC;IACL,CAAC;CACJ;AAxJD,kDAwJC","sourcesContent":["import {\n ProtocolError,\n ApiError,\n HttpErrorStatus,\n BadRequestError,\n VendorError,\n UserError,\n NotFoundError,\n RequestTimeoutError,\n UnauthorizedError,\n ForbiddenError,\n InternalError,\n BadGatewayError,\n GatewayTimeoutError,\n HttpResponseDto,\n HttpResponseStatus,\n LogManager,\n toError,\n} from '@webpieces/core-util';\n\n// The logging backend prepends this logger name to every line, so messages below carry NO\n// \"[HttpErrorWireMapper]\" literal of their own — that would print the name twice.\nconst log = LogManager.getLogger('HttpErrorWireMapper');\n\n/**\n * Turns a thrown {@link HttpError} into the {@link ProtocolError} that goes on the wire — and, just\n * as importantly, decides what does NOT go on the wire.\n *\n * # The rule: only {@link UserError}'s `message` is caller-facing\n *\n * `Error.message` is an OPERATOR-facing field everywhere else in this framework. It is written for\n * whoever reads the logs, and it routinely quotes internal detail: a downstream service url, an HTTP\n * method and content-type, a body snippet, a table name, an internal id. `http-client-node` builds\n * exactly such a message when a downstream dependency answers a 4xx — `ResponseBodyReader`'s\n * foreign-body description names the url it called and embeds the html it got back — and that error\n * arrives here as an `InternalError`. Copying `error.message` onto the response body handed\n * every one of those strings to an external, possibly partner-facing consumer.\n *\n * {@link UserError} is the ONE type whose message was written for a human to read. That is what\n * it is FOR: it is deliberately a 266 (a 2xx code, so it is not lumped in with failures), it carries\n * an `errorCode` the caller branches on, and an app throws it on purpose to say something like\n * \"Email already exists\". Its message goes out verbatim.\n *\n * Every other subclass sends a GENERIC, status-appropriate message (see {@link genericMessage}); the\n * real message goes to the LOG only. The behaviour used to be exactly backwards — an unexpected crash\n * was safely generic while a DELIBERATE `InternalError` shipped its full message outward.\n *\n * # What still goes out, and why\n *\n * - `errorCode` ({@link UserError}) and `waitSeconds` ({@link VendorError}) are structured\n * CONTRACT data the client is meant to branch on, not prose. They carry no internal detail.\n * - `field` and `guiAlertMessage` ({@link BadRequestError}) stay. `guiMessage` exists precisely\n * to be the human-safe half of a bad request — its existence is the admission that `message` is the\n * operator-facing half — and a form field name is not internal detail. The `message` itself is\n * genericised like every other non-user error.\n * - `subType` stays. It is NOT derived from a class name: it is an explicit constructor argument an\n * app passes on purpose (`WRONG_LOGIN`, `NOT_APPROVED`, `EMAIL_NOT_CONFIRMED`, … from\n * `core-util/src/http/errors.ts`), which makes it structured contract data of the same kind as\n * `errorCode`. `ClientErrorTranslator` reads it back when reconstructing `UnauthorizedError`\n * and the generic `HttpError`, so dropping it would break that reconstruction for the one case —\n * login failure reasons — where the caller genuinely has to branch on WHY.\n * - `name` is GONE from this ladder. Nothing in `ClientErrorTranslator` ever read it, so it is not\n * contract data. For a built-in it was a constant string 1:1 with the status code (`'BadRequest'`,\n * `'InternalServerError'`), i.e. it told the caller nothing the status had not already told it —\n * and for any SUBCLASS reaching this ladder it was literally an internal class name\n * (`'EndpointNotFoundError'`, or whatever an app happened to name its type). That is a free read of\n * the server's internals for zero caller benefit, so it is not sent. It is logged instead.\n *\n * An app that WANTS a different wire shape has an explicit opt-out on both sides:\n * `ClientRegistry.setErrorTranslators()`. `ExpressWrapper.handleError` consults\n * `tryTranslateToWire()` BEFORE reaching this class, and whatever that returns is sent verbatim —\n * that is the app's own deliberate choice about what it publishes.\n *\n * # This class IS the webpieces default, and it is DELEGABLE\n *\n * {@link toResponse} produces the same {@link HttpResponseDto} an app's `ErrorTranslators.toWire`\n * produces, so an app that wants \"webpieces' answer, plus one header\" or \"webpieces' answer for\n * everything except MY type\" WRAPS this instead of reimplementing it. That is not hypothetical:\n * a consumer's envelope class carried a status-to-message table with the comment \"copied verbatim\n * from HttpErrorWireMapper's own table\". Copying framework internals is the symptom of a missing\n * export, so the class and {@link genericMessage} are both public and both exported from this\n * package's barrel.\n */\nexport class HttpErrorWireMapper {\n /**\n * status code → the generic, caller-safe text sent in its place. These are the standard HTTP\n * reason phrases (plus 266 and 598, webpieces' own user/vendor codes), so a caller reading the\n * body learns exactly what the status line already told it and nothing more.\n *\n * The SAME string is the response's reason phrase in {@link toResponse}. One table, because a\n * status line that disagrees with the body it introduces helps nobody.\n */\n private readonly genericMessages: Map<number, string> = new Map<number, string>([\n [266, 'User Error'],\n [400, 'Bad Request'],\n [401, 'Unauthorized'],\n [403, 'Forbidden'],\n [404, 'Not Found'],\n [408, 'Request Timeout'],\n [429, 'Too Many Requests'],\n [500, 'Internal Server Error'],\n [502, 'Bad Gateway'],\n [503, 'Service Unavailable'],\n [504, 'Gateway Timeout'],\n [598, 'Vendor Error'],\n ]);\n\n /**\n * Build the wire BODY for `error`, and LOG the operator-facing detail that is being withheld from\n * it. Both halves happen here on purpose: the log line is the only remaining place the real\n * message exists, so it must never be optional or skippable.\n *\n * PRIVATE, deliberately. {@link toResponse} is the one public spelling of \"webpieces' default\n * answer\" — a public body-only producer alongside it would be a second spelling of the same\n * decision, and the caller who picked it would then hand-wrap a status and headers around the\n * body, re-implementing exactly what `toResponse` exists to hand them.\n */\n private toWire(error: ApiError): ProtocolError {\n const protocolError = new ProtocolError();\n\n // The ONE type whose message was written for a human to read — see the class doc.\n if (error instanceof UserError) {\n log.info(`User Error: ${this.operatorDetail(error)}`);\n protocolError.message = error.message;\n protocolError.subType = error.subType;\n protocolError.errorCode = error.errorCode;\n return protocolError;\n }\n\n protocolError.message = this.genericMessage(HttpErrorStatus.code(error));\n protocolError.subType = error.subType;\n this.logOperatorDetail(error);\n this.addContractFields(error, protocolError);\n return protocolError;\n }\n\n /**\n * Build the WHOLE default response for a thrown value — status code, reason phrase, headers and\n * body. This is webpieces' own answer expressed in the SAME {@link HttpResponseDto} an app's\n * `ErrorTranslators.toWire` returns, which is what makes the default delegable: an app wraps it\n * and edits the parts it cares about.\n *\n * Takes `unknown`, not `HttpError`, because the non-HttpError case is part of the default and an\n * app delegating here must get it too: an unexpected throw is a GENERIC 500 whose real message\n * goes to the log only.\n *\n * Note what is NOT here: the `Content-Type` and the transaction-id response header. Both are\n * INFRASTRUCTURE that `ExpressWrapper` writes for every response — success and error, default and\n * app-translated alike — so an app that overrides the error body never has to remember to\n * re-emit them (and, for the content type, can still override it by naming it in its own header\n * list).\n */\n // webpieces-disable no-any-unknown -- a thrown value is genuinely unknown until narrowed below\n public toResponse(error: unknown): HttpResponseDto {\n if (error instanceof ApiError) {\n return new HttpResponseDto(\n new HttpResponseStatus(HttpErrorStatus.code(error), this.genericMessage(HttpErrorStatus.code(error))),\n [],\n this.toWire(error),\n );\n }\n\n // Already generic before this class existed, and deliberately so: an unexpected crash must\n // leak nothing. The real error goes to the log.\n log.error('Unexpected error:', toError(error));\n const protocolError = new ProtocolError();\n protocolError.message = 'Internal Server Error';\n return new HttpResponseDto(\n new HttpResponseStatus(500, 'Internal Server Error'),\n [],\n protocolError,\n );\n }\n\n /**\n * The generic text for a status, or a code-free fallback for an app's own custom status. PUBLIC\n * so an app can reuse the table rather than copy it — see the class doc.\n */\n public genericMessage(code: number): string {\n return this.genericMessages.get(code) ?? 'Request Failed';\n }\n\n /**\n * The full operator-facing string. `name` and `subType` are in here because `name` used to be\n * visible ONLY on the wire — removing it from the body without adding it to the log would lose it\n * entirely.\n */\n private operatorDetail(error: ApiError): string {\n const cause = error.cause instanceof Error ? ` cause=${error.cause.message}` : '';\n return `[name=${error.name} subType=${error.subType ?? 'none'}] ${error.message}${cause}`;\n }\n\n /**\n * Log at the level that matches who is at fault: `info` where the CALLER made a mistake (a 4xx is\n * the server behaving correctly), `error` where the server or a dependency is broken.\n */\n private logOperatorDetail(error: ApiError): void {\n const detail = this.operatorDetail(error);\n if (error instanceof BadRequestError) {\n log.info(`Bad Request: ${detail}`);\n } else if (error instanceof NotFoundError) {\n log.info(`Not Found: ${detail}`);\n } else if (error instanceof RequestTimeoutError) {\n log.error(`Timeout Error: ${detail}`);\n } else if (error instanceof VendorError) {\n log.error(`Vendor Error: ${detail}`);\n } else if (error instanceof UnauthorizedError) {\n log.info(`Unauthorized: ${detail}`);\n } else if (error instanceof ForbiddenError) {\n log.info(`Forbidden: ${detail}`);\n } else if (error instanceof InternalError) {\n log.error(`Internal Server Error: ${detail}`);\n } else if (error instanceof BadGatewayError) {\n log.error(`Bad Gateway: ${detail}`);\n } else if (error instanceof GatewayTimeoutError) {\n log.error(`Gateway Timeout: ${detail}`);\n } else {\n log.info(`Generic HttpError: ${detail}`);\n }\n }\n\n /**\n * The structured, caller-facing fields — the ones a client BRANCHES on rather than displays as\n * server prose. MUST match ClientErrorTranslator's built-in status mapping.\n */\n private addContractFields(error: ApiError, protocolError: ProtocolError): void {\n if (error instanceof BadRequestError) {\n protocolError.field = error.field;\n // The human-safe half of a bad request. `error.message` is the operator half and is NOT\n // sent — the generic 'Bad Request' went out above instead.\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof VendorError) {\n protocolError.waitSeconds = error.waitSeconds;\n }\n }\n}\n"]}