@webpieces/http-server 0.4.749 → 0.4.751

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.749",
3
+ "version": "0.4.751",
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.749",
26
- "@webpieces/core-util": "0.4.749",
27
- "@webpieces/gcp-identity": "0.4.749",
28
- "@webpieces/http-routing": "0.4.749",
25
+ "@webpieces/core-context": "0.4.751",
26
+ "@webpieces/core-util": "0.4.751",
27
+ "@webpieces/gcp-identity": "0.4.751",
28
+ "@webpieces/http-routing": "0.4.751",
29
29
  "cors": "2.8.5",
30
30
  "express": "5.1.0",
31
31
  "inversify": "7.10.4"
@@ -50,7 +50,7 @@ export declare class ExpressWrapper {
50
50
  private maxBodyBytes;
51
51
  /**
52
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 HttpUserError's
53
+ * one instance per wrapper is fine, and the class doc there is where the "only UserError's
54
54
  * message goes on the wire" rule is stated.
55
55
  */
56
56
  private readonly errorWireMapper;
@@ -153,7 +153,7 @@ export declare class ExpressWrapper {
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
155
  * 2. else {@link HttpErrorWireMapper.toResponse}, the webpieces default, which maps every
156
- * `HttpError` subclass to its status and a CALLER-SAFE body (only `HttpUserError`'s message
156
+ * `HttpError` subclass to its status and a CALLER-SAFE body (only `UserError`'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
  *
@@ -52,7 +52,7 @@ class ExpressWrapper {
52
52
  maxBodyBytes;
53
53
  /**
54
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 HttpUserError's
55
+ * one instance per wrapper is fine, and the class doc there is where the "only UserError's
56
56
  * message goes on the wire" rule is stated.
57
57
  */
58
58
  errorWireMapper = new HttpErrorWireMapper_1.HttpErrorWireMapper();
@@ -201,7 +201,7 @@ class ExpressWrapper {
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.HttpBadRequestError('Request body is not valid JSON', undefined, undefined, error);
204
+ throw new core_util_1.BadRequestError('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.HttpBadRequestError(`Request body exceeds the ${this.maxBodyBytes} byte limit`));
289
+ reject(new core_util_1.BadRequestError(`Request body exceeds the ${this.maxBodyBytes} byte limit`));
290
290
  return;
291
291
  }
292
292
  chunks.push(chunk);
@@ -309,7 +309,7 @@ class ExpressWrapper {
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
311
  * 2. else {@link HttpErrorWireMapper.toResponse}, the webpieces default, which maps every
312
- * `HttpError` subclass to its status and a CALLER-SAFE body (only `HttpUserError`'s message
312
+ * `HttpError` subclass to its status and a CALLER-SAFE body (only `UserError`'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
  *
@@ -1 +1 @@
1
- {"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.ts"],"names":[],"mappings":";;;AACA,oDAO8B;AAC9B,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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;AAjWD,wCAiWC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ClientRegistry,\n HttpBadRequestError,\n HttpHeader,\n HttpResponseDto,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport { RequestContext, HttpRequest, RawRequest, RequestContextHeaders } 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 HttpUserError'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 @AuthWebhook 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\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 @AuthWebhook 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(this.absoluteUrl(req), bodyBytes, req.socket?.remoteAddress, parseError)\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 HttpBadRequestError('Request body is not valid JSON', undefined, undefined, error);\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(new HttpBadRequestError(\n `Request body exceeds the ${this.maxBodyBytes} byte limit`,\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 `HttpUserError`'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 = error instanceof Error\n ? ClientRegistry.tryTranslateToWire(error)\n : 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,0DAAyG;AACzG,+DAA4D;AAE5D;;;;;;;;;;;;;;;;;GAiBG;AACU,QAAA,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAE/C;;;;;GAKG;AACH,MAAM,UAAU;IAGQ;IACA;IAEA;IALpB;IACI,+FAA+F;IAC/E,UAAmB,EACnB,GAA2B;IAC3C,gGAAgG;IAChF,U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AC;CACJ;AAjWD,wCAiWC","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 { RequestContext, HttpRequest, RawRequest, RequestContextHeaders } 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 @AuthWebhook 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\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 @AuthWebhook 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(this.absoluteUrl(req), bodyBytes, req.socket?.remoteAddress, parseError)\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('Request body is not valid JSON', undefined, undefined, error);\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(new BadRequestError(\n `Request body exceeds the ${this.maxBodyBytes} byte limit`,\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 = error instanceof Error\n ? ClientRegistry.tryTranslateToWire(error)\n : 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"]}
@@ -3,37 +3,37 @@ import { HttpResponseDto } from '@webpieces/core-util';
3
3
  * Turns a thrown {@link HttpError} into the {@link ProtocolError} that goes on the wire — and, just
4
4
  * as importantly, decides what does NOT go on the wire.
5
5
  *
6
- * # The rule: only {@link HttpUserError}'s `message` is caller-facing
6
+ * # The rule: only {@link UserError}'s `message` is caller-facing
7
7
  *
8
8
  * `Error.message` is an OPERATOR-facing field everywhere else in this framework. It is written for
9
9
  * whoever reads the logs, and it routinely quotes internal detail: a downstream service url, an HTTP
10
10
  * method and content-type, a body snippet, a table name, an internal id. `http-client-node` builds
11
11
  * exactly such a message when a downstream dependency answers a 4xx — `ResponseBodyReader`'s
12
12
  * foreign-body description names the url it called and embeds the html it got back — and that error
13
- * arrives here as an `HttpInternalServerError`. Copying `error.message` onto the response body handed
13
+ * arrives here as an `InternalError`. Copying `error.message` onto the response body handed
14
14
  * every one of those strings to an external, possibly partner-facing consumer.
15
15
  *
16
- * {@link HttpUserError} is the ONE type whose message was written for a human to read. That is what
16
+ * {@link UserError} is the ONE type whose message was written for a human to read. That is what
17
17
  * it is FOR: it is deliberately a 266 (a 2xx code, so it is not lumped in with failures), it carries
18
18
  * an `errorCode` the caller branches on, and an app throws it on purpose to say something like
19
19
  * "Email already exists". Its message goes out verbatim.
20
20
  *
21
21
  * Every other subclass sends a GENERIC, status-appropriate message (see {@link genericMessage}); the
22
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 `HttpInternalServerError` shipped its full message outward.
23
+ * was safely generic while a DELIBERATE `InternalError` shipped its full message outward.
24
24
  *
25
25
  * # What still goes out, and why
26
26
  *
27
- * - `errorCode` ({@link HttpUserError}) and `waitSeconds` ({@link HttpVendorError}) are structured
27
+ * - `errorCode` ({@link UserError}) and `waitSeconds` ({@link VendorError}) are structured
28
28
  * CONTRACT data the client is meant to branch on, not prose. They carry no internal detail.
29
- * - `field` and `guiAlertMessage` ({@link HttpBadRequestError}) stay. `guiMessage` exists precisely
29
+ * - `field` and `guiAlertMessage` ({@link BadRequestError}) stay. `guiMessage` exists precisely
30
30
  * to be the human-safe half of a bad request — its existence is the admission that `message` is the
31
31
  * operator-facing half — and a form field name is not internal detail. The `message` itself is
32
32
  * genericised like every other non-user error.
33
33
  * - `subType` stays. It is NOT derived from a class name: it is an explicit constructor argument an
34
34
  * app passes on purpose (`WRONG_LOGIN`, `NOT_APPROVED`, `EMAIL_NOT_CONFIRMED`, … from
35
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 `HttpUnauthorizedError`
36
+ * `errorCode`. `ClientErrorTranslator` reads it back when reconstructing `UnauthorizedError`
37
37
  * and the generic `HttpError`, so dropping it would break that reconstruction for the one case —
38
38
  * login failure reasons — where the caller genuinely has to branch on WHY.
39
39
  * - `name` is GONE from this ladder. Nothing in `ClientErrorTranslator` ever read it, so it is not
@@ -9,37 +9,37 @@ const log = core_util_1.LogManager.getLogger('HttpErrorWireMapper');
9
9
  * Turns a thrown {@link HttpError} into the {@link ProtocolError} that goes on the wire — and, just
10
10
  * as importantly, decides what does NOT go on the wire.
11
11
  *
12
- * # The rule: only {@link HttpUserError}'s `message` is caller-facing
12
+ * # The rule: only {@link UserError}'s `message` is caller-facing
13
13
  *
14
14
  * `Error.message` is an OPERATOR-facing field everywhere else in this framework. It is written for
15
15
  * whoever reads the logs, and it routinely quotes internal detail: a downstream service url, an HTTP
16
16
  * method and content-type, a body snippet, a table name, an internal id. `http-client-node` builds
17
17
  * exactly such a message when a downstream dependency answers a 4xx — `ResponseBodyReader`'s
18
18
  * foreign-body description names the url it called and embeds the html it got back — and that error
19
- * arrives here as an `HttpInternalServerError`. Copying `error.message` onto the response body handed
19
+ * arrives here as an `InternalError`. Copying `error.message` onto the response body handed
20
20
  * every one of those strings to an external, possibly partner-facing consumer.
21
21
  *
22
- * {@link HttpUserError} is the ONE type whose message was written for a human to read. That is what
22
+ * {@link UserError} is the ONE type whose message was written for a human to read. That is what
23
23
  * it is FOR: it is deliberately a 266 (a 2xx code, so it is not lumped in with failures), it carries
24
24
  * an `errorCode` the caller branches on, and an app throws it on purpose to say something like
25
25
  * "Email already exists". Its message goes out verbatim.
26
26
  *
27
27
  * Every other subclass sends a GENERIC, status-appropriate message (see {@link genericMessage}); the
28
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 `HttpInternalServerError` shipped its full message outward.
29
+ * was safely generic while a DELIBERATE `InternalError` shipped its full message outward.
30
30
  *
31
31
  * # What still goes out, and why
32
32
  *
33
- * - `errorCode` ({@link HttpUserError}) and `waitSeconds` ({@link HttpVendorError}) are structured
33
+ * - `errorCode` ({@link UserError}) and `waitSeconds` ({@link VendorError}) are structured
34
34
  * CONTRACT data the client is meant to branch on, not prose. They carry no internal detail.
35
- * - `field` and `guiAlertMessage` ({@link HttpBadRequestError}) stay. `guiMessage` exists precisely
35
+ * - `field` and `guiAlertMessage` ({@link BadRequestError}) stay. `guiMessage` exists precisely
36
36
  * to be the human-safe half of a bad request — its existence is the admission that `message` is the
37
37
  * operator-facing half — and a form field name is not internal detail. The `message` itself is
38
38
  * genericised like every other non-user error.
39
39
  * - `subType` stays. It is NOT derived from a class name: it is an explicit constructor argument an
40
40
  * app passes on purpose (`WRONG_LOGIN`, `NOT_APPROVED`, `EMAIL_NOT_CONFIRMED`, … from
41
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 `HttpUnauthorizedError`
42
+ * `errorCode`. `ClientErrorTranslator` reads it back when reconstructing `UnauthorizedError`
43
43
  * and the generic `HttpError`, so dropping it would break that reconstruction for the one case —
44
44
  * login failure reasons — where the caller genuinely has to branch on WHY.
45
45
  * - `name` is GONE from this ladder. Nothing in `ClientErrorTranslator` ever read it, so it is not
@@ -100,14 +100,14 @@ class HttpErrorWireMapper {
100
100
  toWire(error) {
101
101
  const protocolError = new core_util_1.ProtocolError();
102
102
  // The ONE type whose message was written for a human to read — see the class doc.
103
- if (error instanceof core_util_1.HttpUserError) {
103
+ if (error instanceof core_util_1.UserError) {
104
104
  log.info(`User Error: ${this.operatorDetail(error)}`);
105
105
  protocolError.message = error.message;
106
106
  protocolError.subType = error.subType;
107
107
  protocolError.errorCode = error.errorCode;
108
108
  return protocolError;
109
109
  }
110
- protocolError.message = this.genericMessage(error.code);
110
+ protocolError.message = this.genericMessage(core_util_1.HttpErrorStatus.code(error));
111
111
  protocolError.subType = error.subType;
112
112
  this.logOperatorDetail(error);
113
113
  this.addContractFields(error, protocolError);
@@ -131,8 +131,8 @@ class HttpErrorWireMapper {
131
131
  */
132
132
  // webpieces-disable no-any-unknown -- a thrown value is genuinely unknown until narrowed below
133
133
  toResponse(error) {
134
- if (error instanceof core_util_1.HttpError) {
135
- return new core_util_1.HttpResponseDto(new core_util_1.HttpResponseStatus(error.code, this.genericMessage(error.code)), [], this.toWire(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
136
  }
137
137
  // Already generic before this class existed, and deliberately so: an unexpected crash must
138
138
  // leak nothing. The real error goes to the log.
@@ -154,7 +154,7 @@ class HttpErrorWireMapper {
154
154
  * entirely.
155
155
  */
156
156
  operatorDetail(error) {
157
- const cause = error.httpCause === undefined ? '' : ` cause=${error.httpCause.message}`;
157
+ const cause = error.cause instanceof Error ? ` cause=${error.cause.message}` : '';
158
158
  return `[name=${error.name} subType=${error.subType ?? 'none'}] ${error.message}${cause}`;
159
159
  }
160
160
  /**
@@ -163,31 +163,31 @@ class HttpErrorWireMapper {
163
163
  */
164
164
  logOperatorDetail(error) {
165
165
  const detail = this.operatorDetail(error);
166
- if (error instanceof core_util_1.HttpBadRequestError) {
166
+ if (error instanceof core_util_1.BadRequestError) {
167
167
  log.info(`Bad Request: ${detail}`);
168
168
  }
169
- else if (error instanceof core_util_1.HttpNotFoundError) {
169
+ else if (error instanceof core_util_1.NotFoundError) {
170
170
  log.info(`Not Found: ${detail}`);
171
171
  }
172
- else if (error instanceof core_util_1.HttpTimeoutError) {
172
+ else if (error instanceof core_util_1.RequestTimeoutError) {
173
173
  log.error(`Timeout Error: ${detail}`);
174
174
  }
175
- else if (error instanceof core_util_1.HttpVendorError) {
175
+ else if (error instanceof core_util_1.VendorError) {
176
176
  log.error(`Vendor Error: ${detail}`);
177
177
  }
178
- else if (error instanceof core_util_1.HttpUnauthorizedError) {
178
+ else if (error instanceof core_util_1.UnauthorizedError) {
179
179
  log.info(`Unauthorized: ${detail}`);
180
180
  }
181
- else if (error instanceof core_util_1.HttpForbiddenError) {
181
+ else if (error instanceof core_util_1.ForbiddenError) {
182
182
  log.info(`Forbidden: ${detail}`);
183
183
  }
184
- else if (error instanceof core_util_1.HttpInternalServerError) {
184
+ else if (error instanceof core_util_1.InternalError) {
185
185
  log.error(`Internal Server Error: ${detail}`);
186
186
  }
187
- else if (error instanceof core_util_1.HttpBadGatewayError) {
187
+ else if (error instanceof core_util_1.BadGatewayError) {
188
188
  log.error(`Bad Gateway: ${detail}`);
189
189
  }
190
- else if (error instanceof core_util_1.HttpGatewayTimeoutError) {
190
+ else if (error instanceof core_util_1.GatewayTimeoutError) {
191
191
  log.error(`Gateway Timeout: ${detail}`);
192
192
  }
193
193
  else {
@@ -199,13 +199,13 @@ class HttpErrorWireMapper {
199
199
  * server prose. MUST match ClientErrorTranslator's built-in status mapping.
200
200
  */
201
201
  addContractFields(error, protocolError) {
202
- if (error instanceof core_util_1.HttpBadRequestError) {
202
+ if (error instanceof core_util_1.BadRequestError) {
203
203
  protocolError.field = error.field;
204
204
  // The human-safe half of a bad request. `error.message` is the operator half and is NOT
205
205
  // sent — the generic 'Bad Request' went out above instead.
206
206
  protocolError.guiAlertMessage = error.guiMessage;
207
207
  }
208
- else if (error instanceof core_util_1.HttpVendorError) {
208
+ else if (error instanceof core_util_1.VendorError) {
209
209
  protocolError.waitSeconds = error.waitSeconds;
210
210
  }
211
211
  }
@@ -1 +1 @@
1
- {"version":3,"file":"HttpErrorWireMapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/HttpErrorWireMapper.ts"],"names":[],"mappings":";;;AAAA,oDAiB8B;AAE9B,0FAA0F;AAC1F,kFAAkF;AAClF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,MAAa,mBAAmB;IAC5B;;;;;;;OAOG;IACc,eAAe,GAAwB,IAAI,GAAG,CAAiB;QAC5E,CAAC,GAAG,EAAE,YAAY,CAAC;QACnB,CAAC,GAAG,EAAE,aAAa,CAAC;QACpB,CAAC,GAAG,EAAE,cAAc,CAAC;QACrB,CA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AC;QACrD,CAAC;aAAM,IAAI,KAAK,YAAY,2BAAe,EAAE,CAAC;YAC1C,aAAa,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QAClD,CAAC;IACL,CAAC;CACJ;AAxJD,kDAwJC","sourcesContent":["import {\n ProtocolError,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\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 HttpUserError}'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 `HttpInternalServerError`. Copying `error.message` onto the response body handed\n * every one of those strings to an external, possibly partner-facing consumer.\n *\n * {@link HttpUserError} 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 `HttpInternalServerError` shipped its full message outward.\n *\n * # What still goes out, and why\n *\n * - `errorCode` ({@link HttpUserError}) and `waitSeconds` ({@link HttpVendorError}) are structured\n * CONTRACT data the client is meant to branch on, not prose. They carry no internal detail.\n * - `field` and `guiAlertMessage` ({@link HttpBadRequestError}) 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 `HttpUnauthorizedError`\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: HttpError): 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 HttpUserError) {\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(error.code);\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 HttpError) {\n return new HttpResponseDto(\n new HttpResponseStatus(error.code, this.genericMessage(error.code)),\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: HttpError): string {\n const cause = error.httpCause === undefined ? '' : ` cause=${error.httpCause.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: HttpError): void {\n const detail = this.operatorDetail(error);\n if (error instanceof HttpBadRequestError) {\n log.info(`Bad Request: ${detail}`);\n } else if (error instanceof HttpNotFoundError) {\n log.info(`Not Found: ${detail}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`Timeout Error: ${detail}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`Vendor Error: ${detail}`);\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`Unauthorized: ${detail}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`Forbidden: ${detail}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`Internal Server Error: ${detail}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`Bad Gateway: ${detail}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\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: HttpError, protocolError: ProtocolError): void {\n if (error instanceof HttpBadRequestError) {\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 HttpVendorError) {\n protocolError.waitSeconds = error.waitSeconds;\n }\n }\n}\n"]}
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;IAC5B;;;;;;;OAOG;IACc,eAAe,GAAwB,IAAI,GAAG,CAAiB;QAC5E,CAAC,GAAG,EAAE,YAAY,CAAC;QACnB,CAAC,GAAG,EAAE,aAAa,CAAC;QACpB,CAAC,GAAG,EAAE,cAAc,CAAC;QACrB,CAAC,GAAG,EAAE,WAAW,CAAC;QAClB,CAAC,GAAG,EAAE,WAAW,CAAC;QAClB,C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AI,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"]}