@webpieces/http-server 0.4.774 → 0.4.775

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,26 @@ Part of the [WebPieces TypeScript](https://github.com/deanhiller/webpieces-ts) f
18
18
  npm install @webpieces/http-server
19
19
  ```
20
20
 
21
+ ## Request bodies on hosts that parse first
22
+
23
+ webpieces reads each request body itself, straight off the request stream (`StreamBodyReader`, the
24
+ default). Some hosts read that stream before your app runs. Cloud Functions gen2 and Firebase are two
25
+ of them: they keep the original bytes on `req.rawBody`. Reading an already-consumed stream would wait
26
+ forever, so the default reader fails the request immediately with a message naming the fix. On such
27
+ hosts, opt in before binding the routes:
28
+
29
+ ```typescript
30
+ const router = new WebpiecesExpressRouter(apiFactory);
31
+ router.setBodyReader(new PreConsumedBodyReader());
32
+ router.bindExpress(app);
33
+ ```
34
+
35
+ `PreConsumedBodyReader` uses `req.rawBody` (the exact bytes sent, so `{ rawBody: true }` webhook
36
+ signatures still verify). If the stream was not consumed, it reads the stream as usual. If the stream
37
+ was consumed and there is no `req.rawBody`, it fails fast. It never re-serializes `req.body`. If you
38
+ mount your own body parser ahead of webpieces, either mount webpieces first or keep the bytes with
39
+ `express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })`.
40
+
21
41
  ## Documentation
22
42
 
23
43
  See the main [WebPieces README](https://github.com/deanhiller/webpieces-ts#readme) for complete documentation and examples.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-server",
3
- "version": "0.4.774",
3
+ "version": "0.4.775",
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.774",
26
- "@webpieces/core-util": "0.4.774",
27
- "@webpieces/gcp-identity": "0.4.774",
28
- "@webpieces/http-routing": "0.4.774",
25
+ "@webpieces/core-context": "0.4.775",
26
+ "@webpieces/core-util": "0.4.775",
27
+ "@webpieces/gcp-identity": "0.4.775",
28
+ "@webpieces/http-routing": "0.4.775",
29
29
  "cors": "2.8.5",
30
30
  "express": "5.1.0",
31
31
  "inversify": "7.10.4"
@@ -1,6 +1,7 @@
1
1
  import { Request, Response, NextFunction } from 'express';
2
2
  import { RouteMetadata } from '@webpieces/core-util';
3
3
  import { RequestContextHeaders } from '@webpieces/core-context';
4
+ import { RequestBodyReader } from './body/RequestBodyReader';
4
5
  /**
5
6
  * The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body
6
7
  * crosses it — the bytes already read are dropped, nothing further is buffered.
@@ -51,6 +52,12 @@ export declare class ExpressWrapper {
51
52
  private maxBodyBytes;
52
53
  /** Exact shared contract route; omitted only by focused legacy wrapper unit tests. */
53
54
  private readonly routeMeta?;
55
+ /**
56
+ * Where the body bytes come from. The default reads the request stream; a host that parses
57
+ * the body before webpieces runs (Cloud Functions gen2) needs `PreConsumedBodyReader`,
58
+ * chosen via `WebpiecesExpressRouter.setBodyReader`. See {@link RequestBodyReader}.
59
+ */
60
+ private readonly bodyReader;
54
61
  /**
55
62
  * Decides what an outside caller is allowed to see of a thrown {@link API error}. Stateless —
56
63
  * one instance per wrapper is fine, and the class doc there is where the "only ApiEndUserError's
@@ -85,7 +92,13 @@ export declare class ExpressWrapper {
85
92
  */
86
93
  maxBodyBytes?: number,
87
94
  /** Exact shared contract route; omitted only by focused legacy wrapper unit tests. */
88
- routeMeta?: RouteMetadata | undefined);
95
+ routeMeta?: RouteMetadata | undefined,
96
+ /**
97
+ * Where the body bytes come from. The default reads the request stream; a host that parses
98
+ * the body before webpieces runs (Cloud Functions gen2) needs `PreConsumedBodyReader`,
99
+ * chosen via `WebpiecesExpressRouter.setBodyReader`. See {@link RequestBodyReader}.
100
+ */
101
+ bodyReader?: RequestBodyReader);
89
102
  execute(req: Request, res: Response, next: NextFunction): Promise<void>;
90
103
  executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void>;
91
104
  executeImpl(req: Request, res: Response, next: NextFunction): Promise<void>;
@@ -141,19 +154,6 @@ export declare class ExpressWrapper {
141
154
  private absoluteUrl;
142
155
  private firstForwarded;
143
156
  private readExpressHeaders;
144
- /**
145
- * Read the raw request body as BYTES (we parse manually rather than mounting express.json()).
146
- *
147
- * Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that
148
- * straddles a chunk boundary into two replacement characters, so the body a webhook hook verified
149
- * would not be the body the vendor signed.
150
- *
151
- * REFUSES a body over {@link maxBodyBytes} the moment it crosses the line — the chunks read so far
152
- * are dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers
153
- * 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a
154
- * caller whose request we are refusing to finish reading, and that ordering is the point.
155
- */
156
- private readRequestBody;
157
157
  /**
158
158
  * Turn a thrown value into the response the caller sees — the SERVER half of webpieces' symmetric
159
159
  * error handling (the CLIENT half is `ClientErrorTranslator.translateError`, and the two speak the
@@ -4,6 +4,7 @@ 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
6
  const ApiErrorHttpMapper_1 = require("./ApiErrorHttpMapper");
7
+ const StreamBodyReader_1 = require("./body/StreamBodyReader");
7
8
  /**
8
9
  * The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body
9
10
  * crosses it — the bytes already read are dropped, nothing further is buffered.
@@ -51,6 +52,7 @@ class ExpressWrapper {
51
52
  rawBody;
52
53
  maxBodyBytes;
53
54
  routeMeta;
55
+ bodyReader;
54
56
  /**
55
57
  * Decides what an outside caller is allowed to see of a thrown {@link API error}. Stateless —
56
58
  * one instance per wrapper is fine, and the class doc there is where the "only ApiEndUserError's
@@ -87,7 +89,13 @@ class ExpressWrapper {
87
89
  */
88
90
  maxBodyBytes = exports.MAX_BODY_BYTES,
89
91
  /** Exact shared contract route; omitted only by focused legacy wrapper unit tests. */
90
- routeMeta) {
92
+ routeMeta,
93
+ /**
94
+ * Where the body bytes come from. The default reads the request stream; a host that parses
95
+ * the body before webpieces runs (Cloud Functions gen2) needs `PreConsumedBodyReader`,
96
+ * chosen via `WebpiecesExpressRouter.setBodyReader`. See {@link RequestBodyReader}.
97
+ */
98
+ bodyReader = new StreamBodyReader_1.StreamBodyReader()) {
91
99
  this.clientMethod = clientMethod;
92
100
  this.path = path;
93
101
  this.headers = headers;
@@ -95,6 +103,7 @@ class ExpressWrapper {
95
103
  this.rawBody = rawBody;
96
104
  this.maxBodyBytes = maxBodyBytes;
97
105
  this.routeMeta = routeMeta;
106
+ this.bodyReader = bodyReader;
98
107
  }
99
108
  async execute(req, res, next) {
100
109
  // MOVED: Wrap entire request in RequestContext.run()
@@ -183,7 +192,7 @@ class ExpressWrapper {
183
192
  // Read BYTES, not text. Concatenating per-chunk toString() corrupted any multi-byte
184
193
  // character that straddled a chunk boundary — invisible on small bodies, and fatal for a
185
194
  // signature computed over the bytes.
186
- const bodyBytes = await this.readRequestBody(req);
195
+ const bodyBytes = await this.bodyReader.read(req, this.maxBodyBytes);
187
196
  const bodyText = bodyBytes.toString('utf8');
188
197
  // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
189
198
  let requestDto;
@@ -318,44 +327,6 @@ class ExpressWrapper {
318
327
  }
319
328
  return headers;
320
329
  }
321
- /**
322
- * Read the raw request body as BYTES (we parse manually rather than mounting express.json()).
323
- *
324
- * Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that
325
- * straddles a chunk boundary into two replacement characters, so the body a webhook hook verified
326
- * would not be the body the vendor signed.
327
- *
328
- * REFUSES a body over {@link maxBodyBytes} the moment it crosses the line — the chunks read so far
329
- * are dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers
330
- * 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a
331
- * caller whose request we are refusing to finish reading, and that ordering is the point.
332
- */
333
- async readRequestBody(req) {
334
- return new Promise((resolve, reject) => {
335
- let chunks = [];
336
- let size = 0;
337
- // A socket emits Buffers; a stream someone put in string mode (or a test's Readable.from)
338
- // emits strings. Normalize to bytes ONCE, here, so everything downstream counts and
339
- // concatenates the same units.
340
- req.on('data', (data) => {
341
- const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');
342
- size += chunk.length;
343
- if (size > this.maxBodyBytes) {
344
- chunks = [];
345
- req.destroy();
346
- reject(new core_util_1.ApiBadRequestError(`Request body exceeds the ${this.maxBodyBytes} byte limit`));
347
- return;
348
- }
349
- chunks.push(chunk);
350
- });
351
- req.on('end', () => {
352
- resolve(Buffer.concat(chunks));
353
- });
354
- req.on('error', (err) => {
355
- reject(err);
356
- });
357
- });
358
- }
359
330
  /**
360
331
  * Turn a thrown value into the response the caller sees — the SERVER half of webpieces' symmetric
361
332
  * error handling (the CLIENT half is `ClientErrorTranslator.translateError`, and the two speak the
@@ -1 +1 @@
1
- {"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.ts"],"names":[],"mappings":";;;AACA,oDAW8B;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;IAC/E,UAAmB,EACnB,GAA2B;IAC3C,gGAAgG;IAChF,UAAkB;QAHlB,eAAU,GAAV,UAAU,CAAS;QACnB,QAAG,GAAH,GAAG,CAAwB;QAE3B,eAAU,GAAV,UAAU,CAAQ;IACnC,CAAC;CACP;AAED,MAAa,cAAc;IAUX;IACA;IAEA;IAMA;IAOA;IAWA;IAES;IAtCrB;;;;OAIG;IACc,eAAe,GAAG,IAAI,uCAAkB,EAAE,CAAC;IAE5D;IACI,+FAA+F;IACvF,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M,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,cAAc,CACvE,EAAE,KAAK,CAAC;QACT,IAAI,mBAAmB,IAAI,WAAW,KAAK,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YACjF,OAAO,OAAO,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACrF,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAC/C,CAAC;IAED;;;;;;;;;OASG;IACK,kBAAkB,CAAC,GAAa;QACpC,IAAI,CAAC,6BAAc,CAAC,QAAQ,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;AA7bD,wCA6bC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ClientRegistry,\n ApiBadRequestError,\n HttpHeader,\n HttpContractMapper,\n HttpResponseDto,\n HttpResponseStatus,\n RouteMetadata,\n ApiImplementationError,\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: (...args: 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 /** Exact shared contract route; omitted only by focused legacy wrapper unit tests. */\n private readonly routeMeta?: RouteMetadata,\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 args = this.routeMeta\n ? HttpContractMapper.fromWire(\n this.routeMeta.parameterBindings,\n this.routeMeta.bodyParameterIndex,\n parsed.requestDto,\n this.pathValues(req),\n this.queryValues(req),\n )\n : [parsed.requestDto];\n const result = await this.clientMethod(...args);\n\n // 5. The contract chooses body-only 200 JSON or caller-owned status/headers/body.\n if (this.routeMeta?.responseType === 'full') {\n if (!(result instanceof HttpResponseDto)) {\n throw new ApiImplementationError(\n `${this.routeMeta.apiName}.${this.routeMeta.methodName} declares responseType:'full' ` +\n `but returned ${result instanceof Object ? result.constructor.name : typeof result}; ` +\n `return HttpResponseDto.`,\n );\n }\n this.send(res, result);\n return;\n }\n if (result instanceof HttpResponseDto) {\n throw new ApiImplementationError(\n `${this.routeMeta?.apiName ?? 'API'}.${this.routeMeta?.methodName ?? 'method'} returned ` +\n `HttpResponseDto but its @Endpoint does not declare responseType:'full'.`,\n );\n }\n this.send(res, new HttpResponseDto(new HttpResponseStatus(200, 'OK'), [], result));\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 = this.formBody(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 /** Preserve repeated form keys as arrays while keeping the historical flat scalar shape. */\n private formBody(bodyText: string): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n new URLSearchParams(bodyText).forEach((value: string, key: string) => {\n const existing = result[key];\n if (existing === undefined) result[key] = value;\n else if (Array.isArray(existing)) existing.push(value);\n else result[key] = [existing, value];\n });\n return result;\n }\n\n /** Express has already URL-decoded route placeholders by the time a handler runs. */\n private pathValues(req: Request): Map<string, string | readonly string[]> {\n const values = new Map<string, string | readonly string[]>();\n const params = req.params ?? {};\n for (const name of Object.keys(params)) {\n values.set(name, params[name]);\n }\n return values;\n }\n\n /** Parse the original query string so repeated keys survive instead of being collapsed. */\n private queryValues(req: Request): Map<string, string | readonly string[]> {\n const values = new Map<string, string | readonly string[]>();\n const rawUrl = req.originalUrl ?? req.url ?? '';\n const query = rawUrl.includes('?') ? rawUrl.slice(rawUrl.indexOf('?') + 1) : '';\n new URLSearchParams(query).forEach((value: string, name: string) => {\n const existing = values.get(name);\n if (existing === undefined) values.set(name, value);\n else if (typeof existing === 'string') values.set(name, [existing, value]);\n else values.set(name, [...existing, value]);\n });\n return values;\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(\n req.method,\n req.path ?? this.path,\n this.readExpressHeaders(req),\n raw,\n );\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 && response.body !== undefined) {\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 const payload =\n response.body === undefined\n ? undefined\n : this.responsePayload(response, declaresContentType);\n res.status(response.status.code).send(payload);\n }\n\n /** JSON by default; explicit text content types write the caller's string verbatim. */\n private responsePayload(response: HttpResponseDto, declaresContentType: boolean): string {\n const contentType = response.headers.find(\n (header: HttpHeader) => header.name.toLowerCase() === 'content-type',\n )?.value;\n if (declaresContentType && contentType !== undefined && !/json/i.test(contentType)) {\n return typeof response.body === 'string' ? response.body : String(response.body);\n }\n return 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"]}
1
+ {"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.ts"],"names":[],"mappings":";;;AACA,oDAW8B;AAC9B,0DAKiC;AACjC,6DAA0D;AAE1D,8DAA2D;AAE3D;;;;;;;;;;;;;;;;;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,UAAkB;QAHlB,eAAU,GAAV,UAAU,CAAS;QACnB,QAAG,GAAH,GAAG,CAAwB;QAE3B,eAAU,GAAV,UAAU,CAAQ;IACnC,CAAC;CACP;AAED,MAAa,cAAc;IAUX;IACA;IAEA;IAMA;IAOA;IAWA;IAES;IAMA;IA5CrB;;;;OAIG;IACc,eAAe,GAAG,IAAI,uCAAkB,EAAE,CAAC;IAE5D;IACI,+FAA+F;IACvF,YAAsD,EACt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AI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACnD,CAAC;IAED,uFAAuF;IAC/E,eAAe,CAAC,QAAyB,EAAE,mBAA4B;QAC3E,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CACrC,CAAC,MAAkB,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,cAAc,CACvE,EAAE,KAAK,CAAC;QACT,IAAI,mBAAmB,IAAI,WAAW,KAAK,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YACjF,OAAO,OAAO,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACrF,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAC/C,CAAC;IAED;;;;;;;;;OASG;IACK,kBAAkB,CAAC,GAAa;QACpC,IAAI,CAAC,6BAAc,CAAC,QAAQ,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;AAxZD,wCAwZC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ClientRegistry,\n ApiBadRequestError,\n HttpHeader,\n HttpContractMapper,\n HttpResponseDto,\n HttpResponseStatus,\n RouteMetadata,\n ApiImplementationError,\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';\nimport { RequestBodyReader } from './body/RequestBodyReader';\nimport { StreamBodyReader } from './body/StreamBodyReader';\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: (...args: 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 /** Exact shared contract route; omitted only by focused legacy wrapper unit tests. */\n private readonly routeMeta?: RouteMetadata,\n /**\n * Where the body bytes come from. The default reads the request stream; a host that parses\n * the body before webpieces runs (Cloud Functions gen2) needs `PreConsumedBodyReader`,\n * chosen via `WebpiecesExpressRouter.setBodyReader`. See {@link RequestBodyReader}.\n */\n private readonly bodyReader: RequestBodyReader = new StreamBodyReader(),\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 args = this.routeMeta\n ? HttpContractMapper.fromWire(\n this.routeMeta.parameterBindings,\n this.routeMeta.bodyParameterIndex,\n parsed.requestDto,\n this.pathValues(req),\n this.queryValues(req),\n )\n : [parsed.requestDto];\n const result = await this.clientMethod(...args);\n\n // 5. The contract chooses body-only 200 JSON or caller-owned status/headers/body.\n if (this.routeMeta?.responseType === 'full') {\n if (!(result instanceof HttpResponseDto)) {\n throw new ApiImplementationError(\n `${this.routeMeta.apiName}.${this.routeMeta.methodName} declares responseType:'full' ` +\n `but returned ${result instanceof Object ? result.constructor.name : typeof result}; ` +\n `return HttpResponseDto.`,\n );\n }\n this.send(res, result);\n return;\n }\n if (result instanceof HttpResponseDto) {\n throw new ApiImplementationError(\n `${this.routeMeta?.apiName ?? 'API'}.${this.routeMeta?.methodName ?? 'method'} returned ` +\n `HttpResponseDto but its @Endpoint does not declare responseType:'full'.`,\n );\n }\n this.send(res, new HttpResponseDto(new HttpResponseStatus(200, 'OK'), [], result));\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.bodyReader.read(req, this.maxBodyBytes);\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 = this.formBody(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 /** Preserve repeated form keys as arrays while keeping the historical flat scalar shape. */\n private formBody(bodyText: string): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n new URLSearchParams(bodyText).forEach((value: string, key: string) => {\n const existing = result[key];\n if (existing === undefined) result[key] = value;\n else if (Array.isArray(existing)) existing.push(value);\n else result[key] = [existing, value];\n });\n return result;\n }\n\n /** Express has already URL-decoded route placeholders by the time a handler runs. */\n private pathValues(req: Request): Map<string, string | readonly string[]> {\n const values = new Map<string, string | readonly string[]>();\n const params = req.params ?? {};\n for (const name of Object.keys(params)) {\n values.set(name, params[name]);\n }\n return values;\n }\n\n /** Parse the original query string so repeated keys survive instead of being collapsed. */\n private queryValues(req: Request): Map<string, string | readonly string[]> {\n const values = new Map<string, string | readonly string[]>();\n const rawUrl = req.originalUrl ?? req.url ?? '';\n const query = rawUrl.includes('?') ? rawUrl.slice(rawUrl.indexOf('?') + 1) : '';\n new URLSearchParams(query).forEach((value: string, name: string) => {\n const existing = values.get(name);\n if (existing === undefined) values.set(name, value);\n else if (typeof existing === 'string') values.set(name, [existing, value]);\n else values.set(name, [...existing, value]);\n });\n return values;\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(\n req.method,\n req.path ?? this.path,\n this.readExpressHeaders(req),\n raw,\n );\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 * 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 && response.body !== undefined) {\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 const payload =\n response.body === undefined\n ? undefined\n : this.responsePayload(response, declaresContentType);\n res.status(response.status.code).send(payload);\n }\n\n /** JSON by default; explicit text content types write the caller's string verbatim. */\n private responsePayload(response: HttpResponseDto, declaresContentType: boolean): string {\n const contentType = response.headers.find(\n (header: HttpHeader) => header.name.toLowerCase() === 'content-type',\n )?.value;\n if (declaresContentType && contentType !== undefined && !/json/i.test(contentType)) {\n return typeof response.body === 'string' ? response.body : String(response.body);\n }\n return 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"]}
@@ -1,5 +1,6 @@
1
1
  import { Express } from 'express';
2
2
  import { ApiFactory, WebpiecesConfig } from '@webpieces/http-routing';
3
+ import { RequestBodyReader } from './body/RequestBodyReader';
3
4
  /** The value returned by express `app.listen(...)` (a node http.Server). */
4
5
  type HttpServer = ReturnType<Express['listen']>;
5
6
  /**
@@ -26,7 +27,24 @@ type HttpServer = ReturnType<Express['listen']>;
26
27
  export declare class WebpiecesExpressRouter {
27
28
  private readonly apiFactory;
28
29
  private readonly middleware;
30
+ /** Where every mounted route reads its body bytes from. See {@link setBodyReader}. */
31
+ private bodyReader;
32
+ /** Set by {@link bindExpress}; a reader chosen after that would reach no route. */
33
+ private bound;
29
34
  constructor(apiFactory: ApiFactory);
35
+ /**
36
+ * Choose how routes read the request body. Call it BEFORE {@link bindExpress}: each route captures
37
+ * the reader when it is mounted.
38
+ *
39
+ * The default ({@link StreamBodyReader}) reads the request stream, which is right whenever
40
+ * webpieces is mounted ahead of any body parser. A host that parses the body before the app runs
41
+ * (Cloud Functions gen2 / Firebase, which keep the verbatim bytes on `req.rawBody`) needs
42
+ * `router.setBodyReader(new PreConsumedBodyReader())`, or every POST fails fast (issue #937).
43
+ *
44
+ * @throws Error when called after {@link bindExpress}, because the already-mounted routes would
45
+ * silently keep the old reader.
46
+ */
47
+ setBodyReader(bodyReader: RequestBodyReader): void;
30
48
  /**
31
49
  * Mount the webpieces routes (each fully self-contained: own body parse, RequestContext,
32
50
  * express-tier + api-tier filter chain, error→JSON) onto the caller's express app.
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebpiecesExpressRouter = void 0;
4
4
  const core_util_1 = require("@webpieces/core-util");
5
5
  const WebpiecesMiddleware_1 = require("./WebpiecesMiddleware");
6
+ const StreamBodyReader_1 = require("./body/StreamBodyReader");
6
7
  const log = core_util_1.LogManager.getLogger('WebpiecesExpressRouter');
7
8
  /**
8
9
  * WebpiecesExpressRouter - the express layer that sits ON TOP of a node-only
@@ -28,9 +29,32 @@ const log = core_util_1.LogManager.getLogger('WebpiecesExpressRouter');
28
29
  class WebpiecesExpressRouter {
29
30
  apiFactory;
30
31
  middleware = new WebpiecesMiddleware_1.WebpiecesMiddleware();
32
+ /** Where every mounted route reads its body bytes from. See {@link setBodyReader}. */
33
+ bodyReader = new StreamBodyReader_1.StreamBodyReader();
34
+ /** Set by {@link bindExpress}; a reader chosen after that would reach no route. */
35
+ bound = false;
31
36
  constructor(apiFactory) {
32
37
  this.apiFactory = apiFactory;
33
38
  }
39
+ /**
40
+ * Choose how routes read the request body. Call it BEFORE {@link bindExpress}: each route captures
41
+ * the reader when it is mounted.
42
+ *
43
+ * The default ({@link StreamBodyReader}) reads the request stream, which is right whenever
44
+ * webpieces is mounted ahead of any body parser. A host that parses the body before the app runs
45
+ * (Cloud Functions gen2 / Firebase, which keep the verbatim bytes on `req.rawBody`) needs
46
+ * `router.setBodyReader(new PreConsumedBodyReader())`, or every POST fails fast (issue #937).
47
+ *
48
+ * @throws Error when called after {@link bindExpress}, because the already-mounted routes would
49
+ * silently keep the old reader.
50
+ */
51
+ setBodyReader(bodyReader) {
52
+ if (this.bound) {
53
+ throw new Error('setBodyReader() was called after bindExpress(); the mounted routes already captured ' +
54
+ 'their body reader. Call setBodyReader() before bindExpress(app).');
55
+ }
56
+ this.bodyReader = bodyReader;
57
+ }
34
58
  /**
35
59
  * Mount the webpieces routes (each fully self-contained: own body parse, RequestContext,
36
60
  * express-tier + api-tier filter chain, error→JSON) onto the caller's express app.
@@ -39,6 +63,7 @@ class WebpiecesExpressRouter {
39
63
  * routes must stay untouched. The caller owns app.listen() and any global middleware.
40
64
  */
41
65
  bindExpress(app) {
66
+ this.bound = true;
42
67
  let count = 0;
43
68
  for (const apiClient of this.apiFactory.apiClients()) {
44
69
  count += this.mountApiClient(app, apiClient);
@@ -120,7 +145,7 @@ class WebpiecesExpressRouter {
120
145
  // so is whether the verbatim bytes survive the parse for an @WpAuthWebhook hook to verify.
121
146
  const wrapper = route.streaming
122
147
  ? this.middleware.createStreamExpressWrapper(apiClient.client[route.methodName], route)
123
- : this.middleware.createExpressWrapper(apiClient.client[route.methodName], route);
148
+ : this.middleware.createExpressWrapper(apiClient.client[route.methodName], route, this.bodyReader);
124
149
  this.registerHandler(app, route.httpMethod, path, wrapper.execute.bind(wrapper));
125
150
  count++;
126
151
  }
@@ -1 +1 @@
1
- {"version":3,"file":"WebpiecesExpressRouter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesExpressRouter.ts"],"names":[],"mappings":";;;AAEA,oDAAiE;AACjE,+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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;gBACN,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,QAAQ;gBACT,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACjC,MAAM;YACV,KAAK,OAAO;gBACR,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAChC,MAAM;YACV;gBACI,GAAG,CAAC,IAAI,CAAC,wBAAwB,UAAU,EAAE,CAAC,CAAC;QACvD,CAAC;IACL,CAAC;CACJ;AAnJD,wDAmJC","sourcesContent":["import { Express } from 'express';\nimport { ApiFactory, ApiClient, WebpiecesConfig } from '@webpieces/http-routing';\nimport { LogManager, RouteMetadata } 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 let count = 0;\n for (const route of apiClient.routes) {\n const path = this.expressPath(route);\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 = route.streaming\n ? this.middleware.createStreamExpressWrapper(\n apiClient.client[route.methodName],\n route,\n )\n : this.middleware.createExpressWrapper(apiClient.client[route.methodName], route);\n this.registerHandler(app, route.httpMethod, path, wrapper.execute.bind(wrapper));\n count++;\n }\n return count;\n }\n\n /** Contract `{name}` placeholders -> Express 5 `:name` route syntax. */\n private expressPath(route: RouteMetadata): string {\n return route.path.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, ':$1');\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":";;;AAEA,oDAAiE;AACjE,+DAAiF;AAEjF,8DAA2D;AAE3D,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAK3D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,sBAAsB;IAOF;IANZ,UAAU,GAAG,IAAI,yCAAmB,EAAE,CAAC;IACxD,sFAAsF;IAC9E,UAAU,GAAsB,IAAI,mCAAgB,EAAE,CAAC;IAC/D,mFAAmF;IAC3E,KAAK,GAAG,KAAK,CAAC;IAEtB,YAA6B,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;IAAG,CAAC;IAEvD;;;;;;;;;;;OAWG;IACH,aAAa,CAAC,UAA6B;QACvC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CACX,sFAAsF;gBAClF,kEAAkE,CACzE,CAAC;QACN,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;IAED;;;;;;OAMG;IACH,WAAW,CAAC,GAAY;QACpB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,U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,UAAkB,EAClB,IAAY,EACZ,cAAmC;QAEnC,QAAQ,UAAU,CAAC,WAAW,EAAE,EAAE,CAAC;YAC/B,KAAK,KAAK;gBACN,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,MAAM;gBACP,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC/B,MAAM;YACV,KAAK,KAAK;gBACN,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,QAAQ;gBACT,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACjC,MAAM;YACV,KAAK,OAAO;gBACR,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAChC,MAAM;YACV;gBACI,GAAG,CAAC,IAAI,CAAC,wBAAwB,UAAU,EAAE,CAAC,CAAC;QACvD,CAAC;IACL,CAAC;CACJ;AAlLD,wDAkLC","sourcesContent":["import { Express } from 'express';\nimport { ApiFactory, ApiClient, WebpiecesConfig } from '@webpieces/http-routing';\nimport { LogManager, RouteMetadata } from '@webpieces/core-util';\nimport { WebpiecesMiddleware, ExpressRouteHandler } from './WebpiecesMiddleware';\nimport { RequestBodyReader } from './body/RequestBodyReader';\nimport { StreamBodyReader } from './body/StreamBodyReader';\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 /** Where every mounted route reads its body bytes from. See {@link setBodyReader}. */\n private bodyReader: RequestBodyReader = new StreamBodyReader();\n /** Set by {@link bindExpress}; a reader chosen after that would reach no route. */\n private bound = false;\n\n constructor(private readonly apiFactory: ApiFactory) {}\n\n /**\n * Choose how routes read the request body. Call it BEFORE {@link bindExpress}: each route captures\n * the reader when it is mounted.\n *\n * The default ({@link StreamBodyReader}) reads the request stream, which is right whenever\n * webpieces is mounted ahead of any body parser. A host that parses the body before the app runs\n * (Cloud Functions gen2 / Firebase, which keep the verbatim bytes on `req.rawBody`) needs\n * `router.setBodyReader(new PreConsumedBodyReader())`, or every POST fails fast (issue #937).\n *\n * @throws Error when called after {@link bindExpress}, because the already-mounted routes would\n * silently keep the old reader.\n */\n setBodyReader(bodyReader: RequestBodyReader): void {\n if (this.bound) {\n throw new Error(\n 'setBodyReader() was called after bindExpress(); the mounted routes already captured ' +\n 'their body reader. Call setBodyReader() before bindExpress(app).',\n );\n }\n this.bodyReader = bodyReader;\n }\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 this.bound = true;\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 let count = 0;\n for (const route of apiClient.routes) {\n const path = this.expressPath(route);\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 = route.streaming\n ? this.middleware.createStreamExpressWrapper(\n apiClient.client[route.methodName],\n route,\n )\n : this.middleware.createExpressWrapper(\n apiClient.client[route.methodName],\n route,\n this.bodyReader,\n );\n this.registerHandler(app, route.httpMethod, path, wrapper.execute.bind(wrapper));\n count++;\n }\n return count;\n }\n\n /** Contract `{name}` placeholders -> Express 5 `:name` route syntax. */\n private expressPath(route: RouteMetadata): string {\n return route.path.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, ':$1');\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"]}
@@ -3,6 +3,7 @@ import { WebpiecesConfig } from '@webpieces/http-routing';
3
3
  import { RouteMetadata } from '@webpieces/core-util';
4
4
  import { ExpressWrapper } from './ExpressWrapper';
5
5
  import { StreamExpressWrapper } from './StreamExpressWrapper';
6
+ import { RequestBodyReader } from './body/RequestBodyReader';
6
7
  /**
7
8
  * Express route handler function type. Lives in http-server (the express adapter),
8
9
  * NOT in the node-only http-routing package, so http-routing stays express-free.
@@ -116,8 +117,11 @@ export declare class WebpiecesMiddleware {
116
117
  * @param rawBody - True for an @Endpoint(..., { rawBody: true }) route: retain the verbatim
117
118
  * bytes + absolute url on the HttpRequest so an @WpAuthWebhook hook can verify a vendor
118
119
  * signature over them. Default false = the bytes are dropped once parsed.
120
+ * @param bodyReader - Where the body bytes come from (the router's choice, see
121
+ * `WebpiecesExpressRouter.setBodyReader`). Required so the router's choice can never be
122
+ * silently dropped on the way to the wrapper.
119
123
  * @returns ExpressWrapper instance
120
124
  */
121
- createExpressWrapper(clientMethod: (...args: unknown[]) => Promise<unknown>, route: RouteMetadata): ExpressWrapper;
125
+ createExpressWrapper(clientMethod: (...args: unknown[]) => Promise<unknown>, route: RouteMetadata, bodyReader: RequestBodyReader): ExpressWrapper;
122
126
  createStreamExpressWrapper(clientMethod: (...args: unknown[]) => Promise<unknown>, route: RouteMetadata): StreamExpressWrapper;
123
127
  }
@@ -197,12 +197,15 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
197
197
  * @param rawBody - True for an @Endpoint(..., { rawBody: true }) route: retain the verbatim
198
198
  * bytes + absolute url on the HttpRequest so an @WpAuthWebhook hook can verify a vendor
199
199
  * signature over them. Default false = the bytes are dropped once parsed.
200
+ * @param bodyReader - Where the body bytes come from (the router's choice, see
201
+ * `WebpiecesExpressRouter.setBodyReader`). Required so the router's choice can never be
202
+ * silently dropped on the way to the wrapper.
200
203
  * @returns ExpressWrapper instance
201
204
  */
202
205
  createExpressWrapper(
203
206
  // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
204
- clientMethod, route) {
205
- return new ExpressWrapper_1.ExpressWrapper(clientMethod, route.path, this.headers, route.formPost, route.rawBody, undefined, route);
207
+ clientMethod, route, bodyReader) {
208
+ return new ExpressWrapper_1.ExpressWrapper(clientMethod, route.path, this.headers, route.formPost, route.rawBody, undefined, route, bodyReader);
206
209
  }
207
210
  createStreamExpressWrapper(
208
211
  // webpieces-disable no-any-unknown -- stream DTOs are erased at the routing boundary
@@ -1 +1 @@
1
- {"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,0DAAqF;AACrF,oDAA8D;AAC9D,0DAAgE;AAChE,oDAAkD;AAClD,qDAAkD;AAClD,iEAA8D;AAE9D,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,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;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,YAAsD,EACtD,KAAoB;QAEpB,OAAO,IAAI,+BAAc,CACrB,YAAY,EACZ,KAAK,CAAC,IAAI,EACV,IAAI,CAAC,OAAO,EACZ,KAAK,CAAC,QAAQ,EACd,KAAK,CAAC,OAAO,EACb,SAAS,EACT,KAAK,CACR,CAAC;IACN,CAAC;IAED,0BAA0B;IACtB,qFAAqF;IACrF,YAAsD,EACtD,KAAoB;QAEpB,OAAO,IAAI,2CAAoB,CAAC,YAAY,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IACvE,CAAC;CACJ,CAAA;AArMY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;GACf,mBAAmB,CAqM/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport { RouteMetadata, toError } from '@webpieces/core-util';\nimport { RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { ExpressWrapper } from './ExpressWrapper';\nimport { StreamExpressWrapper } from './StreamExpressWrapper';\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: (...args: unknown[]) => Promise<unknown>,\n route: RouteMetadata,\n ): ExpressWrapper {\n return new ExpressWrapper(\n clientMethod,\n route.path,\n this.headers,\n route.formPost,\n route.rawBody,\n undefined,\n route,\n );\n }\n\n createStreamExpressWrapper(\n // webpieces-disable no-any-unknown -- stream DTOs are erased at the routing boundary\n clientMethod: (...args: unknown[]) => Promise<unknown>,\n route: RouteMetadata,\n ): StreamExpressWrapper {\n return new StreamExpressWrapper(clientMethod, route, this.headers);\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,oDAA8D;AAC9D,0DAAgE;AAChE,oDAAkD;AAClD,qDAAkD;AAClD,iEAA8D;AAG9D,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;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;;;OAiBG;IACH,oBAAoB;IAChB,+FAA+F;IAC/F,YAAsD,EACtD,KAAoB,EACpB,UAA6B;QAE7B,OAAO,IAAI,+BAAc,CACrB,YAAY,EACZ,KAAK,CAAC,IAAI,EACV,IAAI,CAAC,OAAO,EACZ,KAAK,CAAC,QAAQ,EACd,KAAK,CAAC,OAAO,EACb,SAAS,EACT,KAAK,EACL,UAAU,CACb,CAAC;IACN,CAAC;IAED,0BAA0B;IACtB,qFAAqF;IACrF,YAAsD,EACtD,KAAoB;QAEpB,OAAO,IAAI,2CAAoB,CAAC,YAAY,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IACvE,CAAC;CACJ,CAAA;AA1MY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;GACf,mBAAmB,CA0M/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport { RouteMetadata, toError } from '@webpieces/core-util';\nimport { RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { ExpressWrapper } from './ExpressWrapper';\nimport { StreamExpressWrapper } from './StreamExpressWrapper';\nimport { RequestBodyReader } from './body/RequestBodyReader';\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 * @param bodyReader - Where the body bytes come from (the router's choice, see\n * `WebpiecesExpressRouter.setBodyReader`). Required so the router's choice can never be\n * silently dropped on the way to the wrapper.\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n clientMethod: (...args: unknown[]) => Promise<unknown>,\n route: RouteMetadata,\n bodyReader: RequestBodyReader,\n ): ExpressWrapper {\n return new ExpressWrapper(\n clientMethod,\n route.path,\n this.headers,\n route.formPost,\n route.rawBody,\n undefined,\n route,\n bodyReader,\n );\n }\n\n createStreamExpressWrapper(\n // webpieces-disable no-any-unknown -- stream DTOs are erased at the routing boundary\n clientMethod: (...args: unknown[]) => Promise<unknown>,\n route: RouteMetadata,\n ): StreamExpressWrapper {\n return new StreamExpressWrapper(clientMethod, route, this.headers);\n }\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import { Request } from 'express';
2
+ import { RequestBodyReader } from './RequestBodyReader';
3
+ /**
4
+ * OPT-IN {@link RequestBodyReader} for hosts that parse the body BEFORE webpieces runs: Cloud
5
+ * Functions gen2 / Firebase (the Functions Framework), or an app that mounts
6
+ * `express.json({ verify })` ahead of webpieces. Enable it with
7
+ * `router.setBodyReader(new PreConsumedBodyReader())` before `bindExpress(app)`.
8
+ *
9
+ * Decision order:
10
+ * 1. `req.rawBody` is a `Buffer`: use it. These are the exact bytes the sender transmitted, so a
11
+ * `{ rawBody: true }` webhook route still verifies its signature. The size cap is still enforced.
12
+ * 2. the stream was NOT consumed: read it normally (same as {@link StreamBodyReader}).
13
+ * 3. otherwise: fail fast naming the cure. The host must expose `req.rawBody`.
14
+ *
15
+ * Deliberately NO `JSON.stringify(req.body)` fallback. Re-serialized bytes differ from what was sent
16
+ * (whitespace, key order, number formatting), which silently breaks webhook signature verification,
17
+ * and the host this exists for (#937) always sets `req.rawBody`.
18
+ *
19
+ * Opt-in rather than the default so every correctly mounted server keeps the plain stream read.
20
+ */
21
+ export declare class PreConsumedBodyReader implements RequestBodyReader {
22
+ private readonly streamReader;
23
+ read(req: Request, maxBodyBytes: number): Promise<Buffer>;
24
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PreConsumedBodyReader = void 0;
4
+ const core_util_1 = require("@webpieces/core-util");
5
+ const StreamBodyReader_1 = require("./StreamBodyReader");
6
+ /**
7
+ * OPT-IN {@link RequestBodyReader} for hosts that parse the body BEFORE webpieces runs: Cloud
8
+ * Functions gen2 / Firebase (the Functions Framework), or an app that mounts
9
+ * `express.json({ verify })` ahead of webpieces. Enable it with
10
+ * `router.setBodyReader(new PreConsumedBodyReader())` before `bindExpress(app)`.
11
+ *
12
+ * Decision order:
13
+ * 1. `req.rawBody` is a `Buffer`: use it. These are the exact bytes the sender transmitted, so a
14
+ * `{ rawBody: true }` webhook route still verifies its signature. The size cap is still enforced.
15
+ * 2. the stream was NOT consumed: read it normally (same as {@link StreamBodyReader}).
16
+ * 3. otherwise: fail fast naming the cure. The host must expose `req.rawBody`.
17
+ *
18
+ * Deliberately NO `JSON.stringify(req.body)` fallback. Re-serialized bytes differ from what was sent
19
+ * (whitespace, key order, number formatting), which silently breaks webhook signature verification,
20
+ * and the host this exists for (#937) always sets `req.rawBody`.
21
+ *
22
+ * Opt-in rather than the default so every correctly mounted server keeps the plain stream read.
23
+ */
24
+ class PreConsumedBodyReader {
25
+ streamReader = new StreamBodyReader_1.StreamBodyReader();
26
+ read(req, maxBodyBytes) {
27
+ // webpieces-disable no-any-unknown -- `rawBody` is set by the host, absent from the express types
28
+ const rawBody = req['rawBody'];
29
+ if (Buffer.isBuffer(rawBody)) {
30
+ if (rawBody.length > maxBodyBytes) {
31
+ return Promise.reject(new core_util_1.ApiBadRequestError(`Request body exceeds the ${maxBodyBytes} byte limit`));
32
+ }
33
+ return Promise.resolve(rawBody);
34
+ }
35
+ if (!this.streamReader.isConsumed(req)) {
36
+ return this.streamReader.read(req, maxBodyBytes);
37
+ }
38
+ return Promise.reject(new core_util_1.ApiImplementationError('PreConsumedBodyReader: the request body stream was already consumed and ' +
39
+ '`req.rawBody` is not a Buffer, so the verbatim body bytes are unavailable. ' +
40
+ 'Fix: have the host keep the bytes on `req.rawBody`, e.g. ' +
41
+ '`express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })`, ' +
42
+ 'or mount webpieces BEFORE the body parser.'));
43
+ }
44
+ }
45
+ exports.PreConsumedBodyReader = PreConsumedBodyReader;
46
+ //# sourceMappingURL=PreConsumedBodyReader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PreConsumedBodyReader.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/body/PreConsumedBodyReader.ts"],"names":[],"mappings":";;;AACA,oDAAkF;AAElF,yDAAsD;AAEtD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,qBAAqB;IACb,YAAY,GAAG,IAAI,mCAAgB,EAAE,CAAC;IAEvD,IAAI,CAAC,GAAY,EAAE,YAAoB;QACnC,kGAAkG;QAClG,MAAM,OAAO,GAAI,GAA0C,CAAC,SAAS,CAAC,CAAC;QACvE,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;YAC3B,IAAI,OAAO,CAAC,MAAM,GAAG,YAAY,EAAE,CAAC;gBAChC,OAAO,OAAO,CAAC,MAAM,CACjB,IAAI,8BAAkB,CAAC,4BAA4B,YAAY,aAAa,CAAC,CAChF,CAAC;YACN,CAAC;YACD,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACrC,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;QACrD,CAAC;QACD,OAAO,OAAO,CAAC,MAAM,CACjB,IAAI,kCAAsB,CACtB,0EAA0E;YACtE,6EAA6E;YAC7E,2DAA2D;YAC3D,0EAA0E;YAC1E,4CAA4C,CACnD,CACJ,CAAC;IACN,CAAC;CACJ;AA3BD,sDA2BC","sourcesContent":["import { Request } from 'express';\nimport { ApiBadRequestError, ApiImplementationError } from '@webpieces/core-util';\nimport { RequestBodyReader } from './RequestBodyReader';\nimport { StreamBodyReader } from './StreamBodyReader';\n\n/**\n * OPT-IN {@link RequestBodyReader} for hosts that parse the body BEFORE webpieces runs: Cloud\n * Functions gen2 / Firebase (the Functions Framework), or an app that mounts\n * `express.json({ verify })` ahead of webpieces. Enable it with\n * `router.setBodyReader(new PreConsumedBodyReader())` before `bindExpress(app)`.\n *\n * Decision order:\n * 1. `req.rawBody` is a `Buffer`: use it. These are the exact bytes the sender transmitted, so a\n * `{ rawBody: true }` webhook route still verifies its signature. The size cap is still enforced.\n * 2. the stream was NOT consumed: read it normally (same as {@link StreamBodyReader}).\n * 3. otherwise: fail fast naming the cure. The host must expose `req.rawBody`.\n *\n * Deliberately NO `JSON.stringify(req.body)` fallback. Re-serialized bytes differ from what was sent\n * (whitespace, key order, number formatting), which silently breaks webhook signature verification,\n * and the host this exists for (#937) always sets `req.rawBody`.\n *\n * Opt-in rather than the default so every correctly mounted server keeps the plain stream read.\n */\nexport class PreConsumedBodyReader implements RequestBodyReader {\n private readonly streamReader = new StreamBodyReader();\n\n read(req: Request, maxBodyBytes: number): Promise<Buffer> {\n // webpieces-disable no-any-unknown -- `rawBody` is set by the host, absent from the express types\n const rawBody = (req as unknown as Record<string, unknown>)['rawBody'];\n if (Buffer.isBuffer(rawBody)) {\n if (rawBody.length > maxBodyBytes) {\n return Promise.reject(\n new ApiBadRequestError(`Request body exceeds the ${maxBodyBytes} byte limit`),\n );\n }\n return Promise.resolve(rawBody);\n }\n if (!this.streamReader.isConsumed(req)) {\n return this.streamReader.read(req, maxBodyBytes);\n }\n return Promise.reject(\n new ApiImplementationError(\n 'PreConsumedBodyReader: the request body stream was already consumed and ' +\n '`req.rawBody` is not a Buffer, so the verbatim body bytes are unavailable. ' +\n 'Fix: have the host keep the bytes on `req.rawBody`, e.g. ' +\n '`express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })`, ' +\n 'or mount webpieces BEFORE the body parser.',\n ),\n );\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import { Request } from 'express';
2
+ /**
3
+ * How a webpieces route obtains the inbound body BYTES from express.
4
+ *
5
+ * webpieces parses bodies itself (it never mounts `express.json()`), so by default it reads the
6
+ * request stream. That only works when nothing upstream read the stream first. Some hosts do:
7
+ * Cloud Functions gen2 / Firebase run a body parser BEFORE the app sees the request and leave the
8
+ * verbatim bytes on `req.rawBody`. Reading the drained stream there waits for an `end` event that
9
+ * already fired, so the request hangs until the platform timeout (issue #937).
10
+ *
11
+ * The reader is chosen ONCE per router via `WebpiecesExpressRouter.setBodyReader(...)`:
12
+ * - {@link StreamBodyReader}: the default. Reads the stream, fails fast if it was already consumed.
13
+ * - {@link PreConsumedBodyReader}: opt-in for hosts that parse first. Uses `req.rawBody`.
14
+ *
15
+ * An interface (not a class) because it is behaviour: an implementation decides WHERE the bytes come
16
+ * from. Whatever it returns must be the bytes the sender transmitted, because a `{ rawBody: true }`
17
+ * webhook route verifies a vendor signature over exactly this buffer.
18
+ */
19
+ export interface RequestBodyReader {
20
+ /**
21
+ * @param req - the express request of a POST/PUT/PATCH route.
22
+ * @param maxBodyBytes - the inbound cap. An implementation MUST refuse a larger body with an
23
+ * `ApiBadRequestError` rather than buffer it.
24
+ * @returns the verbatim body bytes (empty for an empty body).
25
+ */
26
+ read(req: Request, maxBodyBytes: number): Promise<Buffer>;
27
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=RequestBodyReader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RequestBodyReader.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/body/RequestBodyReader.ts"],"names":[],"mappings":"","sourcesContent":["import { Request } from 'express';\n\n/**\n * How a webpieces route obtains the inbound body BYTES from express.\n *\n * webpieces parses bodies itself (it never mounts `express.json()`), so by default it reads the\n * request stream. That only works when nothing upstream read the stream first. Some hosts do:\n * Cloud Functions gen2 / Firebase run a body parser BEFORE the app sees the request and leave the\n * verbatim bytes on `req.rawBody`. Reading the drained stream there waits for an `end` event that\n * already fired, so the request hangs until the platform timeout (issue #937).\n *\n * The reader is chosen ONCE per router via `WebpiecesExpressRouter.setBodyReader(...)`:\n * - {@link StreamBodyReader}: the default. Reads the stream, fails fast if it was already consumed.\n * - {@link PreConsumedBodyReader}: opt-in for hosts that parse first. Uses `req.rawBody`.\n *\n * An interface (not a class) because it is behaviour: an implementation decides WHERE the bytes come\n * from. Whatever it returns must be the bytes the sender transmitted, because a `{ rawBody: true }`\n * webhook route verifies a vendor signature over exactly this buffer.\n */\nexport interface RequestBodyReader {\n /**\n * @param req - the express request of a POST/PUT/PATCH route.\n * @param maxBodyBytes - the inbound cap. An implementation MUST refuse a larger body with an\n * `ApiBadRequestError` rather than buffer it.\n * @returns the verbatim body bytes (empty for an empty body).\n */\n read(req: Request, maxBodyBytes: number): Promise<Buffer>;\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import { Request } from 'express';
2
+ import { RequestBodyReader } from './RequestBodyReader';
3
+ /**
4
+ * The DEFAULT {@link RequestBodyReader}: read the body off the express request stream.
5
+ *
6
+ * This is the logic `ExpressWrapper.readRequestBody` always had, unchanged, plus ONE guard. A stream
7
+ * that something upstream already consumed (a body parser mounted ahead of webpieces, or a host like
8
+ * Cloud Functions gen2 that parses before the app runs) never emits `end` again, so waiting on it
9
+ * hung the request until the platform timeout with nothing in the logs (issue #937). That case now
10
+ * throws immediately, and the message names both cures.
11
+ */
12
+ export declare class StreamBodyReader implements RequestBodyReader {
13
+ read(req: Request, maxBodyBytes: number): Promise<Buffer>;
14
+ /**
15
+ * True when the request stream can no longer produce a body.
16
+ *
17
+ * `readableEnded` is set once `end` has been emitted, which every complete read (the Functions
18
+ * Framework, body-parser 2's raw-body) leaves behind. body-parser 1.x also marks the request with
19
+ * `_body = true` after parsing it. That marker is checked together with `complete` so a stray
20
+ * `_body` field on a request nobody has read yet is not mistaken for a consumed stream.
21
+ */
22
+ isConsumed(req: Request): boolean;
23
+ /**
24
+ * Read the raw request body as BYTES (we parse manually rather than mounting express.json()).
25
+ *
26
+ * Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that
27
+ * straddles a chunk boundary into two replacement characters, so the body a webhook hook verified
28
+ * would not be the body the vendor signed.
29
+ *
30
+ * REFUSES a body over `maxBodyBytes` the moment it crosses the line. The chunks read so far are
31
+ * dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers
32
+ * 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a
33
+ * caller whose request we are refusing to finish reading, and that ordering is the point.
34
+ */
35
+ private readStream;
36
+ }
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StreamBodyReader = void 0;
4
+ const core_util_1 = require("@webpieces/core-util");
5
+ /**
6
+ * The DEFAULT {@link RequestBodyReader}: read the body off the express request stream.
7
+ *
8
+ * This is the logic `ExpressWrapper.readRequestBody` always had, unchanged, plus ONE guard. A stream
9
+ * that something upstream already consumed (a body parser mounted ahead of webpieces, or a host like
10
+ * Cloud Functions gen2 that parses before the app runs) never emits `end` again, so waiting on it
11
+ * hung the request until the platform timeout with nothing in the logs (issue #937). That case now
12
+ * throws immediately, and the message names both cures.
13
+ */
14
+ class StreamBodyReader {
15
+ read(req, maxBodyBytes) {
16
+ if (this.isConsumed(req)) {
17
+ return Promise.reject(new core_util_1.ApiImplementationError('The request body stream was already consumed before webpieces could read it ' +
18
+ '(a body parser or the hosting platform read it first), and reading it again ' +
19
+ 'would hang forever. Fix: call ' +
20
+ '`router.setBodyReader(new PreConsumedBodyReader())` before ' +
21
+ '`bindExpress(app)` when the host keeps the verbatim bytes on `req.rawBody` ' +
22
+ '(Cloud Functions gen2 / Firebase), or mount webpieces BEFORE the body parser.'));
23
+ }
24
+ return this.readStream(req, maxBodyBytes);
25
+ }
26
+ /**
27
+ * True when the request stream can no longer produce a body.
28
+ *
29
+ * `readableEnded` is set once `end` has been emitted, which every complete read (the Functions
30
+ * Framework, body-parser 2's raw-body) leaves behind. body-parser 1.x also marks the request with
31
+ * `_body = true` after parsing it. That marker is checked together with `complete` so a stray
32
+ * `_body` field on a request nobody has read yet is not mistaken for a consumed stream.
33
+ */
34
+ isConsumed(req) {
35
+ if (req.readableEnded) {
36
+ return true;
37
+ }
38
+ // webpieces-disable no-any-unknown -- `_body` is body-parser 1.x's private marker, absent from the express types
39
+ const marker = req['_body'];
40
+ return req.complete === true && marker === true;
41
+ }
42
+ /**
43
+ * Read the raw request body as BYTES (we parse manually rather than mounting express.json()).
44
+ *
45
+ * Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that
46
+ * straddles a chunk boundary into two replacement characters, so the body a webhook hook verified
47
+ * would not be the body the vendor signed.
48
+ *
49
+ * REFUSES a body over `maxBodyBytes` the moment it crosses the line. The chunks read so far are
50
+ * dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers
51
+ * 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a
52
+ * caller whose request we are refusing to finish reading, and that ordering is the point.
53
+ */
54
+ readStream(req, maxBodyBytes) {
55
+ return new Promise((resolve, reject) => {
56
+ let chunks = [];
57
+ let size = 0;
58
+ // A socket emits Buffers; a stream someone put in string mode (or a test's Readable.from)
59
+ // emits strings. Normalize to bytes ONCE, here, so everything downstream counts and
60
+ // concatenates the same units.
61
+ req.on('data', (data) => {
62
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');
63
+ size += chunk.length;
64
+ if (size > maxBodyBytes) {
65
+ chunks = [];
66
+ req.destroy();
67
+ reject(new core_util_1.ApiBadRequestError(`Request body exceeds the ${maxBodyBytes} byte limit`));
68
+ return;
69
+ }
70
+ chunks.push(chunk);
71
+ });
72
+ req.on('end', () => {
73
+ resolve(Buffer.concat(chunks));
74
+ });
75
+ req.on('error', (err) => {
76
+ reject(err);
77
+ });
78
+ });
79
+ }
80
+ }
81
+ exports.StreamBodyReader = StreamBodyReader;
82
+ //# sourceMappingURL=StreamBodyReader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StreamBodyReader.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/body/StreamBodyReader.ts"],"names":[],"mappings":";;;AACA,oDAAkF;AAGlF;;;;;;;;GAQG;AACH,M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Z,GAAG,CAAC,OAAO,EAAE,CAAC;oBACd,MAAM,CACF,IAAI,8BAAkB,CAAC,4BAA4B,YAAY,aAAa,CAAC,CAChF,CAAC;oBACF,OAAO;gBACX,CAAC;gBACD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACvB,CAAC,CAAC,CAAC;YACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;gBACf,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;YACnC,CAAC,CAAC,CAAC;YACH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAU,EAAE,EAAE;gBAC3B,MAAM,CAAC,GAAG,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AA1ED,4CA0EC","sourcesContent":["import { Request } from 'express';\nimport { ApiBadRequestError, ApiImplementationError } from '@webpieces/core-util';\nimport { RequestBodyReader } from './RequestBodyReader';\n\n/**\n * The DEFAULT {@link RequestBodyReader}: read the body off the express request stream.\n *\n * This is the logic `ExpressWrapper.readRequestBody` always had, unchanged, plus ONE guard. A stream\n * that something upstream already consumed (a body parser mounted ahead of webpieces, or a host like\n * Cloud Functions gen2 that parses before the app runs) never emits `end` again, so waiting on it\n * hung the request until the platform timeout with nothing in the logs (issue #937). That case now\n * throws immediately, and the message names both cures.\n */\nexport class StreamBodyReader implements RequestBodyReader {\n read(req: Request, maxBodyBytes: number): Promise<Buffer> {\n if (this.isConsumed(req)) {\n return Promise.reject(\n new ApiImplementationError(\n 'The request body stream was already consumed before webpieces could read it ' +\n '(a body parser or the hosting platform read it first), and reading it again ' +\n 'would hang forever. Fix: call ' +\n '`router.setBodyReader(new PreConsumedBodyReader())` before ' +\n '`bindExpress(app)` when the host keeps the verbatim bytes on `req.rawBody` ' +\n '(Cloud Functions gen2 / Firebase), or mount webpieces BEFORE the body parser.',\n ),\n );\n }\n return this.readStream(req, maxBodyBytes);\n }\n\n /**\n * True when the request stream can no longer produce a body.\n *\n * `readableEnded` is set once `end` has been emitted, which every complete read (the Functions\n * Framework, body-parser 2's raw-body) leaves behind. body-parser 1.x also marks the request with\n * `_body = true` after parsing it. That marker is checked together with `complete` so a stray\n * `_body` field on a request nobody has read yet is not mistaken for a consumed stream.\n */\n isConsumed(req: Request): boolean {\n if (req.readableEnded) {\n return true;\n }\n // webpieces-disable no-any-unknown -- `_body` is body-parser 1.x's private marker, absent from the express types\n const marker = (req as unknown as Record<string, unknown>)['_body'];\n return req.complete === true && marker === true;\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 `maxBodyBytes` the moment it crosses the line. The chunks read so far are\n * 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 readStream(req: Request, maxBodyBytes: number): 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 > maxBodyBytes) {\n chunks = [];\n req.destroy();\n reject(\n new ApiBadRequestError(`Request body exceeds the ${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"]}
package/src/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  export { WebpiecesExpressRouter } from './WebpiecesExpressRouter';
2
2
  export { WebpiecesMiddleware } from './WebpiecesMiddleware';
3
+ export { RequestBodyReader } from './body/RequestBodyReader';
4
+ export { StreamBodyReader } from './body/StreamBodyReader';
5
+ export { PreConsumedBodyReader } from './body/PreConsumedBodyReader';
3
6
  export { RecordingFilter } from './filters/RecordingFilter';
4
7
  export { ApiErrorHttpMapper } from './ApiErrorHttpMapper';
5
8
  export { TestCaseRecorderImpl } from './recorder/TestCaseRecorderImpl';
package/src/index.js CHANGED
@@ -1,11 +1,15 @@
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.ApiErrorHttpMapper = 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.PreConsumedBodyReader = exports.StreamBodyReader = 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; } });
7
7
  var WebpiecesMiddleware_1 = require("./WebpiecesMiddleware");
