@webpieces/http-server 0.4.773 → 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.773",
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.773",
26
- "@webpieces/core-util": "0.4.773",
27
- "@webpieces/gcp-identity": "0.4.773",
28
- "@webpieces/http-routing": "0.4.773",
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 { HttpResponseDto } from '@webpieces/core-util';
2
2
  /** HTTP adapter for the transport-neutral API error taxonomy. */
3
3
  export declare class ApiErrorHttpMapper {
4
+ private readonly boundary;
4
5
  private readonly genericMessages;
5
6
  /**
6
7
  * Unknown throws and caller-local failures become a concrete implementation failure at this
@@ -8,7 +9,4 @@ export declare class ApiErrorHttpMapper {
8
9
  */
9
10
  toResponse(thrown: unknown): HttpResponseDto;
10
11
  genericMessage(code: number): string;
11
- private normalize;
12
- private operatorDetail;
13
- private logOperatorDetail;
14
12
  }
@@ -5,6 +5,7 @@ const core_util_1 = require("@webpieces/core-util");
5
5
  const log = core_util_1.LogManager.getLogger('ApiErrorHttpMapper');
6
6
  /** HTTP adapter for the transport-neutral API error taxonomy. */
7
7
  class ApiErrorHttpMapper {
8
+ boundary = new core_util_1.ApiErrorBoundary(log);
8
9
  genericMessages = new Map([
9
10
  [266, 'End User Error'],
10
11
  [400, 'Bad Request'],
@@ -24,9 +25,9 @@ class ApiErrorHttpMapper {
24
25
  */
25
26
  // webpieces-disable no-any-unknown -- thrown values are unknown until normalized at this boundary
26
27
  toResponse(thrown) {
27
- const error = this.normalize(thrown);
28
+ const error = this.boundary.normalize(thrown);
28
29
  const status = core_util_1.ApiErrorHttpStatus.code(error);
29
- this.logOperatorDetail(error);
30
+ this.boundary.logOperatorDetail(error);
30
31
  const headers = error instanceof core_util_1.ApiDependencyBackoffError
31
32
  ? [new core_util_1.HttpHeader('retry-after', String(error.retryAfterSeconds))]
32
33
  : [];
@@ -35,34 +36,6 @@ class ApiErrorHttpMapper {
35
36
  genericMessage(code) {
36
37
  return this.genericMessages.get(code) ?? 'Request Failed';
37
38
  }
38
- // webpieces-disable no-any-unknown -- thrown values are unknown until normalized
39
- normalize(thrown) {
40
- if (thrown instanceof core_util_1.ApiError && !(thrown instanceof core_util_1.ApiConnectionError))
41
- return thrown;
42
- const error = (0, core_util_1.toError)(thrown);
43
- return new core_util_1.ApiImplementationError(error.message, error);
44
- }
45
- operatorDetail(error) {
46
- const cause = error.cause instanceof Error ? ` cause=${error.cause.message}` : '';
47
- return `[name=${error.name} kind=${error.kind} subType=${error.subType ?? 'none'}] ${error.message}${cause}`;
48
- }
49
- logOperatorDetail(error) {
50
- const detail = this.operatorDetail(error);
51
- if (error instanceof core_util_1.ApiEndUserError)
52
- log.info(`End User Error: ${detail}`);
53
- else if (error instanceof core_util_1.ApiBadRequestError)
54
- log.info(`Bad Request: ${detail}`);
55
- else if (error instanceof core_util_1.ApiNotFoundError)
56
- log.info(`Not Found: ${detail}`);
57
- else if (error instanceof core_util_1.ApiUnauthorizedError)
58
- log.info(`Unauthorized: ${detail}`);
59
- else if (error instanceof core_util_1.ApiForbiddenError)
60
- log.info(`Forbidden: ${detail}`);
61
- else if (error instanceof core_util_1.ApiRequestTimeoutError)
62
- log.error(`Request Timeout: ${detail}`);
63
- else
64
- log.error(`API failure: ${detail}`);
65
- }
66
39
  }
67
40
  exports.ApiErrorHttpMapper = ApiErrorHttpMapper;
68
41
  //# sourceMappingURL=ApiErrorHttpMapper.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ApiErrorHttpMapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ApiErrorHttpMapper.ts"],"names":[],"mappings":";;;AAAA,oDAkB8B;AAE9B,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;AAEvD,iEAAiE;AACjE,MAAa,kBAAkB;IACV,eAAe,GAAwB,IAAI,GAAG,CAAiB;QAC5E,CAAC,GAAG,EAAE,gBAAgB,CAAC;QACvB,CAAC,GAAG,EAAE,aAAa,CAAC;QACpB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{\n ApiBadRequestError,\n ApiConnectionError,\n ApiDependencyBackoffError,\n ApiEndUserError,\n ApiError,\n ApiErrorCodec,\n ApiForbiddenError,\n ApiImplementationError,\n ApiNotFoundError,\n ApiRequestTimeoutError,\n ApiUnauthorizedError,\n ApiErrorHttpStatus,\n HttpHeader,\n HttpResponseDto,\n HttpResponseStatus,\n LogManager,\n toError,\n} from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('ApiErrorHttpMapper');\n\n/** HTTP adapter for the transport-neutral API error taxonomy. */\nexport class ApiErrorHttpMapper {\n private readonly genericMessages: Map<number, string> = new Map<number, string>([\n [266, 'End User Error'],\n [400, 'Bad Request'],\n [401, 'Unauthorized'],\n [403, 'Forbidden'],\n [404, 'Not Found'],\n [408, 'Request Timeout'],\n [429, 'Too Many Requests'],\n [500, 'Internal Server Error'],\n [502, 'Bad Gateway'],\n [503, 'Service Unavailable'],\n [504, 'Gateway Timeout'],\n ]);\n\n /**\n * Unknown throws and caller-local failures become a concrete implementation failure at this\n * owning API boundary. ApiError itself has no fallback status mapping.\n */\n // webpieces-disable no-any-unknown -- thrown values are unknown until normalized at this boundary\n public toResponse(thrown: unknown): HttpResponseDto {\n const error = this.normalize(thrown);\n const status = ApiErrorHttpStatus.code(error);\n this.logOperatorDetail(error);\n const headers =\n error instanceof ApiDependencyBackoffError\n ? [new HttpHeader('retry-after', String(error.retryAfterSeconds))]\n : [];\n return new HttpResponseDto(\n new HttpResponseStatus(status, this.genericMessage(status)),\n headers,\n ApiErrorCodec.encode(error),\n );\n }\n\n public genericMessage(code: number): string {\n return this.genericMessages.get(code) ?? 'Request Failed';\n }\n\n // webpieces-disable no-any-unknown -- thrown values are unknown until normalized\n private normalize(thrown: unknown): ApiError {\n if (thrown instanceof ApiError && !(thrown instanceof ApiConnectionError)) return thrown;\n const error = toError(thrown);\n return new ApiImplementationError(error.message, error);\n }\n\n private operatorDetail(error: ApiError): string {\n const cause = error.cause instanceof Error ? ` cause=${error.cause.message}` : '';\n return `[name=${error.name} kind=${error.kind} subType=${error.subType ?? 'none'}] ${error.message}${cause}`;\n }\n\n private logOperatorDetail(error: ApiError): void {\n const detail = this.operatorDetail(error);\n if (error instanceof ApiEndUserError) log.info(`End User Error: ${detail}`);\n else if (error instanceof ApiBadRequestError) log.info(`Bad Request: ${detail}`);\n else if (error instanceof ApiNotFoundError) log.info(`Not Found: ${detail}`);\n else if (error instanceof ApiUnauthorizedError) log.info(`Unauthorized: ${detail}`);\n else if (error instanceof ApiForbiddenError) log.info(`Forbidden: ${detail}`);\n else if (error instanceof ApiRequestTimeoutError) log.error(`Request Timeout: ${detail}`);\n else log.error(`API failure: ${detail}`);\n }\n}\n"]}
1
+ {"version":3,"file":"ApiErrorHttpMapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ApiErrorHttpMapper.ts"],"names":[],"mappings":";;;AAAA,oDAS8B;AAE9B,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;AAEvD,iEAAiE;AACjE,MAAa,kBAAkB;IACV,QAAQ,GAAG,IAAI,4BAAgB,CAAC,GAAG,CAAC,CAAC;IACrC,eAAe,GAAwB,IAAI,GAAG,CAAiB;QAC5E,CAAC,GAAG,EAAE,gBAAgB,CAAC;QACvB,CAAC,GAAG,EAAE,aAAa,CAAC;QACpB,CAAC,GAAG,EAAE,cAAc,CAAC;QACrB,CAAC,GAAG,EAAE,WAAW,CAAC;QAClB,CAAC,GAAG,EAAE,WAAW,CAAC;QAClB,CAAC,GAAG,EAAE,iBAAiB,CAAC;QACxB,CAAC,GAAG,EAAE,mBAAmB,CAAC;QAC1B,CAAC,GAAG,EAAE,uBAAuB,CAAC;QAC9B,CAAC,GAAG,EAAE,aAAa,CAAC;QACpB,CAAC,GAAG,EAAE,qBAAqB,CAAC;QAC5B,CAAC,GAAG,EAAE,iBAAiB,CAAC;KAC3B,CAAC,CAAC;IAEH;;;OAGG;IACH,kGAAkG;IAC3F,UAAU,CAAC,MAAe;QAC7B,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QAC9C,MAAM,MAAM,GAAG,8BAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC;QACvC,MAAM,OAAO,GACT,KAAK,YAAY,qCAAyB;YACtC,CAAC,CAAC,CAAC,IAAI,sBAAU,CAAC,aAAa,EAAE,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;YAClE,CAAC,CAAC,EAAE,CAAC;QACb,OAAO,IAAI,2BAAe,CACtB,IAAI,8BAAkB,CAAC,MAAM,EAAE,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,EAC3D,OAAO,EACP,yBAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAC9B,CAAC;IACN,CAAC;IAEM,cAAc,CAAC,IAAY;QAC9B,OAAO,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,gBAAgB,CAAC;IAC9D,CAAC;CACJ;AAvCD,gDAuCC","sourcesContent":["import {\n ApiDependencyBackoffError,\n ApiErrorBoundary,\n ApiErrorCodec,\n ApiErrorHttpStatus,\n HttpHeader,\n HttpResponseDto,\n HttpResponseStatus,\n LogManager,\n} from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('ApiErrorHttpMapper');\n\n/** HTTP adapter for the transport-neutral API error taxonomy. */\nexport class ApiErrorHttpMapper {\n private readonly boundary = new ApiErrorBoundary(log);\n private readonly genericMessages: Map<number, string> = new Map<number, string>([\n [266, 'End User Error'],\n [400, 'Bad Request'],\n [401, 'Unauthorized'],\n [403, 'Forbidden'],\n [404, 'Not Found'],\n [408, 'Request Timeout'],\n [429, 'Too Many Requests'],\n [500, 'Internal Server Error'],\n [502, 'Bad Gateway'],\n [503, 'Service Unavailable'],\n [504, 'Gateway Timeout'],\n ]);\n\n /**\n * Unknown throws and caller-local failures become a concrete implementation failure at this\n * owning API boundary. ApiError itself has no fallback status mapping.\n */\n // webpieces-disable no-any-unknown -- thrown values are unknown until normalized at this boundary\n public toResponse(thrown: unknown): HttpResponseDto {\n const error = this.boundary.normalize(thrown);\n const status = ApiErrorHttpStatus.code(error);\n this.boundary.logOperatorDetail(error);\n const headers =\n error instanceof ApiDependencyBackoffError\n ? [new HttpHeader('retry-after', String(error.retryAfterSeconds))]\n : [];\n return new HttpResponseDto(\n new HttpResponseStatus(status, this.genericMessage(status)),\n headers,\n ApiErrorCodec.encode(error),\n );\n }\n\n public genericMessage(code: number): string {\n return this.genericMessages.get(code) ?? 'Request Failed';\n }\n}\n"]}
@@ -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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,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,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;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,CAA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xZD,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"]}
@@ -0,0 +1,22 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+ import { RouteMetadata } from '@webpieces/core-util';
3
+ import { RequestContextHeaders } from '@webpieces/core-context';
4
+ /** Express adapter for a `@WpStream` request-NDJSON / response-SSE contract. */
5
+ export declare class StreamExpressWrapper {
6
+ private readonly clientMethod;
7
+ private readonly route;
8
+ private readonly headers;
9
+ private readonly ordinaryErrors;
10
+ private readonly validator;
11
+ constructor(clientMethod: (...args: unknown[]) => Promise<unknown>, route: RouteMetadata, headers: RequestContextHeaders);
12
+ execute(req: Request, res: Response, next: NextFunction): Promise<void>;
13
+ private executeInContext;
14
+ private runOpenStream;
15
+ private consumeNdjson;
16
+ private dispatchLine;
17
+ private parseEnvelope;
18
+ private parseCorrelation;
19
+ private requireNdjson;
20
+ private isRequestWriter;
21
+ private toWebpiecesRequest;
22
+ }