@webpieces/http-server 0.4.790 → 0.4.791
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 +20 -12
- package/package.json +5 -5
- package/src/ExpressResponseWriter.d.ts +1 -1
- package/src/ExpressResponseWriter.js +1 -1
- package/src/ExpressResponseWriter.js.map +1 -1
- package/src/ExpressWrapper.d.ts +27 -30
- package/src/ExpressWrapper.js +42 -41
- package/src/ExpressWrapper.js.map +1 -1
- package/src/StreamExpressWrapper.d.ts +1 -4
- package/src/StreamExpressWrapper.js +2 -4
- package/src/StreamExpressWrapper.js.map +1 -1
- package/src/WebpiecesExpressRouter.d.ts +1 -17
- package/src/WebpiecesExpressRouter.js +3 -24
- package/src/WebpiecesExpressRouter.js.map +1 -1
- package/src/WebpiecesMiddleware.d.ts +3 -6
- package/src/WebpiecesMiddleware.js +5 -7
- package/src/WebpiecesMiddleware.js.map +1 -1
- package/src/index.d.ts +0 -2
- package/src/index.js +3 -4
- package/src/index.js.map +1 -1
- package/src/ApiErrorHttpMapper.d.ts +0 -49
- package/src/ApiErrorHttpMapper.js +0 -73
- package/src/ApiErrorHttpMapper.js.map +0 -1
package/README.md
CHANGED
|
@@ -38,24 +38,32 @@ was consumed and there is no `req.rawBody`, it fails fast. It never re-serialize
|
|
|
38
38
|
mount your own body parser ahead of webpieces, either mount webpieces first or keep the bytes with
|
|
39
39
|
`express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })`.
|
|
40
40
|
|
|
41
|
-
## End-user errors
|
|
41
|
+
## End-user errors, and the caller SURFACE that decides their status
|
|
42
42
|
|
|
43
43
|
An `ApiEndUserError` is answered with **266** by default: the call succeeded and a GUI (or the next
|
|
44
|
-
webpieces hop) shows its message.
|
|
45
|
-
statuses opts its router into edge mode before binding the routes:
|
|
44
|
+
webpieces hop) shows its message.
|
|
46
45
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
router.
|
|
50
|
-
|
|
51
|
-
|
|
46
|
+
A partner or public REST API whose contract promises real 4xx statuses gets them **per request**, not
|
|
47
|
+
per router. The same endpoint is reached by a browser GUI, by an LLM through the MCP bridge and by an
|
|
48
|
+
external partner, so which one it is was never something a router could know. `AuthFilter` stamps
|
|
49
|
+
`WebpiecesCoreHeaders.SURFACE` from the auth mode that matched, and `ExpressWrapper.handleError`
|
|
50
|
+
derives the status from it (`SurfaceEndUserStatus`):
|
|
51
|
+
|
|
52
|
+
| how the request authenticated | surface | an `ApiEndUserError` answers |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| `@WpAuthJwt` | `gui` | 266 |
|
|
55
|
+
| `@WpMcpAuthJwt` (through the MCP bridge) | `llm` | 266 |
|
|
56
|
+
| `@WpAuthApiKey` | `public-api` | `edgeHttpStatus`, else 400 |
|
|
57
|
+
| nothing established one (public, webhook, internal hop) | absent | 266 |
|
|
58
|
+
|
|
59
|
+
`gui` and `llm` are both webpieces clients that DECODE the body and render the message themselves, so
|
|
60
|
+
a real 4xx would throw away the only thing they are there to show. A partner has no such client.
|
|
52
61
|
|
|
53
|
-
The
|
|
62
|
+
The published status is the one the throw site chose:
|
|
54
63
|
`new ApiEndUserError(message, errorCode, edgeHttpStatus, cause)` with `edgeHttpStatus` one of
|
|
55
64
|
400/404/409/422, or 400 when it chose none. That field travels in the error body across every
|
|
56
|
-
server-to-server hop, so a service several hops down can set it
|
|
57
|
-
|
|
58
|
-
real 4xx on a hop is still that caller's own 500.
|
|
65
|
+
server-to-server hop, so a service several hops down can set it — and the SURFACE travels with it, so
|
|
66
|
+
the hop that finally answers the partner still knows who asked.
|
|
59
67
|
|
|
60
68
|
## Documentation
|
|
61
69
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-server",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.791",
|
|
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.
|
|
26
|
-
"@webpieces/core-util": "0.4.
|
|
27
|
-
"@webpieces/gcp-identity": "0.4.
|
|
28
|
-
"@webpieces/http-routing": "0.4.
|
|
25
|
+
"@webpieces/core-context": "0.4.791",
|
|
26
|
+
"@webpieces/core-util": "0.4.791",
|
|
27
|
+
"@webpieces/gcp-identity": "0.4.791",
|
|
28
|
+
"@webpieces/http-routing": "0.4.791",
|
|
29
29
|
"cors": "2.8.5",
|
|
30
30
|
"express": "5.1.0",
|
|
31
31
|
"inversify": "7.10.4"
|
|
@@ -4,7 +4,7 @@ import { HttpResponseDto } from '@webpieces/core-util';
|
|
|
4
4
|
* The ONE place an {@link HttpResponseDto} becomes bytes on an express response.
|
|
5
5
|
*
|
|
6
6
|
* Every webpieces surface that owns a socket writes through this: `ExpressWrapper.handleError` for
|
|
7
|
-
* the ordinary API path (webpieces' own default AND an app's `
|
|
7
|
+
* the ordinary API path (webpieces' own default AND an app's `ErrorTranslator`), and
|
|
8
8
|
* `WpMcpServer`'s pre-SDK boundary, which used to hand-roll `res.status(...).json(...)` and so got
|
|
9
9
|
* none of the rules below. Producing a VALUE and handing it here is what makes those two paths the
|
|
10
10
|
* same path.
|
|
@@ -5,7 +5,7 @@ exports.ExpressResponseWriter = void 0;
|
|
|
5
5
|
* The ONE place an {@link HttpResponseDto} becomes bytes on an express response.
|
|
6
6
|
*
|
|
7
7
|
* Every webpieces surface that owns a socket writes through this: `ExpressWrapper.handleError` for
|
|
8
|
-
* the ordinary API path (webpieces' own default AND an app's `
|
|
8
|
+
* the ordinary API path (webpieces' own default AND an app's `ErrorTranslator`), and
|
|
9
9
|
* `WpMcpServer`'s pre-SDK boundary, which used to hand-roll `res.status(...).json(...)` and so got
|
|
10
10
|
* none of the rules below. Producing a VALUE and handing it here is what makes those two paths the
|
|
11
11
|
* same path.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExpressResponseWriter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressResponseWriter.ts"],"names":[],"mappings":";;;AAGA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,qBAAqB;IAC9B,KAAK,CAAC,GAAa,EAAE,QAAyB;QAC1C,MAAM,mBAAmB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAC7C,CAAC,MAAkB,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,cAAc,CACvE,CAAC;QACF,IAAI,CAAC,mBAAmB,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACtD,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC;QACtD,CAAC;QACD,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;YACpC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;QACD,mFAAmF;QACnF,6FAA6F;QAC7F,6DAA6D;QAC7D,GAAG,CAAC,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC;QAC3C,MAAM,OAAO,GACT,QAAQ,CAAC,IAAI,KAAK,SAAS;YACvB,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,mBAAmB,CAAC,CAAC;QAC9D,GAAG,CAAC,MAAM,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;CACJ;AAhCD,sDAgCC","sourcesContent":["import { Response } from 'express';\nimport { HttpHeader, HttpResponseDto } from '@webpieces/core-util';\n\n/**\n * The ONE place an {@link HttpResponseDto} becomes bytes on an express response.\n *\n * Every webpieces surface that owns a socket writes through this: `ExpressWrapper.handleError` for\n * the ordinary API path (webpieces' own default AND an app's `
|
|
1
|
+
{"version":3,"file":"ExpressResponseWriter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressResponseWriter.ts"],"names":[],"mappings":";;;AAGA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,qBAAqB;IAC9B,KAAK,CAAC,GAAa,EAAE,QAAyB;QAC1C,MAAM,mBAAmB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAC7C,CAAC,MAAkB,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,cAAc,CACvE,CAAC;QACF,IAAI,CAAC,mBAAmB,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACtD,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC;QACtD,CAAC;QACD,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;YACpC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;QACD,mFAAmF;QACnF,6FAA6F;QAC7F,6DAA6D;QAC7D,GAAG,CAAC,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC;QAC3C,MAAM,OAAO,GACT,QAAQ,CAAC,IAAI,KAAK,SAAS;YACvB,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,mBAAmB,CAAC,CAAC;QAC9D,GAAG,CAAC,MAAM,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;CACJ;AAhCD,sDAgCC","sourcesContent":["import { Response } from 'express';\nimport { HttpHeader, HttpResponseDto } from '@webpieces/core-util';\n\n/**\n * The ONE place an {@link HttpResponseDto} becomes bytes on an express response.\n *\n * Every webpieces surface that owns a socket writes through this: `ExpressWrapper.handleError` for\n * the ordinary API path (webpieces' own default AND an app's `ErrorTranslator`), and\n * `WpMcpServer`'s pre-SDK boundary, which used to hand-roll `res.status(...).json(...)` and so got\n * none of the rules below. Producing a VALUE and handing it here is what makes those two paths the\n * same path.\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 string\n * body to `text/html`, which is wrong for every response this framework sends. A translator that\n * genuinely wants another type says so in its own header list and wins.\n */\nexport class ExpressResponseWriter {\n write(res: Response, response: HttpResponseDto): void {\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"]}
|
package/src/ExpressWrapper.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
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 { EndUserStatus } from './ApiErrorHttpMapper';
|
|
5
4
|
import { RequestBodyReader } from './body/RequestBodyReader';
|
|
6
5
|
/**
|
|
7
6
|
* The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body
|
|
@@ -59,12 +58,6 @@ export declare class ExpressWrapper {
|
|
|
59
58
|
* chosen via `WebpiecesExpressRouter.setBodyReader`. See {@link RequestBodyReader}.
|
|
60
59
|
*/
|
|
61
60
|
private readonly bodyReader;
|
|
62
|
-
/**
|
|
63
|
-
* Decides what an outside caller is allowed to see of a thrown {@link API error}. Stateless —
|
|
64
|
-
* one instance per wrapper is fine, and the class doc there is where the "only ApiEndUserError's
|
|
65
|
-
* message goes on the wire" rule is stated.
|
|
66
|
-
*/
|
|
67
|
-
private readonly errorWireMapper;
|
|
68
61
|
private readonly responseWriter;
|
|
69
62
|
constructor(clientMethod: (...args: unknown[]) => Promise<unknown>, path: string,
|
|
70
63
|
/** Owns the wire<->context transfer, both directions. Stateless framework singleton. */
|
|
@@ -100,13 +93,7 @@ export declare class ExpressWrapper {
|
|
|
100
93
|
* the body before webpieces runs (Cloud Functions gen2) needs `PreConsumedBodyReader`,
|
|
101
94
|
* chosen via `WebpiecesExpressRouter.setBodyReader`. See {@link RequestBodyReader}.
|
|
102
95
|
*/
|
|
103
|
-
bodyReader?: RequestBodyReader
|
|
104
|
-
/**
|
|
105
|
-
* How an `ApiEndUserError` is answered: 266 for a GUI edge, `edgeHttpStatus` (or 400) for a
|
|
106
|
-
* partner-facing API edge. Chosen via `WebpiecesExpressRouter.setEndUserStatus`; see
|
|
107
|
-
* {@link EndUserStatus}.
|
|
108
|
-
*/
|
|
109
|
-
endUserStatus?: EndUserStatus);
|
|
96
|
+
bodyReader?: RequestBodyReader);
|
|
110
97
|
execute(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
111
98
|
executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
112
99
|
executeImpl(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
@@ -164,35 +151,45 @@ export declare class ExpressWrapper {
|
|
|
164
151
|
private readExpressHeaders;
|
|
165
152
|
/**
|
|
166
153
|
* Turn a thrown value into the response the caller sees — the SERVER half of webpieces' symmetric
|
|
167
|
-
* error handling (the CLIENT half is `ClientErrorTranslator.
|
|
168
|
-
* same {@link HttpResponseDto}).
|
|
154
|
+
* error handling (the CLIENT half is `ClientErrorTranslator.throwIfFailure`, and the two speak
|
|
155
|
+
* the same {@link HttpResponseDto}).
|
|
169
156
|
*
|
|
170
157
|
* PUBLIC so wrapExpress can call it for symmetric error handling.
|
|
171
158
|
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
* reason phrase and logs the real one) and turns anything else into a generic 500.
|
|
159
|
+
* ONE source, unconditionally: `ClientRegistry.getErrorTranslator()`. It is never undefined — it
|
|
160
|
+
* holds {@link WebpiecesDefaultErrorTranslator} until an app replaces it, and an app's own
|
|
161
|
+
* translator declines an error by DELEGATING to that default. So there is no "did this process
|
|
162
|
+
* install one" branch and no per-error "not mine" branch; the app owns the WHOLE response —
|
|
163
|
+
* status code, reason phrase, headers and body — which is what lets it publish its own envelope
|
|
164
|
+
* AND its own `Retry-After` / `WWW-Authenticate` / trace header / cookie.
|
|
179
165
|
*
|
|
180
|
-
* Nothing status-specific is decided here
|
|
181
|
-
* and the list of statuses, which must stay in step with `
|
|
182
|
-
* mapping.
|
|
166
|
+
* Nothing status-specific is decided here — read `WebpiecesDefaultErrorTranslator` for the full
|
|
167
|
+
* rule and the list of statuses, which must stay in step with its own `fromWire`.
|
|
183
168
|
*/
|
|
184
169
|
handleError(res: Response, thrown: unknown): void;
|
|
185
170
|
/**
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
171
|
+
* Republish an end-user answer at the status THIS CALLER's surface expects — the per-request
|
|
172
|
+
* replacement for the deleted per-router `setEndUserStatus`.
|
|
173
|
+
*
|
|
174
|
+
* The same endpoint is reached by a GUI, by an LLM through the MCP bridge and by a partner
|
|
175
|
+
* against a published REST contract, so 266-or-real-4xx was never a property the ROUTER could
|
|
176
|
+
* know. `WebpiecesCoreHeaders.SURFACE` is set at the edge by `AuthFilter` from the auth mode that
|
|
177
|
+
* matched and propagates unchanged; {@link SurfaceEndUserStatus} turns it into the status.
|
|
178
|
+
*
|
|
179
|
+
* It runs over the translator's output rather than inside it, which is deliberate and fixes a
|
|
180
|
+
* footgun: an app translator that declines by delegating used to have to REPEAT its router's mode
|
|
181
|
+
* (`new ApiErrorHttpMapper('edge')`) and repeating it wrongly was silent. Now every end-user
|
|
182
|
+
* answer — webpieces' own and an app's — is republished at the caller's status in one place.
|
|
183
|
+
*
|
|
184
|
+
* Only a webpieces `end-user` payload is touched. An app that publishes its OWN 266 body owns it.
|
|
189
185
|
*/
|
|
186
|
+
private publishedForCallerSurface;
|
|
190
187
|
private send;
|
|
191
188
|
/**
|
|
192
189
|
* Put the transaction id on EVERY response — success and error, webpieces' default body and an
|
|
193
190
|
* app's own. It is INFRASTRUCTURE, not app policy: an app that overrides what an error looks like
|
|
194
191
|
* must not thereby lose the header its support desk quotes back. That is why this lives here and
|
|
195
|
-
* not in {@link
|
|
192
|
+
* not in {@link WebpiecesDefaultErrorTranslator.toWire} or in an app's translators.
|
|
196
193
|
*
|
|
197
194
|
* Silently absent when there is no id to send, which is exactly the accepted known issue recorded
|
|
198
195
|
* at step 0 of {@link executeImpl}: a malformed or oversize body fails before `fillFromRequest`
|
package/src/ExpressWrapper.js
CHANGED
|
@@ -4,7 +4,6 @@ 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 ExpressResponseWriter_1 = require("./ExpressResponseWriter");
|
|
7
|
-
const ApiErrorHttpMapper_1 = require("./ApiErrorHttpMapper");
|
|
8
7
|
const StreamBodyReader_1 = require("./body/StreamBodyReader");
|
|
9
8
|
/**
|
|
10
9
|
* The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body
|
|
@@ -54,12 +53,6 @@ class ExpressWrapper {
|
|
|
54
53
|
maxBodyBytes;
|
|
55
54
|
routeMeta;
|
|
56
55
|
bodyReader;
|
|
57
|
-
/**
|
|
58
|
-
* Decides what an outside caller is allowed to see of a thrown {@link API error}. Stateless —
|
|
59
|
-
* one instance per wrapper is fine, and the class doc there is where the "only ApiEndUserError's
|
|
60
|
-
* message goes on the wire" rule is stated.
|
|
61
|
-
*/
|
|
62
|
-
errorWireMapper;
|
|
63
56
|
responseWriter = new ExpressResponseWriter_1.ExpressResponseWriter();
|
|
64
57
|
constructor(
|
|
65
58
|
// webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
|
|
@@ -97,13 +90,7 @@ class ExpressWrapper {
|
|
|
97
90
|
* the body before webpieces runs (Cloud Functions gen2) needs `PreConsumedBodyReader`,
|
|
98
91
|
* chosen via `WebpiecesExpressRouter.setBodyReader`. See {@link RequestBodyReader}.
|
|
99
92
|
*/
|
|
100
|
-
bodyReader = new StreamBodyReader_1.StreamBodyReader()
|
|
101
|
-
/**
|
|
102
|
-
* How an `ApiEndUserError` is answered: 266 for a GUI edge, `edgeHttpStatus` (or 400) for a
|
|
103
|
-
* partner-facing API edge. Chosen via `WebpiecesExpressRouter.setEndUserStatus`; see
|
|
104
|
-
* {@link EndUserStatus}.
|
|
105
|
-
*/
|
|
106
|
-
endUserStatus = 'gui') {
|
|
93
|
+
bodyReader = new StreamBodyReader_1.StreamBodyReader()) {
|
|
107
94
|
this.clientMethod = clientMethod;
|
|
108
95
|
this.path = path;
|
|
109
96
|
this.headers = headers;
|
|
@@ -112,7 +99,6 @@ class ExpressWrapper {
|
|
|
112
99
|
this.maxBodyBytes = maxBodyBytes;
|
|
113
100
|
this.routeMeta = routeMeta;
|
|
114
101
|
this.bodyReader = bodyReader;
|
|
115
|
-
this.errorWireMapper = new ApiErrorHttpMapper_1.ApiErrorHttpMapper(endUserStatus);
|
|
116
102
|
}
|
|
117
103
|
async execute(req, res, next) {
|
|
118
104
|
// MOVED: Wrap entire request in RequestContext.run()
|
|
@@ -135,7 +121,7 @@ class ExpressWrapper {
|
|
|
135
121
|
async executeImpl(req, res, next) {
|
|
136
122
|
// 0. PUBLISH the transport-neutral request BEFORE anything that can throw.
|
|
137
123
|
//
|
|
138
|
-
// This is the ordering bug issue #862 was filed for. An app's
|
|
124
|
+
// This is the ordering bug issue #862 was filed for. An app's ErrorTranslator.toWire has
|
|
139
125
|
// to be able to tell WHICH request it is answering for — the surface, the route, the
|
|
140
126
|
// method — and the only place that lives is RequestContext.getRequest(). Publishing it at
|
|
141
127
|
// step 3 (below) meant a body that failed to parse at step 1 reached handleError with an
|
|
@@ -338,22 +324,20 @@ class ExpressWrapper {
|
|
|
338
324
|
}
|
|
339
325
|
/**
|
|
340
326
|
* Turn a thrown value into the response the caller sees — the SERVER half of webpieces' symmetric
|
|
341
|
-
* error handling (the CLIENT half is `ClientErrorTranslator.
|
|
342
|
-
* same {@link HttpResponseDto}).
|
|
327
|
+
* error handling (the CLIENT half is `ClientErrorTranslator.throwIfFailure`, and the two speak
|
|
328
|
+
* the same {@link HttpResponseDto}).
|
|
343
329
|
*
|
|
344
330
|
* PUBLIC so wrapExpress can call it for symmetric error handling.
|
|
345
331
|
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
*
|
|
350
|
-
*
|
|
351
|
-
*
|
|
352
|
-
* reason phrase and logs the real one) and turns anything else into a generic 500.
|
|
332
|
+
* ONE source, unconditionally: `ClientRegistry.getErrorTranslator()`. It is never undefined — it
|
|
333
|
+
* holds {@link WebpiecesDefaultErrorTranslator} until an app replaces it, and an app's own
|
|
334
|
+
* translator declines an error by DELEGATING to that default. So there is no "did this process
|
|
335
|
+
* install one" branch and no per-error "not mine" branch; the app owns the WHOLE response —
|
|
336
|
+
* status code, reason phrase, headers and body — which is what lets it publish its own envelope
|
|
337
|
+
* AND its own `Retry-After` / `WWW-Authenticate` / trace header / cookie.
|
|
353
338
|
*
|
|
354
|
-
* Nothing status-specific is decided here
|
|
355
|
-
* and the list of statuses, which must stay in step with `
|
|
356
|
-
* mapping.
|
|
339
|
+
* Nothing status-specific is decided here — read `WebpiecesDefaultErrorTranslator` for the full
|
|
340
|
+
* rule and the list of statuses, which must stay in step with its own `fromWire`.
|
|
357
341
|
*/
|
|
358
342
|
// webpieces-disable no-any-unknown -- a thrown value is genuinely unknown until toError narrows it
|
|
359
343
|
handleError(res, thrown) {
|
|
@@ -361,21 +345,38 @@ class ExpressWrapper {
|
|
|
361
345
|
return;
|
|
362
346
|
}
|
|
363
347
|
// ONE narrowing, at the top, and every layer below it is honest about holding an `Error`.
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
// and body — so an app can publish its own envelope AND its own `Retry-After` /
|
|
367
|
-
// `WWW-Authenticate` / trace header / cookie, which the old (statusCode, protocolError) pair
|
|
368
|
-
// could not express at all. A registered translator REPLACES this default and declines by
|
|
369
|
-
// delegating back to it, so there is no per-error "not mine" branch here: the only question
|
|
370
|
-
// is whether this process installed one.
|
|
371
|
-
const translators = core_util_1.ClientRegistry.getErrorTranslators();
|
|
372
|
-
this.send(res, translators ? translators.toWire(error) : this.errorWireMapper.toResponse(error));
|
|
348
|
+
const wire = core_util_1.ClientRegistry.getErrorTranslator().toWire((0, core_util_1.toError)(thrown));
|
|
349
|
+
this.send(res, this.publishedForCallerSurface(wire));
|
|
373
350
|
}
|
|
374
351
|
/**
|
|
375
|
-
*
|
|
376
|
-
*
|
|
377
|
-
*
|
|
352
|
+
* Republish an end-user answer at the status THIS CALLER's surface expects — the per-request
|
|
353
|
+
* replacement for the deleted per-router `setEndUserStatus`.
|
|
354
|
+
*
|
|
355
|
+
* The same endpoint is reached by a GUI, by an LLM through the MCP bridge and by a partner
|
|
356
|
+
* against a published REST contract, so 266-or-real-4xx was never a property the ROUTER could
|
|
357
|
+
* know. `WebpiecesCoreHeaders.SURFACE` is set at the edge by `AuthFilter` from the auth mode that
|
|
358
|
+
* matched and propagates unchanged; {@link SurfaceEndUserStatus} turns it into the status.
|
|
359
|
+
*
|
|
360
|
+
* It runs over the translator's output rather than inside it, which is deliberate and fixes a
|
|
361
|
+
* footgun: an app translator that declines by delegating used to have to REPEAT its router's mode
|
|
362
|
+
* (`new ApiErrorHttpMapper('edge')`) and repeating it wrongly was silent. Now every end-user
|
|
363
|
+
* answer — webpieces' own and an app's — is republished at the caller's status in one place.
|
|
364
|
+
*
|
|
365
|
+
* Only a webpieces `end-user` payload is touched. An app that publishes its OWN 266 body owns it.
|
|
378
366
|
*/
|
|
367
|
+
publishedForCallerSurface(response) {
|
|
368
|
+
if (response.status.code !== 266 || !core_util_1.ApiErrorCodec.isPayload(response.body)) {
|
|
369
|
+
return response;
|
|
370
|
+
}
|
|
371
|
+
const payload = response.body;
|
|
372
|
+
const status = core_util_1.SurfaceEndUserStatus.statusFor(core_context_1.RequestContext.isActive()
|
|
373
|
+
? core_context_1.RequestContext.getTrusted(core_util_1.WebpiecesCoreHeaders.SURFACE)
|
|
374
|
+
: undefined, payload.edgeHttpStatus);
|
|
375
|
+
if (status === 266) {
|
|
376
|
+
return response;
|
|
377
|
+
}
|
|
378
|
+
return new core_util_1.HttpResponseDto(new core_util_1.HttpResponseStatus(status, core_util_1.WEBPIECES_DEFAULT_ERROR_TRANSLATOR.genericMessage(status)), response.headers, response.body);
|
|
379
|
+
}
|
|
379
380
|
send(res, response) {
|
|
380
381
|
this.stampTransactionId(res);
|
|
381
382
|
this.responseWriter.write(res, response);
|
|
@@ -384,7 +385,7 @@ class ExpressWrapper {
|
|
|
384
385
|
* Put the transaction id on EVERY response — success and error, webpieces' default body and an
|
|
385
386
|
* app's own. It is INFRASTRUCTURE, not app policy: an app that overrides what an error looks like
|
|
386
387
|
* must not thereby lose the header its support desk quotes back. That is why this lives here and
|
|
387
|
-
* not in {@link
|
|
388
|
+
* not in {@link WebpiecesDefaultErrorTranslator.toWire} or in an app's translators.
|
|
388
389
|
*
|
|
389
390
|
* Silently absent when there is no id to send, which is exactly the accepted known issue recorded
|
|
390
391
|
* at step 0 of {@link executeImpl}: a malformed or oversize body fails before `fillFromRequest`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.ts"],"names":[],"mappings":";;;AACA,oDAU8B;AAC9B,0DAKiC;AACjC,mEAAgE;AAChE,6DAAyE;AAEzE,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;IAWX;IACA;IAEA;IAMA;IAOA;IAWA;IAES;IAMA;IA7CrB;;;;OAIG;IACc,eAAe,CAAqB;IACpC,cAAc,GAAG,IAAI,6CAAqB,EAAE,CAAC;IAE9D;IACI,+FAA+F;IACvF,YAAsD,EACtD,IAAY;IACpB,wFAAwF;IAChF,OAA8B;IACtC;;;;OAIG;IACK,WAAoB,KAAK;IACjC;;;;;OAKG;IACK,UAAmB,KAAK;IAChC;;;;;;;;;OASG;IACK,eAAuB,sBAAc;IAC7C,sFAAsF;IACrE,SAAyB;IAC1C;;;;OAIG;IACc,aAAgC,IAAI,mCAAgB,EAAE;IACvE;;;;OAIG;IACH,gBAA+B,KAAK;QAzC5B,iBAAY,GAAZ,YAAY,CAA0C;QACtD,SAAI,GAAJ,IAAI,CAAQ;QA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I,CAAC,IAAI,CACL,GAAG,EACH,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC,KAAK,CAAC,CACnF,CAAC;IACN,CAAC;IAED;;;;OAIG;IACK,IAAI,CAAC,GAAa,EAAE,QAAyB;QACjD,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAC7C,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;AAjYD,wCAiYC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ClientRegistry,\n ApiBadRequestError,\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 { ExpressResponseWriter } from './ExpressResponseWriter';\nimport { ApiErrorHttpMapper, EndUserStatus } 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: ApiErrorHttpMapper;\n private readonly responseWriter = new ExpressResponseWriter();\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 * How an `ApiEndUserError` is answered: 266 for a GUI edge, `edgeHttpStatus` (or 400) for a\n * partner-facing API edge. Chosen via `WebpiecesExpressRouter.setEndUserStatus`; see\n * {@link EndUserStatus}.\n */\n endUserStatus: EndUserStatus = 'gui',\n ) {\n this.errorWireMapper = new ApiErrorHttpMapper(endUserStatus);\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 (an `ApiEndUserError` per this wrapper's\n * {@link EndUserStatus}) 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 value is genuinely unknown until toError narrows it\n public handleError(res: Response, thrown: unknown): void {\n if (res.headersSent) {\n return;\n }\n\n // ONE narrowing, at the top, and every layer below it is honest about holding an `Error`.\n const error = toError(thrown);\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. A registered translator REPLACES this default and declines by\n // delegating back to it, so there is no per-error \"not mine\" branch here: the only question\n // is whether this process installed one.\n const translators = ClientRegistry.getErrorTranslators();\n this.send(\n res,\n translators ? translators.toWire(error) : this.errorWireMapper.toResponse(error),\n );\n }\n\n /**\n * Stamp the transaction id and hand the DTO to the shared {@link ExpressResponseWriter} — the\n * ONE place a response DTO becomes bytes, used by the app's translators, by webpieces' own\n * default, and by the MCP pre-SDK boundary alike.\n */\n private send(res: Response, response: HttpResponseDto): void {\n this.stampTransactionId(res);\n this.responseWriter.write(res, response);\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,oDAc8B;AAC9B,0DAKiC;AACjC,mEAAgE;AAEhE,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,c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QAAQ,CAAC,CAAC;IAC7C,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;AAtYD,wCAsYC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ClientRegistry,\n ApiBadRequestError,\n HttpContractMapper,\n HttpResponseDto,\n HttpResponseStatus,\n RouteMetadata,\n ApiImplementationError,\n toError,\n WebpiecesCoreHeaders,\n ApiErrorCodec,\n ApiErrorPayload,\n SurfaceEndUserStatus,\n WEBPIECES_DEFAULT_ERROR_TRANSLATOR,\n} from '@webpieces/core-util';\nimport {\n RequestContext,\n HttpRequest,\n RawRequest,\n RequestContextHeaders,\n} from '@webpieces/core-context';\nimport { ExpressResponseWriter } from './ExpressResponseWriter';\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 private readonly responseWriter = new ExpressResponseWriter();\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 ErrorTranslator.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.throwIfFailure`, and the two speak\n * the same {@link HttpResponseDto}).\n *\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n *\n * ONE source, unconditionally: `ClientRegistry.getErrorTranslator()`. It is never undefined — it\n * holds {@link WebpiecesDefaultErrorTranslator} until an app replaces it, and an app's own\n * translator declines an error by DELEGATING to that default. So there is no \"did this process\n * install one\" branch and no per-error \"not mine\" branch; the app owns the WHOLE response —\n * status code, reason phrase, headers and body — which is what lets it publish its own envelope\n * AND its own `Retry-After` / `WWW-Authenticate` / trace header / cookie.\n *\n * Nothing status-specific is decided here — read `WebpiecesDefaultErrorTranslator` for the full\n * rule and the list of statuses, which must stay in step with its own `fromWire`.\n */\n // webpieces-disable no-any-unknown -- a thrown value is genuinely unknown until toError narrows it\n public handleError(res: Response, thrown: unknown): void {\n if (res.headersSent) {\n return;\n }\n // ONE narrowing, at the top, and every layer below it is honest about holding an `Error`.\n const wire = ClientRegistry.getErrorTranslator().toWire(toError(thrown));\n this.send(res, this.publishedForCallerSurface(wire));\n }\n\n /**\n * Republish an end-user answer at the status THIS CALLER's surface expects — the per-request\n * replacement for the deleted per-router `setEndUserStatus`.\n *\n * The same endpoint is reached by a GUI, by an LLM through the MCP bridge and by a partner\n * against a published REST contract, so 266-or-real-4xx was never a property the ROUTER could\n * know. `WebpiecesCoreHeaders.SURFACE` is set at the edge by `AuthFilter` from the auth mode that\n * matched and propagates unchanged; {@link SurfaceEndUserStatus} turns it into the status.\n *\n * It runs over the translator's output rather than inside it, which is deliberate and fixes a\n * footgun: an app translator that declines by delegating used to have to REPEAT its router's mode\n * (`new ApiErrorHttpMapper('edge')`) and repeating it wrongly was silent. Now every end-user\n * answer — webpieces' own and an app's — is republished at the caller's status in one place.\n *\n * Only a webpieces `end-user` payload is touched. An app that publishes its OWN 266 body owns it.\n */\n private publishedForCallerSurface(response: HttpResponseDto): HttpResponseDto {\n if (response.status.code !== 266 || !ApiErrorCodec.isPayload(response.body)) {\n return response;\n }\n const payload = response.body as ApiErrorPayload;\n const status = SurfaceEndUserStatus.statusFor(\n RequestContext.isActive()\n ? RequestContext.getTrusted(WebpiecesCoreHeaders.SURFACE)\n : undefined,\n payload.edgeHttpStatus,\n );\n if (status === 266) {\n return response;\n }\n return new HttpResponseDto(\n new HttpResponseStatus(status, WEBPIECES_DEFAULT_ERROR_TRANSLATOR.genericMessage(status)),\n response.headers,\n response.body,\n );\n }\n\n private send(res: Response, response: HttpResponseDto): void {\n this.stampTransactionId(res);\n this.responseWriter.write(res, response);\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 WebpiecesDefaultErrorTranslator.toWire} 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,7 +1,6 @@
|
|
|
1
1
|
import { NextFunction, Request, Response } from 'express';
|
|
2
2
|
import { RouteMetadata } from '@webpieces/core-util';
|
|
3
3
|
import { RequestContextHeaders } from '@webpieces/core-context';
|
|
4
|
-
import { EndUserStatus } from './ApiErrorHttpMapper';
|
|
5
4
|
/** Express adapter for a `@WpStream` request-NDJSON / response-SSE contract. */
|
|
6
5
|
export declare class StreamExpressWrapper {
|
|
7
6
|
private readonly clientMethod;
|
|
@@ -9,9 +8,7 @@ export declare class StreamExpressWrapper {
|
|
|
9
8
|
private readonly headers;
|
|
10
9
|
private readonly ordinaryErrors;
|
|
11
10
|
private readonly validator;
|
|
12
|
-
constructor(clientMethod: (...args: unknown[]) => Promise<unknown>, route: RouteMetadata, headers: RequestContextHeaders
|
|
13
|
-
/** How a handshake-time `ApiEndUserError` is answered; see {@link EndUserStatus}. */
|
|
14
|
-
endUserStatus?: EndUserStatus);
|
|
11
|
+
constructor(clientMethod: (...args: unknown[]) => Promise<unknown>, route: RouteMetadata, headers: RequestContextHeaders);
|
|
15
12
|
execute(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
16
13
|
private executeInContext;
|
|
17
14
|
private runOpenStream;
|
|
@@ -101,13 +101,11 @@ class StreamExpressWrapper {
|
|
|
101
101
|
validator = new core_util_1.StreamEventValidator();
|
|
102
102
|
constructor(
|
|
103
103
|
// webpieces-disable no-any-unknown -- stream contract types are erased at the express boundary
|
|
104
|
-
clientMethod, route, headers
|
|
105
|
-
/** How a handshake-time `ApiEndUserError` is answered; see {@link EndUserStatus}. */
|
|
106
|
-
endUserStatus = 'gui') {
|
|
104
|
+
clientMethod, route, headers) {
|
|
107
105
|
this.clientMethod = clientMethod;
|
|
108
106
|
this.route = route;
|
|
109
107
|
this.headers = headers;
|
|
110
|
-
this.ordinaryErrors = new ExpressWrapper_1.ExpressWrapper(clientMethod, route.path, headers, false, false, undefined, route
|
|
108
|
+
this.ordinaryErrors = new ExpressWrapper_1.ExpressWrapper(clientMethod, route.path, headers, false, false, undefined, route);
|
|
111
109
|
}
|
|
112
110
|
async execute(req, res, next) {
|
|
113
111
|
void next;
|