8
8
  Object.defineProperty(exports, "WebpiecesMiddleware", { enumerable: true, get: function () { return WebpiecesMiddleware_1.WebpiecesMiddleware; } });
9
+ var StreamBodyReader_1 = require("./body/StreamBodyReader");
10
+ Object.defineProperty(exports, "StreamBodyReader", { enumerable: true, get: function () { return StreamBodyReader_1.StreamBodyReader; } });
11
+ var PreConsumedBodyReader_1 = require("./body/PreConsumedBodyReader");
12
+ Object.defineProperty(exports, "PreConsumedBodyReader", { enumerable: true, get: function () { return PreConsumedBodyReader_1.PreConsumedBodyReader; } });
9
13
  // LogApiFilter is now a FIXED framework filter auto-installed by WebpiecesRouter (outermost, at
10
14
  // priority 1,000,000, above AuthFilter). Apps must NOT install it themselves — it is no longer
11
15
  // exported here. Remove any `router.addFilter(new FilterDefinition(1800, LogApiFilter, '*'))`.
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,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
+ {"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;AAI5B,4DAA2D;AAAlD,oHAAA,gBAAgB,OAAA;AACzB,sEAAqE;AAA5D,8HAAA,qBAAqB,OAAA;AAC9B,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// How routes read the body bytes: stream (default) or a host's pre-consumed req.rawBody (issue #937).\n// Chosen via WebpiecesExpressRouter.setBodyReader(...) before bindExpress(app).\nexport { RequestBodyReader } from './body/RequestBodyReader';\nexport { StreamBodyReader } from './body/StreamBodyReader';\nexport { PreConsumedBodyReader } from './body/PreConsumedBodyReader';\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"]}