@webpieces/http-server 0.4.641 → 0.4.642
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -5
- package/src/ExpressWrapper.d.ts +55 -3
- package/src/ExpressWrapper.js +100 -15
- package/src/ExpressWrapper.js.map +1 -1
- package/src/WebpiecesExpressRouter.js +3 -2
- package/src/WebpiecesExpressRouter.js.map +1 -1
- package/src/WebpiecesMiddleware.d.ts +4 -1
- package/src/WebpiecesMiddleware.js +5 -2
- package/src/WebpiecesMiddleware.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-server",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.642",
|
|
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.642",
|
|
26
|
+
"@webpieces/core-util": "0.4.642",
|
|
27
|
+
"@webpieces/gcp-identity": "0.4.642",
|
|
28
|
+
"@webpieces/http-routing": "0.4.642",
|
|
29
29
|
"cors": "2.8.5",
|
|
30
30
|
"express": "5.1.0",
|
|
31
31
|
"inversify": "7.10.4"
|
package/src/ExpressWrapper.d.ts
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import { Request, Response, NextFunction } from 'express';
|
|
2
2
|
import { RequestContextHeaders } from '@webpieces/core-context';
|
|
3
|
+
/**
|
|
4
|
+
* The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body
|
|
5
|
+
* crosses it — the bytes already read are dropped, nothing further is buffered.
|
|
6
|
+
*
|
|
7
|
+
* There was NO limit at all before, which was a latent memory DoS on every route and an outright one
|
|
8
|
+
* on a webhook route: `{ rawBody: true }` retains what it reads, and a webhook url is public by
|
|
9
|
+
* construction, so the endpoint most likely to be flooded was also the one that held on to the flood.
|
|
10
|
+
* 10 MiB is comfortably above any api DTO and well under Cloud Run's own 32 MiB request limit.
|
|
11
|
+
*/
|
|
12
|
+
export declare const MAX_BODY_BYTES: number;
|
|
3
13
|
export declare class ExpressWrapper {
|
|
4
14
|
private clientMethod;
|
|
5
15
|
private path;
|
|
@@ -11,6 +21,15 @@ export declare class ExpressWrapper {
|
|
|
11
21
|
* the request Content-Type header — the annotation is the single source of truth.
|
|
12
22
|
*/
|
|
13
23
|
private formPost;
|
|
24
|
+
/**
|
|
25
|
+
* True for an @Endpoint(..., { rawBody: true }) route: RETAIN the verbatim bytes + the
|
|
26
|
+
* absolute url on the published {@link HttpRequest}, so an @AuthWebhook hook can verify a
|
|
27
|
+
* vendor signature over what the sender actually transmitted. Also switches the JSON parse
|
|
28
|
+
* failure from "throw now" to "hold it for AuthFilter" — see {@link RawRequest.bodyParseError}.
|
|
29
|
+
*/
|
|
30
|
+
private rawBody;
|
|
31
|
+
/** The inbound body cap for this route. See {@link MAX_BODY_BYTES}. */
|
|
32
|
+
private maxBodyBytes;
|
|
14
33
|
constructor(clientMethod: (requestDto: unknown) => Promise<unknown>, path: string,
|
|
15
34
|
/** Owns the wire<->context transfer, both directions. Stateless framework singleton. */
|
|
16
35
|
headers: RequestContextHeaders,
|
|
@@ -19,7 +38,16 @@ export declare class ExpressWrapper {
|
|
|
19
38
|
* application/x-www-form-urlencoded (flat) instead of JSON. Driven by the ANNOTATION, not
|
|
20
39
|
* the request Content-Type header — the annotation is the single source of truth.
|
|
21
40
|
*/
|
|
22
|
-
formPost?: boolean
|
|
41
|
+
formPost?: boolean,
|
|
42
|
+
/**
|
|
43
|
+
* True for an @Endpoint(..., { rawBody: true }) route: RETAIN the verbatim bytes + the
|
|
44
|
+
* absolute url on the published {@link HttpRequest}, so an @AuthWebhook hook can verify a
|
|
45
|
+
* vendor signature over what the sender actually transmitted. Also switches the JSON parse
|
|
46
|
+
* failure from "throw now" to "hold it for AuthFilter" — see {@link RawRequest.bodyParseError}.
|
|
47
|
+
*/
|
|
48
|
+
rawBody?: boolean,
|
|
49
|
+
/** The inbound body cap for this route. See {@link MAX_BODY_BYTES}. */
|
|
50
|
+
maxBodyBytes?: number);
|
|
23
51
|
execute(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
24
52
|
executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
25
53
|
executeImpl(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
@@ -35,10 +63,34 @@ export declare class ExpressWrapper {
|
|
|
35
63
|
* in-process with no transport at all.
|
|
36
64
|
*/
|
|
37
65
|
private toWebpiecesRequest;
|
|
66
|
+
/**
|
|
67
|
+
* The absolute url AS THE SENDER ADDRESSED IT — the string a vendor like Twilio signed.
|
|
68
|
+
*
|
|
69
|
+
* `x-forwarded-proto` / `x-forwarded-host` WIN when present, because behind a TLS-terminating
|
|
70
|
+
* proxy (Cloud Run, any load balancer) express's own view is wrong in both halves: `req.protocol`
|
|
71
|
+
* reads `http` and the Host header is the internal one, while the vendor signed the public
|
|
72
|
+
* `https://...` url the customer configured. Reconstructing naively therefore fails 100% of the
|
|
73
|
+
* time in production and works 100% of the time locally — the worst possible pairing, so this is
|
|
74
|
+
* stated here and pinned by a test rather than left to each app.
|
|
75
|
+
*
|
|
76
|
+
* These headers are attacker-controllable when nothing strips them, and that is ACCEPTABLE here
|
|
77
|
+
* precisely because of what the value is used for: a forged url produces a signature that does not
|
|
78
|
+
* verify, i.e. a 401. It grants nothing. (It is used for verification only — never for a redirect.)
|
|
79
|
+
*/
|
|
80
|
+
private absoluteUrl;
|
|
81
|
+
private firstForwarded;
|
|
38
82
|
private readExpressHeaders;
|
|
39
83
|
/**
|
|
40
|
-
* Read raw request body as
|
|
41
|
-
*
|
|
84
|
+
* Read the raw request body as BYTES (we parse manually rather than mounting express.json()).
|
|
85
|
+
*
|
|
86
|
+
* Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that
|
|
87
|
+
* straddles a chunk boundary into two replacement characters, so the body a webhook hook verified
|
|
88
|
+
* would not be the body the vendor signed.
|
|
89
|
+
*
|
|
90
|
+
* REFUSES a body over {@link maxBodyBytes} the moment it crosses the line — the chunks read so far
|
|
91
|
+
* are dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers
|
|
92
|
+
* 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a
|
|
93
|
+
* caller whose request we are refusing to finish reading, and that ordering is the point.
|
|
42
94
|
*/
|
|
43
95
|
private readRequestBody;
|
|
44
96
|
/**
|
package/src/ExpressWrapper.js
CHANGED
|
@@ -1,16 +1,28 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ExpressWrapper = void 0;
|
|
3
|
+
exports.ExpressWrapper = exports.MAX_BODY_BYTES = void 0;
|
|
4
4
|
const core_util_1 = require("@webpieces/core-util");
|
|
5
5
|
const core_context_1 = require("@webpieces/core-context");
|
|
6
6
|
// The logging backend prepends this logger name to every line, so messages below carry NO
|
|
7
7
|
// "[ExpressWrapper]" literal of their own — that would print the name twice.
|
|
8
8
|
const log = core_util_1.LogManager.getLogger('ExpressWrapper');
|
|
9
|
+
/**
|
|
10
|
+
* The cap on an inbound body, in bytes. Reading stops and the request is refused the moment a body
|
|
11
|
+
* crosses it — the bytes already read are dropped, nothing further is buffered.
|
|
12
|
+
*
|
|
13
|
+
* There was NO limit at all before, which was a latent memory DoS on every route and an outright one
|
|
14
|
+
* on a webhook route: `{ rawBody: true }` retains what it reads, and a webhook url is public by
|
|
15
|
+
* construction, so the endpoint most likely to be flooded was also the one that held on to the flood.
|
|
16
|
+
* 10 MiB is comfortably above any api DTO and well under Cloud Run's own 32 MiB request limit.
|
|
17
|
+
*/
|
|
18
|
+
exports.MAX_BODY_BYTES = 10 * 1024 * 1024;
|
|
9
19
|
class ExpressWrapper {
|
|
10
20
|
clientMethod;
|
|
11
21
|
path;
|
|
12
22
|
headers;
|
|
13
23
|
formPost;
|
|
24
|
+
rawBody;
|
|
25
|
+
maxBodyBytes;
|
|
14
26
|
constructor(
|
|
15
27
|
// webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
|
|
16
28
|
clientMethod, path,
|
|
@@ -21,11 +33,22 @@ class ExpressWrapper {
|
|
|
21
33
|
* application/x-www-form-urlencoded (flat) instead of JSON. Driven by the ANNOTATION, not
|
|
22
34
|
* the request Content-Type header — the annotation is the single source of truth.
|
|
23
35
|
*/
|
|
24
|
-
formPost = false
|
|
36
|
+
formPost = false,
|
|
37
|
+
/**
|
|
38
|
+
* True for an @Endpoint(..., { rawBody: true }) route: RETAIN the verbatim bytes + the
|
|
39
|
+
* absolute url on the published {@link HttpRequest}, so an @AuthWebhook hook can verify a
|
|
40
|
+
* vendor signature over what the sender actually transmitted. Also switches the JSON parse
|
|
41
|
+
* failure from "throw now" to "hold it for AuthFilter" — see {@link RawRequest.bodyParseError}.
|
|
42
|
+
*/
|
|
43
|
+
rawBody = false,
|
|
44
|
+
/** The inbound body cap for this route. See {@link MAX_BODY_BYTES}. */
|
|
45
|
+
maxBodyBytes = exports.MAX_BODY_BYTES) {
|
|
25
46
|
this.clientMethod = clientMethod;
|
|
26
47
|
this.path = path;
|
|
27
48
|
this.headers = headers;
|
|
28
49
|
this.formPost = formPost;
|
|
50
|
+
this.rawBody = rawBody;
|
|
51
|
+
this.maxBodyBytes = maxBodyBytes;
|
|
29
52
|
}
|
|
30
53
|
async execute(req, res, next) {
|
|
31
54
|
// MOVED: Wrap entire request in RequestContext.run()
|
|
@@ -46,14 +69,18 @@ class ExpressWrapper {
|
|
|
46
69
|
}
|
|
47
70
|
}
|
|
48
71
|
async executeImpl(req, res, next) {
|
|
49
|
-
// 1.
|
|
50
|
-
const httpRequest = this.toWebpiecesRequest(req);
|
|
51
|
-
// 2. Parse the request body. The PARSER is chosen by the @Endpoint annotation (this.formPost),
|
|
72
|
+
// 1. Parse the request body. The PARSER is chosen by the @Endpoint annotation (this.formPost),
|
|
52
73
|
// NOT the request Content-Type header — the annotation is the single source of truth.
|
|
53
74
|
// webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
|
|
54
75
|
let requestDto = {};
|
|
76
|
+
let raw;
|
|
55
77
|
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
|
56
|
-
|
|
78
|
+
// Read BYTES, not text. Concatenating per-chunk toString() corrupted any multi-byte
|
|
79
|
+
// character that straddled a chunk boundary — invisible on small bodies, and fatal for a
|
|
80
|
+
// signature computed over the bytes.
|
|
81
|
+
const bodyBytes = await this.readRequestBody(req);
|
|
82
|
+
const bodyText = bodyBytes.toString('utf8');
|
|
83
|
+
let parseError;
|
|
57
84
|
if (this.formPost) {
|
|
58
85
|
// application/x-www-form-urlencoded → flat key→value. URLSearchParams is lenient
|
|
59
86
|
// (never throws) — right for EXTERNAL webhooks (e.g. Twilio) that post form-encoded.
|
|
@@ -68,10 +95,21 @@ class ExpressWrapper {
|
|
|
68
95
|
}
|
|
69
96
|
catch (err) {
|
|
70
97
|
const error = (0, core_util_1.toError)(err);
|
|
71
|
-
|
|
98
|
+
// On a raw-body (webhook) route the failure is HELD, not thrown: AuthFilter must
|
|
99
|
+
// answer 401 to an unauthenticated caller rather than 400, because "your JSON was
|
|
100
|
+
// bad" tells that caller it got past auth. Everywhere else, fail now as before.
|
|
101
|
+
if (!this.rawBody) {
|
|
102
|
+
throw new core_util_1.HttpBadRequestError('Request body is not valid JSON', undefined, undefined, error);
|
|
103
|
+
}
|
|
104
|
+
parseError = error;
|
|
72
105
|
}
|
|
73
106
|
}
|
|
107
|
+
if (this.rawBody) {
|
|
108
|
+
raw = new core_context_1.RawRequest(this.absoluteUrl(req), bodyBytes, req.socket?.remoteAddress, parseError);
|
|
109
|
+
}
|
|
74
110
|
}
|
|
111
|
+
// 2. Translate express's request into the transport-neutral HttpRequest webpieces speaks.
|
|
112
|
+
const httpRequest = this.toWebpiecesRequest(req, raw);
|
|
75
113
|
// 3. Publish the transport-neutral HttpRequest, then move its headers into the context and
|
|
76
114
|
// mint a request id if the caller sent none. BOTH happen above the api boundary, because
|
|
77
115
|
// http-routing requires an already-established, already-filled request scope — it never
|
|
@@ -95,8 +133,35 @@ class ExpressWrapper {
|
|
|
95
133
|
* filter chain and controllers never see express, which is what lets the same chain run
|
|
96
134
|
* in-process with no transport at all.
|
|
97
135
|
*/
|
|
98
|
-
toWebpiecesRequest(req) {
|
|
99
|
-
return new core_context_1.HttpRequest(req.method, this.path, this.readExpressHeaders(req));
|
|
136
|
+
toWebpiecesRequest(req, raw) {
|
|
137
|
+
return new core_context_1.HttpRequest(req.method, this.path, this.readExpressHeaders(req), raw);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The absolute url AS THE SENDER ADDRESSED IT — the string a vendor like Twilio signed.
|
|
141
|
+
*
|
|
142
|
+
* `x-forwarded-proto` / `x-forwarded-host` WIN when present, because behind a TLS-terminating
|
|
143
|
+
* proxy (Cloud Run, any load balancer) express's own view is wrong in both halves: `req.protocol`
|
|
144
|
+
* reads `http` and the Host header is the internal one, while the vendor signed the public
|
|
145
|
+
* `https://...` url the customer configured. Reconstructing naively therefore fails 100% of the
|
|
146
|
+
* time in production and works 100% of the time locally — the worst possible pairing, so this is
|
|
147
|
+
* stated here and pinned by a test rather than left to each app.
|
|
148
|
+
*
|
|
149
|
+
* These headers are attacker-controllable when nothing strips them, and that is ACCEPTABLE here
|
|
150
|
+
* precisely because of what the value is used for: a forged url produces a signature that does not
|
|
151
|
+
* verify, i.e. a 401. It grants nothing. (It is used for verification only — never for a redirect.)
|
|
152
|
+
*/
|
|
153
|
+
absoluteUrl(req) {
|
|
154
|
+
const forwardedProto = req.headers['x-forwarded-proto'];
|
|
155
|
+
const forwardedHost = req.headers['x-forwarded-host'];
|
|
156
|
+
// A proxy chain sends a comma-separated list; the FIRST entry is the original client's hop.
|
|
157
|
+
const proto = this.firstForwarded(forwardedProto) ?? req.protocol;
|
|
158
|
+
const host = this.firstForwarded(forwardedHost) ?? req.get('host') ?? '';
|
|
159
|
+
return `${proto}://${host}${req.originalUrl ?? req.url ?? this.path}`;
|
|
160
|
+
}
|
|
161
|
+
firstForwarded(value) {
|
|
162
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
163
|
+
const first = raw?.split(',')[0]?.trim();
|
|
164
|
+
return first === undefined || first === '' ? undefined : first;
|
|
100
165
|
}
|
|
101
166
|
readExpressHeaders(req) {
|
|
102
167
|
const headers = new Map();
|
|
@@ -113,17 +178,37 @@ class ExpressWrapper {
|
|
|
113
178
|
return headers;
|
|
114
179
|
}
|
|
115
180
|
/**
|
|
116
|
-
* Read raw request body as
|
|
117
|
-
*
|
|
181
|
+
* Read the raw request body as BYTES (we parse manually rather than mounting express.json()).
|
|
182
|
+
*
|
|
183
|
+
* Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that
|
|
184
|
+
* straddles a chunk boundary into two replacement characters, so the body a webhook hook verified
|
|
185
|
+
* would not be the body the vendor signed.
|
|
186
|
+
*
|
|
187
|
+
* REFUSES a body over {@link maxBodyBytes} the moment it crosses the line — the chunks read so far
|
|
188
|
+
* are dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers
|
|
189
|
+
* 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a
|
|
190
|
+
* caller whose request we are refusing to finish reading, and that ordering is the point.
|
|
118
191
|
*/
|
|
119
192
|
async readRequestBody(req) {
|
|
120
193
|
return new Promise((resolve, reject) => {
|
|
121
|
-
let
|
|
122
|
-
|
|
123
|
-
|
|
194
|
+
let chunks = [];
|
|
195
|
+
let size = 0;
|
|
196
|
+
// A socket emits Buffers; a stream someone put in string mode (or a test's Readable.from)
|
|
197
|
+
// emits strings. Normalize to bytes ONCE, here, so everything downstream counts and
|
|
198
|
+
// concatenates the same units.
|
|
199
|
+
req.on('data', (data) => {
|
|
200
|
+
const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');
|
|
201
|
+
size += chunk.length;
|
|
202
|
+
if (size > this.maxBodyBytes) {
|
|
203
|
+
chunks = [];
|
|
204
|
+
req.destroy();
|
|
205
|
+
reject(new core_util_1.HttpBadRequestError(`Request body exceeds the ${this.maxBodyBytes} byte limit`));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
chunks.push(chunk);
|
|
124
209
|
});
|
|
125
210
|
req.on('end', () => {
|
|
126
|
-
resolve(
|
|
211
|
+
resolve(Buffer.concat(chunks));
|
|
127
212
|
});
|
|
128
213
|
req.on('error', (err) => {
|
|
129
214
|
reject(err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.ts"],"names":[],"mappings":";;;AACA,oDAgB8B;AAC9B,0DAA6F;AAE7F,0FAA0F;AAC1F,6EAA6E;AAC7E,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;AAEnD,MAAa,cAAc;IAGX;IACA;IAEA;IAMA;IAXZ;IACI,+FAA+F;IACvF,YAAuD,EACvD,IAAY;IACpB,wFAAwF;IAChF,OAA8B;IACtC;;;;OAIG;IACK,WAAoB,KAAK;QATzB,iBAAY,GAAZ,YAAY,CAA2C;QACvD,SAAI,GAAJ,IAAI,CAAQ;QAEZ,YAAO,GAAP,OAAO,CAAuB;QAM9B,aAAQ,GAAR,QAAQ,CAAiB;IAErC,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QAChE,qDAAqD;QACrD,6DAA6D;QAC7D,MAAM,6BAAc,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YA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BAAuB,CAAC;YAChD,GAAG,CAAC,KAAK,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC;YACpC,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;YACnD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QACrF,CAAC;IACL,CAAC;CACJ;AAtND,wCAsNC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ProtocolError,\n ClientRegistry,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n toError,\n LogManager,\n} from '@webpieces/core-util';\nimport { RequestContext, HttpRequest, RequestContextHeaders } from '@webpieces/core-context';\n\n// The logging backend prepends this logger name to every line, so messages below carry NO\n// \"[ExpressWrapper]\" literal of their own — that would print the name twice.\nconst log = LogManager.getLogger('ExpressWrapper');\n\nexport class ExpressWrapper {\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n private clientMethod: (requestDto: unknown) => Promise<unknown>,\n private path: string,\n /** Owns the wire<->context transfer, both directions. Stateless framework singleton. */\n private headers: RequestContextHeaders,\n /**\n * True for an @Endpoint(..., { formPost: true }) route: parse the body as\n * application/x-www-form-urlencoded (flat) instead of JSON. Driven by the ANNOTATION, not\n * the request Content-Type header — the annotation is the single source of truth.\n */\n private formPost: boolean = false,\n ) {\n }\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 // 1. Translate express's request into the transport-neutral HttpRequest webpieces speaks.\n const httpRequest = this.toWebpiecesRequest(req);\n\n // 2. Parse the request body. The PARSER is chosen by the @Endpoint annotation (this.formPost),\n // NOT the request Content-Type header — the annotation is the single source of truth.\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n let requestDto: unknown = {};\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n const bodyText = await this.readRequestBody(req);\n if (this.formPost) {\n // application/x-www-form-urlencoded → flat key→value. URLSearchParams is lenient\n // (never throws) — right for EXTERNAL webhooks (e.g. Twilio) that post form-encoded.\n requestDto = Object.fromEntries(new URLSearchParams(bodyText));\n } else {\n // JSON (default, SYMMETRIC with the client's JSON.stringify). A non-JSON body is a\n // CLIENT error → 400, not the raw 500 an unguarded JSON.parse would throw.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- translate parse failure to a 400 HttpError\n try {\n requestDto = bodyText ? JSON.parse(bodyText) : {};\n } catch (err: unknown) {\n const error = toError(err);\n throw new HttpBadRequestError('Request body is not valid JSON', undefined, undefined, error);\n }\n }\n }\n\n // 3. Publish the transport-neutral HttpRequest, then move its headers into the context and\n // mint a request id if the caller sent none. BOTH happen above the api boundary, because\n // http-routing requires an already-established, already-filled request scope — it never\n // builds one for you. This is the \"translation layer\" every transport must provide.\n this.headers.fillFromRequest(httpRequest);\n\n // 4. Invoke the api CLIENT method — the SAME proxy tests use. Its filter chain + controller\n // run here, reading the context filled above; the chain never touches express `req`.\n const result = await this.clientMethod(requestDto);\n\n // 5. Serialize the response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(result);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\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): HttpRequest {\n return new HttpRequest(req.method, this.path, this.readExpressHeaders(req));\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 raw request body as text.\n * Used to manually parse JSON (instead of express.json() middleware).\n */\n private async readRequestBody(req: Request): Promise<string> {\n return new Promise((resolve: (body: string) => void, reject: (err: Error) => void) => {\n let body = '';\n req.on('data', (chunk: Buffer) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err: Error) => {\n reject(err);\n });\n });\n }\n\n /**\n * Handle errors - translate to JSON ProtocolError (SYMMETRIC with ClientErrorTranslator).\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n * Maps HttpError subclasses to appropriate HTTP status codes and ProtocolError response.\n *\n * Maps all HttpError types (must match ClientErrorTranslator.translateError()):\n * - HttpUserError → 266 (with errorCode)\n * - HttpBadRequestError → 400 (with field, guiAlertMessage)\n * - HttpUnauthorizedError → 401\n * - HttpForbiddenError → 403\n * - HttpNotFoundError → 404\n * - HttpTimeoutError → 408\n * - HttpInternalServerError → 500\n * - HttpBadGatewayError → 502\n * - HttpGatewayTimeoutError → 504\n * - HttpVendorError → 598 (with waitSeconds)\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 // App-registered translations win, so an app can serialize its OWN error types (e.g. a\n // custom 460) AND override built-ins. `undefined` means \"not mine\" — fall through to the\n // built-in instanceof-HttpError ladder below, which stays the generic default. Symmetric\n // with the client's ClientErrorTranslator, which consults tryTranslateFromWire() first.\n if (error instanceof Error) {\n const wire = ClientRegistry.tryTranslateToWire(error);\n if (wire !== undefined) {\n res.status(wire.statusCode)\n .setHeader('Content-Type', 'application/json')\n .send(JSON.stringify(wire.protocolError));\n return;\n }\n }\n\n const protocolError = new ProtocolError();\n\n if (error instanceof HttpError) {\n // Set common fields for all HttpError types\n protocolError.message = error.message;\n protocolError.subType = error.subType;\n protocolError.name = error.name;\n\n // Set type-specific fields (MUST match ClientErrorTranslator)\n if (error instanceof HttpUserError) {\n log.info(`User Error: ${error.message}`);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info(`Bad Request: ${error.message}`);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info(`Not Found: ${error.message}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`Timeout Error: ${error.message}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`Vendor Error: ${error.message}`);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`Unauthorized: ${error.message}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`Forbidden: ${error.message}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`Internal Server Error: ${error.message}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`Bad Gateway: ${error.message}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error(`Gateway Timeout: ${error.message}`);\n } else {\n log.info(`Generic HttpError: ${error.message}`);\n }\n\n // Serialize ProtocolError to JSON (SYMMETRIC with client)\n const responseJson = JSON.stringify(protocolError);\n res.status(error.code).setHeader('Content-Type', 'application/json').send(responseJson);\n } else {\n // Unknown error - 500\n const err = toError(error);\n protocolError.message = 'Internal Server Error';\n log.error('Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ExpressWrapper.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/ExpressWrapper.ts"],"names":[],"mappings":";;;AACA,oDAgB8B;AAC9B,0DAAyG;AAEzG,0FAA0F;AAC1F,6EAA6E;AAC7E,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;AAEnD;;;;;;;;GAQG;AACU,QAAA,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAE/C,MAAa,cAAc;IAGX;IACA;IAEA;IAMA;IAOA;IAEA;IApBZ;IACI,+FAA+F;IACvF,YAAuD,EACvD,IAAY;IACpB,wFAAwF;IAChF,OAA8B;IACtC;;;;OAIG;IACK,WAAoB,KAAK;IACjC;;;;;OAKG;IACK,UAAmB,KAAK;IAChC,uEAAuE;IAC/D,eAAuB,sBAAc;QAlBrC,iBAAY,GAAZ,YAAY,CAA2C;QACvD,SAAI,GAAJ,IAAI,CAAQ;QAEZ,YAAO,GAAP,OAAO,CAAuB;QAM9B,aAAQ,GAAR,QAAQ,CAAiB;QAOzB,YAAO,GAAP,OAAO,CAAiB;QAExB,iBAAY,GAAZ,YAAY,CAAyB;IAEjD,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QAChE,qDAAqD;QACrD,6DAA6D;QAC7D,MAAM,6BAAc,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YAChC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACP,CAAC;IAEM,KAAK,CAAC,eAAe,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QACxE,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,EAAE,CAAC,CAAC;YAC/C,CAAC;iBAAM,IAAI,KAAK,YAAY,mCAAuB,EAAE,CAAC;gBAClD,GAAG,CAAC,KAAK,CAAC,oBAAoB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,CAAC;gBACJ,GAAG,CAAC,IAAI,CAAC,sBAAsB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YACpD,CAAC;YAED,0DAA0D;YAC1D,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;YACnD,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAC5F,CAAC;aAAM,CAAC;YACJ,sBAAsB;YACtB,MAAM,GAAG,GAAG,IAAA,mBAAO,EAAC,KAAK,CAAC,CAAC;YAC3B,aAAa,CAAC,OAAO,GAAG,uBAAuB,CAAC;YAChD,GAAG,CAAC,KAAK,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC;YACpC,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;YACnD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QACrF,CAAC;IACL,CAAC;CACJ;AAjSD,wCAiSC","sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport {\n ProtocolError,\n ClientRegistry,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n toError,\n LogManager,\n} from '@webpieces/core-util';\nimport { RequestContext, HttpRequest, RawRequest, RequestContextHeaders } from '@webpieces/core-context';\n\n// The logging backend prepends this logger name to every line, so messages below carry NO\n// \"[ExpressWrapper]\" literal of their own — that would print the name twice.\nconst log = LogManager.getLogger('ExpressWrapper');\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 */\nexport const MAX_BODY_BYTES = 10 * 1024 * 1024;\n\nexport class ExpressWrapper {\n constructor(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n private clientMethod: (requestDto: unknown) => Promise<unknown>,\n private path: string,\n /** Owns the wire<->context transfer, both directions. Stateless framework singleton. */\n private headers: RequestContextHeaders,\n /**\n * True for an @Endpoint(..., { formPost: true }) route: parse the body as\n * application/x-www-form-urlencoded (flat) instead of JSON. Driven by the ANNOTATION, not\n * the request Content-Type header — the annotation is the single source of truth.\n */\n private formPost: boolean = false,\n /**\n * True for an @Endpoint(..., { rawBody: true }) route: RETAIN the verbatim bytes + the\n * absolute url on the published {@link HttpRequest}, so an @AuthWebhook hook can verify a\n * vendor signature over what the sender actually transmitted. Also switches the JSON parse\n * failure from \"throw now\" to \"hold it for AuthFilter\" — see {@link RawRequest.bodyParseError}.\n */\n private rawBody: boolean = false,\n /** The inbound body cap for this route. See {@link MAX_BODY_BYTES}. */\n private maxBodyBytes: number = MAX_BODY_BYTES,\n ) {\n }\n\n public async execute(req: Request, res: Response, next: NextFunction): Promise<void> {\n // MOVED: Wrap entire request in RequestContext.run()\n // This establishes AsyncLocalStorage context for the request\n await RequestContext.run(async () => {\n await this.executeTryCatch(req, res, next);\n });\n }\n\n public async executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- ExpressWrapper catches errors to translate to HTTP responses\n try {\n await this.executeImpl(req, res, next);\n } catch (err: unknown) {\n const error = toError(err);\n // 5. Handle errors\n this.handleError(res, error);\n }\n }\n\n public async executeImpl(req: Request, res: Response, next: NextFunction): Promise<void> {\n // 1. Parse the request body. The PARSER is chosen by the @Endpoint annotation (this.formPost),\n // NOT the request Content-Type header — the annotation is the single source of truth.\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n let requestDto: unknown = {};\n let raw: RawRequest | undefined;\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\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 let parseError: Error | undefined;\n if (this.formPost) {\n // application/x-www-form-urlencoded → flat key→value. URLSearchParams is lenient\n // (never throws) — right for EXTERNAL webhooks (e.g. Twilio) that post form-encoded.\n requestDto = Object.fromEntries(new URLSearchParams(bodyText));\n } else {\n // JSON (default, SYMMETRIC with the client's JSON.stringify). A non-JSON body is a\n // CLIENT error → 400, not the raw 500 an unguarded JSON.parse would throw.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- translate parse failure to a 400 HttpError\n try {\n requestDto = bodyText ? JSON.parse(bodyText) : {};\n } catch (err: unknown) {\n const error = toError(err);\n // On a raw-body (webhook) route the failure is HELD, not thrown: AuthFilter must\n // answer 401 to an unauthenticated caller rather than 400, because \"your JSON was\n // bad\" tells that caller it got past auth. Everywhere else, fail now as before.\n if (!this.rawBody) {\n throw new HttpBadRequestError('Request body is not valid JSON', undefined, undefined, error);\n }\n parseError = error;\n }\n }\n if (this.rawBody) {\n raw = new RawRequest(this.absoluteUrl(req), bodyBytes, req.socket?.remoteAddress, parseError);\n }\n }\n\n // 2. Translate express's request into the transport-neutral HttpRequest webpieces speaks.\n const httpRequest = this.toWebpiecesRequest(req, raw);\n\n // 3. Publish the transport-neutral HttpRequest, then move its headers into the context and\n // mint a request id if the caller sent none. BOTH happen above the api boundary, because\n // http-routing requires an already-established, already-filled request scope — it never\n // builds one for you. This is the \"translation layer\" every transport must provide.\n this.headers.fillFromRequest(httpRequest);\n\n // 4. Invoke the api CLIENT method — the SAME proxy tests use. Its filter chain + controller\n // run here, reading the context filled above; the chain never touches express `req`.\n const result = await this.clientMethod(requestDto);\n\n // 5. Serialize the response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(result);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n\n /**\n * Read HTTP headers from Express request.\n * Returns Map of header name (lowercase) -> array of values.\n *\n * HTTP spec allows multiple values for same header name.\n */\n /**\n * express Request -> webpieces {@link HttpRequest}. THE translation layer: below this line the\n * filter chain and controllers never see express, which is what lets the same chain run\n * in-process with no transport at all.\n */\n private toWebpiecesRequest(req: Request, raw?: RawRequest): HttpRequest {\n return new HttpRequest(req.method, this.path, this.readExpressHeaders(req), raw);\n }\n\n /**\n * The absolute url AS THE SENDER ADDRESSED IT — the string a vendor like Twilio signed.\n *\n * `x-forwarded-proto` / `x-forwarded-host` WIN when present, because behind a TLS-terminating\n * proxy (Cloud Run, any load balancer) express's own view is wrong in both halves: `req.protocol`\n * reads `http` and the Host header is the internal one, while the vendor signed the public\n * `https://...` url the customer configured. Reconstructing naively therefore fails 100% of the\n * time in production and works 100% of the time locally — the worst possible pairing, so this is\n * stated here and pinned by a test rather than left to each app.\n *\n * These headers are attacker-controllable when nothing strips them, and that is ACCEPTABLE here\n * precisely because of what the value is used for: a forged url produces a signature that does not\n * verify, i.e. a 401. It grants nothing. (It is used for verification only — never for a redirect.)\n */\n private absoluteUrl(req: Request): string {\n const forwardedProto = req.headers['x-forwarded-proto'];\n const forwardedHost = req.headers['x-forwarded-host'];\n // A proxy chain sends a comma-separated list; the FIRST entry is the original client's hop.\n const proto = this.firstForwarded(forwardedProto) ?? req.protocol;\n const host = this.firstForwarded(forwardedHost) ?? req.get('host') ?? '';\n return `${proto}://${host}${req.originalUrl ?? req.url ?? this.path}`;\n }\n\n private firstForwarded(value: string | string[] | undefined): string | undefined {\n const raw = Array.isArray(value) ? value[0] : value;\n const first = raw?.split(',')[0]?.trim();\n return first === undefined || first === '' ? undefined : first;\n }\n\n private readExpressHeaders(req: Request): Map<string, string[]> {\n const headers = new Map<string, string[]>();\n\n // Express stores headers in req.headers as Record<string, string | string[]>\n for (const [name, value] of Object.entries(req.headers)) {\n const lowerName = name.toLowerCase();\n\n if (typeof value === 'string') {\n headers.set(lowerName, [value]);\n } else if (Array.isArray(value)) {\n headers.set(lowerName, value);\n }\n }\n\n return headers;\n }\n\n /**\n * Read the raw request body as BYTES (we parse manually rather than mounting express.json()).\n *\n * Bytes, not a growing string: a per-chunk `toString()` splits any multi-byte character that\n * straddles a chunk boundary into two replacement characters, so the body a webhook hook verified\n * would not be the body the vendor signed.\n *\n * REFUSES a body over {@link maxBodyBytes} the moment it crosses the line — the chunks read so far\n * are dropped and the stream is destroyed, so an oversize body is never fully buffered. It answers\n * 400 rather than 401 even on a webhook route, unavoidably: there is no way to authenticate a\n * caller whose request we are refusing to finish reading, and that ordering is the point.\n */\n private async readRequestBody(req: Request): Promise<Buffer> {\n return new Promise((resolve: (body: Buffer) => void, reject: (err: Error) => void) => {\n let chunks: Buffer[] = [];\n let size = 0;\n // A socket emits Buffers; a stream someone put in string mode (or a test's Readable.from)\n // emits strings. Normalize to bytes ONCE, here, so everything downstream counts and\n // concatenates the same units.\n req.on('data', (data: Buffer | string) => {\n const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');\n size += chunk.length;\n if (size > this.maxBodyBytes) {\n chunks = [];\n req.destroy();\n reject(new HttpBadRequestError(\n `Request body exceeds the ${this.maxBodyBytes} byte limit`,\n ));\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n resolve(Buffer.concat(chunks));\n });\n req.on('error', (err: Error) => {\n reject(err);\n });\n });\n }\n\n /**\n * Handle errors - translate to JSON ProtocolError (SYMMETRIC with ClientErrorTranslator).\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n * Maps HttpError subclasses to appropriate HTTP status codes and ProtocolError response.\n *\n * Maps all HttpError types (must match ClientErrorTranslator.translateError()):\n * - HttpUserError → 266 (with errorCode)\n * - HttpBadRequestError → 400 (with field, guiAlertMessage)\n * - HttpUnauthorizedError → 401\n * - HttpForbiddenError → 403\n * - HttpNotFoundError → 404\n * - HttpTimeoutError → 408\n * - HttpInternalServerError → 500\n * - HttpBadGatewayError → 502\n * - HttpGatewayTimeoutError → 504\n * - HttpVendorError → 598 (with waitSeconds)\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 // App-registered translations win, so an app can serialize its OWN error types (e.g. a\n // custom 460) AND override built-ins. `undefined` means \"not mine\" — fall through to the\n // built-in instanceof-HttpError ladder below, which stays the generic default. Symmetric\n // with the client's ClientErrorTranslator, which consults tryTranslateFromWire() first.\n if (error instanceof Error) {\n const wire = ClientRegistry.tryTranslateToWire(error);\n if (wire !== undefined) {\n res.status(wire.statusCode)\n .setHeader('Content-Type', 'application/json')\n .send(JSON.stringify(wire.protocolError));\n return;\n }\n }\n\n const protocolError = new ProtocolError();\n\n if (error instanceof HttpError) {\n // Set common fields for all HttpError types\n protocolError.message = error.message;\n protocolError.subType = error.subType;\n protocolError.name = error.name;\n\n // Set type-specific fields (MUST match ClientErrorTranslator)\n if (error instanceof HttpUserError) {\n log.info(`User Error: ${error.message}`);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info(`Bad Request: ${error.message}`);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info(`Not Found: ${error.message}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`Timeout Error: ${error.message}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`Vendor Error: ${error.message}`);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`Unauthorized: ${error.message}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`Forbidden: ${error.message}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`Internal Server Error: ${error.message}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`Bad Gateway: ${error.message}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error(`Gateway Timeout: ${error.message}`);\n } else {\n log.info(`Generic HttpError: ${error.message}`);\n }\n\n // Serialize ProtocolError to JSON (SYMMETRIC with client)\n const responseJson = JSON.stringify(protocolError);\n res.status(error.code).setHeader('Content-Type', 'application/json').send(responseJson);\n } else {\n // Unknown error - 500\n const err = toError(error);\n protocolError.message = 'Internal Server Error';\n log.error('Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n"]}
|
|
@@ -119,8 +119,9 @@ class WebpiecesExpressRouter {
|
|
|
119
119
|
let count = 0;
|
|
120
120
|
for (const [methodName, endpointPath] of Object.entries(endpoints)) {
|
|
121
121
|
const path = basePath + endpointPath;
|
|
122
|
-
// The parser is chosen by the @Endpoint annotation, not the request Content-Type
|
|
123
|
-
|
|
122
|
+
// The parser is chosen by the @Endpoint annotation, not the request Content-Type — and
|
|
123
|
+
// so is whether the verbatim bytes survive the parse for an @AuthWebhook hook to verify.
|
|
124
|
+
const wrapper = this.middleware.createExpressWrapper(apiClient.client[methodName], path, (0, http_routing_1.isFormPost)(apiClient.api, methodName), (0, http_routing_1.isRawBody)(apiClient.api, methodName));
|
|
124
125
|
// All webpieces routes are POST (the api-tier convention).
|
|
125
126
|
this.registerHandler(app, 'POST', path, wrapper.execute.bind(wrapper));
|
|
126
127
|
count++;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebpiecesExpressRouter.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IAAI,CAAC,UAAU,CAAC,oBAAoB,CAChD,SAAS,CAAC,MAAM,CAAC,UAAU,CAAC,EAC5B,IAAI,EACJ,IAAA,yBAAU,EAAC,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CACxC,CAAC;YACF,2DAA2D;YAC3D,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;YACvE,KAAK,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,eAAe,CACnB,GAAY,EACZ,UAAkB,EAClB,IAAY,EACZ,cAAmC;QAEnC,QAAQ,UAAU,CAAC,WAAW,EAAE,EAAE,CAAC;YAC/B,KAAK,KAAK;gBACN,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,MAAM;gBACP,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC/B,MAAM;YACV,KAAK,KAAK;gBACN,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,QAAQ;gBACT,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACjC,MAAM;YACV,KAAK,OAAO;gBACR,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAChC,MAAM;YACV;gBACI,GAAG,CAAC,IAAI,CAAC,wBAAwB,UAAU,EAAE,CAAC,CAAC;QACvD,CAAC;IACL,CAAC;CACJ;AA/ID,wDA+IC","sourcesContent":["import { Express } from 'express';\nimport { ApiFactory, ApiClient, getApiPath, getEndpoints, isFormPost, WebpiecesConfig } from '@webpieces/http-routing';\nimport { LogManager } from '@webpieces/core-util';\nimport { WebpiecesMiddleware, ExpressRouteHandler } from './WebpiecesMiddleware';\n\nconst log = LogManager.getLogger('WebpiecesExpressRouter');\n\n/** The value returned by express `app.listen(...)` (a node http.Server). */\ntype HttpServer = ReturnType<Express['listen']>;\n\n/**\n * WebpiecesExpressRouter - the express layer that sits ON TOP of a node-only\n * {@link ApiFactory} (a WebpiecesRouter). It is the ONLY place express lifecycle lives.\n *\n * It never reaches into routing internals: it asks the ApiFactory for `apiClients()` — each\n * an api + routeMeta + composed filter-chain→controller impl — and binds each to an express\n * route (`app.<verb>(path, handler)`) invoked when the matching HTTP request arrives. The\n * RouteBuilder stays hidden inside the ApiFactory.\n *\n * ```typescript\n * const apiFactory = await WebpiecesRouterFactory.create(config, { appBindings });\n * apiFactory.addRoutes(SaveApi, SaveController);\n * const express = new WebpiecesExpressRouter(apiFactory);\n *\n * // legacy / side-by-side: mount onto an existing app; you own listen + your middleware\n * express.bindExpress(existingApp);\n *\n * // non-legacy: add webpieces global middleware + listen for you\n * await express.bindAndStartExpress(express(), 8080);\n * ```\n */\nexport class WebpiecesExpressRouter {\n private readonly middleware = new WebpiecesMiddleware();\n\n constructor(private readonly apiFactory: ApiFactory) {}\n\n /**\n * Mount the webpieces routes (each fully self-contained: own body parse, RequestContext,\n * express-tier + api-tier filter chain, error→JSON) onto the caller's express app.\n *\n * Adds NO global app.use() middleware, so it is safe to attach to a legacy app whose other\n * routes must stay untouched. The caller owns app.listen() and any global middleware.\n */\n bindExpress(app: Express): void {\n let count = 0;\n for (const apiClient of this.apiFactory.apiClients()) {\n count += this.mountApiClient(app, apiClient);\n }\n log.info(`Mounted ${count} webpieces route(s) onto express`);\n }\n\n /**\n * Add the webpieces global middleware (optional CORS), bind the routes, mount the top-level\n * error handler AFTER them, then app.listen(port). Convenience for a non-legacy webpieces server where\n * webpieces owns the whole express app. Resolves with the http.Server once listening.\n *\n * CORS is mounted ONLY when `config.corsOrigins` is non-empty — see the note below and\n * {@link WebpiecesMiddleware.corsMiddleware}.\n */\n async bindAndStartExpress(\n app: Express,\n port: number = 8080,\n config?: WebpiecesConfig,\n ): Promise<HttpServer> {\n // Global middleware layers (outermost first) — only for a webpieces-owned app.\n // CORS is OPT-IN, and stays OFF in production. A server that serves its own browser app does\n // not need it — a browser applies no cors check to a same-origin request — so mounting it\n // would only hand credentialed cross-origin read access to whatever it allows, for nothing.\n // It is needed solely when a browser on ANOTHER origin calls this api: `ng serve` in dev, or\n // a UI hosted on a different host. Those say so via corsOrigins.\n const corsOrigins = config?.corsOrigins ?? [];\n if (corsOrigins.length > 0) {\n app.use(this.middleware.corsMiddleware(config));\n }\n\n this.bindExpress(app);\n\n // Top-level error handler is mounted LAST (AFTER the routes). Express only forwards a\n // downstream failure to a 4-arg error middleware that sits BELOW the failing route — it does\n // NOT bubble errors back up through next(). See WebpiecesMiddleware.errorHandler.\n app.use(this.middleware.errorHandler.bind(this.middleware));\n\n return new Promise<HttpServer>(\n (resolve: (server: HttpServer) => void, reject: (err: Error) => void) => {\n const server: HttpServer = app.listen(port, (error?: Error) => {\n if (error) {\n log.error(`Failed to start on port ${port}:`, error);\n reject(error);\n return;\n }\n log.info(`Listening on http://localhost:${port}`);\n this.logStartupBanner(port);\n resolve(server);\n });\n },\n );\n }\n\n /**\n * The \"Svr Ready!!\" ASCII banner, LOCAL DEV ONLY (skipped on Cloud Run, where `K_SERVICE` is set and\n * every line becomes its own structured log entry — a multi-line banner there is pure noise). Copied\n * verbatim from the production service it was ported from, so a familiar splash marks \"the server is up and reachable\".\n */\n private logStartupBanner(port: number): void {\n if (process.env['K_SERVICE']) {\n return;\n }\n log.info(`\n ___ _____ _\n/ _| | _ \\\\ | |\n\\\\ \\`--. _ _ ___ ___ _ _ | |_/ /_ _ _ _| |_ _\n \\`--. \\\\/ _ \\\\ '_\\\\ \\\\ / / _ \\\\ '_| | // _ \\\\/ _\\` |/ _\\` | | | |\n/\\\\_/ / _/ | \\\\ V / _/ | | |\\\\ \\\\ _/ (_| | (_| | |_| |\n\\\\___/ \\\\_|_| \\\\_/ \\\\_|_| \\\\_| \\\\_\\\\_|\\\\_,_|\\\\_,_|\\\\_, |\n _/ |\n |_/\n\n Svr Ready!! port=${port}\n`);\n }\n\n /**\n * Bind EACH method of one ApiClient. The api's @ApiPath/@Endpoint decorators give the paths;\n * for each we wrap the matching client method (the proxy — RequestContext.run + header read +\n * JSON body parse + error→ProtocolError all live in the wrapper/chain) and register the route.\n * This is one-to-one with a test: an HTTP POST maps straight to `client[method](dto)`.\n *\n * @returns the number of routes mounted for this api.\n */\n private mountApiClient(app: Express, apiClient: ApiClient): number {\n const basePath = getApiPath(apiClient.api) || '';\n const endpoints = getEndpoints(apiClient.api) || {};\n let count = 0;\n for (const [methodName, endpointPath] of Object.entries(endpoints)) {\n const path = basePath + endpointPath;\n // The parser is chosen by the @Endpoint annotation, not the request Content-Type.\n const wrapper = this.middleware.createExpressWrapper(\n apiClient.client[methodName],\n path,\n isFormPost(apiClient.api, methodName),\n );\n // All webpieces routes are POST (the api-tier convention).\n this.registerHandler(app, 'POST', path, wrapper.execute.bind(wrapper));\n count++;\n }\n return count;\n }\n\n private registerHandler(\n app: Express,\n httpMethod: string,\n path: string,\n expressHandler: ExpressRouteHandler,\n ): void {\n switch (httpMethod.toLowerCase()) {\n case 'get':\n app.get(path, expressHandler);\n break;\n case 'post':\n app.post(path, expressHandler);\n break;\n case 'put':\n app.put(path, expressHandler);\n break;\n case 'delete':\n app.delete(path, expressHandler);\n break;\n case 'patch':\n app.patch(path, expressHandler);\n break;\n default:\n log.warn(`Unknown HTTP method: ${httpMethod}`);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"WebpiecesExpressRouter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesExpressRouter.ts"],"names":[],"mappings":";;;AACA,0DAAkI;AAClI,oDAAkD;AAClD,+DAAiF;AAEjF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAK3D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,sBAAsB;IAGF;IAF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C3D,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;YACvE,KAAK,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,eAAe,CACnB,GAAY,EACZ,UAAkB,EAClB,IAAY,EACZ,cAAmC;QAEnC,QAAQ,UAAU,CAAC,WAAW,EAAE,EAAE,CAAC;YAC/B,KAAK,KAAK;gBACN,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,MAAM;gBACP,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC/B,MAAM;YACV,KAAK,KAAK;gBACN,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAC9B,MAAM;YACV,KAAK,QAAQ;gBACT,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACjC,MAAM;YACV,KAAK,OAAO;gBACR,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBAChC,MAAM;YACV;gBACI,GAAG,CAAC,IAAI,CAAC,wBAAwB,UAAU,EAAE,CAAC,CAAC;QACvD,CAAC;IACL,CAAC;CACJ;AAjJD,wDAiJC","sourcesContent":["import { Express } from 'express';\nimport { ApiFactory, ApiClient, getApiPath, getEndpoints, isFormPost, isRawBody, WebpiecesConfig } from '@webpieces/http-routing';\nimport { LogManager } from '@webpieces/core-util';\nimport { WebpiecesMiddleware, ExpressRouteHandler } from './WebpiecesMiddleware';\n\nconst log = LogManager.getLogger('WebpiecesExpressRouter');\n\n/** The value returned by express `app.listen(...)` (a node http.Server). */\ntype HttpServer = ReturnType<Express['listen']>;\n\n/**\n * WebpiecesExpressRouter - the express layer that sits ON TOP of a node-only\n * {@link ApiFactory} (a WebpiecesRouter). It is the ONLY place express lifecycle lives.\n *\n * It never reaches into routing internals: it asks the ApiFactory for `apiClients()` — each\n * an api + routeMeta + composed filter-chain→controller impl — and binds each to an express\n * route (`app.<verb>(path, handler)`) invoked when the matching HTTP request arrives. The\n * RouteBuilder stays hidden inside the ApiFactory.\n *\n * ```typescript\n * const apiFactory = await WebpiecesRouterFactory.create(config, { appBindings });\n * apiFactory.addRoutes(SaveApi, SaveController);\n * const express = new WebpiecesExpressRouter(apiFactory);\n *\n * // legacy / side-by-side: mount onto an existing app; you own listen + your middleware\n * express.bindExpress(existingApp);\n *\n * // non-legacy: add webpieces global middleware + listen for you\n * await express.bindAndStartExpress(express(), 8080);\n * ```\n */\nexport class WebpiecesExpressRouter {\n private readonly middleware = new WebpiecesMiddleware();\n\n constructor(private readonly apiFactory: ApiFactory) {}\n\n /**\n * Mount the webpieces routes (each fully self-contained: own body parse, RequestContext,\n * express-tier + api-tier filter chain, error→JSON) onto the caller's express app.\n *\n * Adds NO global app.use() middleware, so it is safe to attach to a legacy app whose other\n * routes must stay untouched. The caller owns app.listen() and any global middleware.\n */\n bindExpress(app: Express): void {\n let count = 0;\n for (const apiClient of this.apiFactory.apiClients()) {\n count += this.mountApiClient(app, apiClient);\n }\n log.info(`Mounted ${count} webpieces route(s) onto express`);\n }\n\n /**\n * Add the webpieces global middleware (optional CORS), bind the routes, mount the top-level\n * error handler AFTER them, then app.listen(port). Convenience for a non-legacy webpieces server where\n * webpieces owns the whole express app. Resolves with the http.Server once listening.\n *\n * CORS is mounted ONLY when `config.corsOrigins` is non-empty — see the note below and\n * {@link WebpiecesMiddleware.corsMiddleware}.\n */\n async bindAndStartExpress(\n app: Express,\n port: number = 8080,\n config?: WebpiecesConfig,\n ): Promise<HttpServer> {\n // Global middleware layers (outermost first) — only for a webpieces-owned app.\n // CORS is OPT-IN, and stays OFF in production. A server that serves its own browser app does\n // not need it — a browser applies no cors check to a same-origin request — so mounting it\n // would only hand credentialed cross-origin read access to whatever it allows, for nothing.\n // It is needed solely when a browser on ANOTHER origin calls this api: `ng serve` in dev, or\n // a UI hosted on a different host. Those say so via corsOrigins.\n const corsOrigins = config?.corsOrigins ?? [];\n if (corsOrigins.length > 0) {\n app.use(this.middleware.corsMiddleware(config));\n }\n\n this.bindExpress(app);\n\n // Top-level error handler is mounted LAST (AFTER the routes). Express only forwards a\n // downstream failure to a 4-arg error middleware that sits BELOW the failing route — it does\n // NOT bubble errors back up through next(). See WebpiecesMiddleware.errorHandler.\n app.use(this.middleware.errorHandler.bind(this.middleware));\n\n return new Promise<HttpServer>(\n (resolve: (server: HttpServer) => void, reject: (err: Error) => void) => {\n const server: HttpServer = app.listen(port, (error?: Error) => {\n if (error) {\n log.error(`Failed to start on port ${port}:`, error);\n reject(error);\n return;\n }\n log.info(`Listening on http://localhost:${port}`);\n this.logStartupBanner(port);\n resolve(server);\n });\n },\n );\n }\n\n /**\n * The \"Svr Ready!!\" ASCII banner, LOCAL DEV ONLY (skipped on Cloud Run, where `K_SERVICE` is set and\n * every line becomes its own structured log entry — a multi-line banner there is pure noise). Copied\n * verbatim from the production service it was ported from, so a familiar splash marks \"the server is up and reachable\".\n */\n private logStartupBanner(port: number): void {\n if (process.env['K_SERVICE']) {\n return;\n }\n log.info(`\n ___ _____ _\n/ _| | _ \\\\ | |\n\\\\ \\`--. _ _ ___ ___ _ _ | |_/ /_ _ _ _| |_ _\n \\`--. \\\\/ _ \\\\ '_\\\\ \\\\ / / _ \\\\ '_| | // _ \\\\/ _\\` |/ _\\` | | | |\n/\\\\_/ / _/ | \\\\ V / _/ | | |\\\\ \\\\ _/ (_| | (_| | |_| |\n\\\\___/ \\\\_|_| \\\\_/ \\\\_|_| \\\\_| \\\\_\\\\_|\\\\_,_|\\\\_,_|\\\\_, |\n _/ |\n |_/\n\n Svr Ready!! port=${port}\n`);\n }\n\n /**\n * Bind EACH method of one ApiClient. The api's @ApiPath/@Endpoint decorators give the paths;\n * for each we wrap the matching client method (the proxy — RequestContext.run + header read +\n * JSON body parse + error→ProtocolError all live in the wrapper/chain) and register the route.\n * This is one-to-one with a test: an HTTP POST maps straight to `client[method](dto)`.\n *\n * @returns the number of routes mounted for this api.\n */\n private mountApiClient(app: Express, apiClient: ApiClient): number {\n const basePath = getApiPath(apiClient.api) || '';\n const endpoints = getEndpoints(apiClient.api) || {};\n let count = 0;\n for (const [methodName, endpointPath] of Object.entries(endpoints)) {\n const path = basePath + endpointPath;\n // The parser is chosen by the @Endpoint annotation, not the request Content-Type — and\n // so is whether the verbatim bytes survive the parse for an @AuthWebhook hook to verify.\n const wrapper = this.middleware.createExpressWrapper(\n apiClient.client[methodName],\n path,\n isFormPost(apiClient.api, methodName),\n isRawBody(apiClient.api, methodName),\n );\n // All webpieces routes are POST (the api-tier convention).\n this.registerHandler(app, 'POST', path, wrapper.execute.bind(wrapper));\n count++;\n }\n return count;\n }\n\n private registerHandler(\n app: Express,\n httpMethod: string,\n path: string,\n expressHandler: ExpressRouteHandler,\n ): void {\n switch (httpMethod.toLowerCase()) {\n case 'get':\n app.get(path, expressHandler);\n break;\n case 'post':\n app.post(path, expressHandler);\n break;\n case 'put':\n app.put(path, expressHandler);\n break;\n case 'delete':\n app.delete(path, expressHandler);\n break;\n case 'patch':\n app.patch(path, expressHandler);\n break;\n default:\n log.warn(`Unknown HTTP method: ${httpMethod}`);\n }\n }\n}\n"]}
|
|
@@ -106,7 +106,10 @@ export declare class WebpiecesMiddleware {
|
|
|
106
106
|
* @param path - The route path (used to build the HttpRequest).
|
|
107
107
|
* @param formPost - True for an @Endpoint(..., { formPost: true }) route (parse body as
|
|
108
108
|
* urlencoded, not JSON). Default false = JSON.
|
|
109
|
+
* @param rawBody - True for an @Endpoint(..., { rawBody: true }) route: retain the verbatim
|
|
110
|
+
* bytes + absolute url on the HttpRequest so an @AuthWebhook hook can verify a vendor
|
|
111
|
+
* signature over them. Default false = the bytes are dropped once parsed.
|
|
109
112
|
* @returns ExpressWrapper instance
|
|
110
113
|
*/
|
|
111
|
-
createExpressWrapper(clientMethod: (requestDto: unknown) => Promise<unknown>, path: string, formPost?: boolean): ExpressWrapper;
|
|
114
|
+
createExpressWrapper(clientMethod: (requestDto: unknown) => Promise<unknown>, path: string, formPost?: boolean, rawBody?: boolean): ExpressWrapper;
|
|
112
115
|
}
|
|
@@ -189,12 +189,15 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
|
189
189
|
* @param path - The route path (used to build the HttpRequest).
|
|
190
190
|
* @param formPost - True for an @Endpoint(..., { formPost: true }) route (parse body as
|
|
191
191
|
* urlencoded, not JSON). Default false = JSON.
|
|
192
|
+
* @param rawBody - True for an @Endpoint(..., { rawBody: true }) route: retain the verbatim
|
|
193
|
+
* bytes + absolute url on the HttpRequest so an @AuthWebhook hook can verify a vendor
|
|
194
|
+
* signature over them. Default false = the bytes are dropped once parsed.
|
|
192
195
|
* @returns ExpressWrapper instance
|
|
193
196
|
*/
|
|
194
197
|
createExpressWrapper(
|
|
195
198
|
// webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary
|
|
196
|
-
clientMethod, path, formPost = false) {
|
|
197
|
-
return new ExpressWrapper_1.ExpressWrapper(clientMethod, path, this.headers, formPost);
|
|
199
|
+
clientMethod, path, formPost = false, rawBody = false) {
|
|
200
|
+
return new ExpressWrapper_1.ExpressWrapper(clientMethod, path, this.headers, formPost, rawBody);
|
|
198
201
|
}
|
|
199
202
|
};
|
|
200
203
|
exports.WebpiecesMiddleware = WebpiecesMiddleware;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,0DAAqF;AACrF,oDAA+C;AAC/C,0DAAgE;AAChE,oDAAkD;AAClD,qDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AACxD,iGAAiG;AACjG,+FAA+F;AA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OAAe,EAAW,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAClG,CAAC;IAED;;;;;;;OAOG;IACK,aAAa,CAAC,MAAc,EAAE,OAAe;QACjD,IAAI,OAAO,KAAK,MAAM,EAAE,CAAC;YACrB,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,MAAM,cAAc,GAAG,IAAI,CAAC;QAC5B,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;YACpC,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC;YACnC,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC7C,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED;;;;;;;;;;;OAWG;IACH,oBAAoB;IAChB,+FAA+F;IAC/F,YAAuD,EACvD,IAAY,EACZ,WAAoB,KAAK;QAEzB,OAAO,IAAI,+BAAc,CAAC,YAAY,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC1E,CAAC;CACJ,CAAA;AA1KY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;GACf,mBAAmB,CA0K/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { ExpressWrapper } from './ExpressWrapper';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n// CORS mount/allow/block lines log under their own name (not [WebpiecesMiddleware]); the backend\n// prepends \"[CORS]\" for us, so the message strings below carry no literal prefix of their own.\nconst corsLog = LogManager.getLogger('CORS');\n\n/**\n * Express route handler function type. Lives in http-server (the express adapter),\n * NOT in the node-only http-routing package, so http-routing stays express-free.\n * Used by WebpiecesExpressRouter to register handlers Express can call.\n */\nexport type ExpressRouteHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => Promise<void>;\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. errorHandler - Top-level 4-arg error middleware, returns HTML 500 page. Mounted AFTER the\n * routes so express can forward downstream failures to it (express routes errors DOWN a\n * separate pipeline, it does not bubble them back up through next()). Last-resort net only:\n * api routes translate their own errors to JSON inside the filter chain (ExpressWrapper).\n * 2. corsMiddleware - Opt-in CORS (mounted only when corsOrigins is non-empty).\n *\n * Per-request logging is intentionally NOT here — the api filter chain's LogApiCall already logs\n * every request/response with full context (requestId, method, path, body), so a plain express\n * START/END line would only duplicate it with less information.\n *\n * Route dispatch happens via Express's registered route handlers (the per-route ExpressWrapper),\n * NOT via this middleware.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideFrameworkSingleton()\nexport class WebpiecesMiddleware {\n /** The ONE wire<->context transfer, handed to every route's ExpressWrapper. Stateless. */\n private readonly headers = new RequestContextHeaders();\n\n\n /**\n * Top-level error handler — the last-ditch catch-all. MUST be mounted AFTER all routes (see\n * {@link WebpiecesExpressRouter}). The 4-argument `(err, req, res, next)` signature is what\n * tells express this is an error-handling middleware: express's router forwards ANY downstream\n * failure to it — synchronous throws AND rejected async-handler promises alike (the router does\n * `promise.then(null, err => next(err))`, and a `next(err)` with a truthy arg jumps straight to\n * the first 4-arg middleware). This is why a `try { await next() } catch` wrapper is NOT needed\n * (and would not work) — express `next()` is not promise-aware, so it never hands the parent the\n * downstream promise; errors travel down this separate pipeline instead of bubbling back up.\n *\n * Returns an HTML 500 page. Api routes translate their own errors to JSON inside the filter\n * chain (JsonFilter/ExpressWrapper), so this normally only fires for failures OUTSIDE a route\n * (body parsing, unmatched paths, a bug in the wrapper itself).\n */\n // webpieces-disable no-any-unknown -- a thrown/forwarded express error is genuinely unknown until narrowed\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- express needs the 4-arg (err,req,res,next) arity to recognize this as error-handling middleware\n errorHandler(err: unknown, req: Request, res: Response, next: NextFunction): void {\n const error = toError(err);\n log.error(`Unhandled error: ${req.method} ${req.path}`, error);\n if (res.headersSent) {\n return;\n }\n // Return HTML error page (not JSON - api routes translate JSON errors in their filter chain)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n <pre>${error.message}</pre>\n </body>\n </html>\n `);\n }\n\n /**\n * CORS middleware. DO NOT MOUNT UNCONDITIONALLY — {@link WebpiecesExpressRouter.bindAndStartExpress}\n * mounts it ONLY when {@link WebpiecesConfig.corsOrigins} is non-empty, and that is the point.\n *\n * CORS exists solely to let a browser on a DIFFERENT origin call this api — in practice\n * `ng serve` on :4200 hitting an api on :8080 during development, or a UI hosted on a different\n * host than the api. A server that serves its own browser app needs NO cors at all, because a\n * browser does not apply cors to a same-origin request. So in production this middleware is\n * normally ABSENT, and absent is the safe state: every origin it allows gains the right to make\n * CREDENTIALED cross-origin calls and READ the responses. Mounting it unconditionally (as the\n * old corsForLocalhost did) handed that right to anything on the victim's localhost, in prod,\n * for no benefit whatsoever.\n *\n * When mounted, allows: a request with NO Origin (curl, server-to-server, a CLI); the server's\n * OWN origin; and EXACTLY the origins in `corsOrigins` — nothing is implicit. Anything else gets\n * a clean 403, never the HTML 500 the old `callback(new Error(...))` produced.\n *\n * SAME-ORIGIN MUST STAY ALLOWED even though a same-origin request needs no cors headers, because\n * a browser attaches an `Origin` header to EVERY POST — including a same-origin POST — and every\n * webpieces route is a POST. Once mounted, this middleware SEES that origin, so if it did not\n * allow it, it would 403 the server's own UI. That was the production bug.\n *\n * The same-origin test compares HOST ONLY, deliberately. Behind a TLS-terminating proxy (Cloud\n * Run, any load balancer) `req.protocol` is `http` while the browser's `Origin` says `https`, so\n * comparing full origins would reject the server's own origin on every deploy.\n *\n * @returns Express middleware handler for CORS\n */\n corsMiddleware(config?: WebpiecesConfig): RequestHandler {\n const allowedOrigins = config?.corsOrigins ?? [];\n corsLog.info(\n `CORS MOUNTED. Allowing same-origin + [${allowedOrigins.join(', ')}]. ` +\n `Every other browser origin gets a 403.`,\n );\n\n const handler = cors({\n origin: true, // reflect the request origin — we have already vetted it below\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*',\n exposedHeaders: '*',\n maxAge: 3600,\n });\n\n return (req: Request, res: Response, next: NextFunction): void => {\n const origin = req.headers.origin;\n if (!origin) {\n // No Origin -> not a browser cross-origin request; nothing to negotiate.\n next();\n return;\n }\n if (this.isOriginAllowed(origin, req.get('host'), allowedOrigins)) {\n handler(req, res, next);\n return;\n }\n corsLog.info(`Blocked origin: ${origin}`);\n res.status(403).json({\n name: 'CorsError',\n message: `CORS not allowed for origin: ${origin}`,\n });\n };\n }\n\n /**\n * Same-origin (HOST ONLY — see corsMiddleware() on why the scheme is deliberately ignored), or an\n * explicit entry in corsOrigins. NOTHING is implicit: localhost is allowed only if the config\n * asked for it, so a production server that enables cors for a cross-host UI does not silently\n * open the door to localhost as well.\n */\n private isOriginAllowed(origin: string, host: string | undefined, allowedOrigins: string[]): boolean {\n let originHost: string;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a malformed Origin is untrusted browser input, not a server fault; it must become a 403 here, never bubble to the 500 chokepoint\n try {\n originHost = new URL(origin).host;\n } catch (err: unknown) {\n const error = toError(err);\n corsLog.info(`Malformed Origin header '${origin}': ${error.message}`);\n return false;\n }\n if (host !== undefined && originHost === host) {\n return true; // same-origin: the server's own UI calling its own api\n }\n return allowedOrigins.some((allowed: string): boolean => this.matchesOrigin(origin, allowed));\n }\n\n /**\n * Exact origin match, except a `*` in the PORT position matches any port: `http://localhost:*`\n * is what a developer writes, because the angular dev-server port moves around.\n *\n * The `*` is deliberately NOT a general wildcard — it never spans a host, and what follows the\n * prefix must be a real (digits-only) port. So `http://localhost:*` cannot be tricked into\n * matching `http://localhost.evil.com`, and a bare `*` matches nothing at all.\n */\n private matchesOrigin(origin: string, allowed: string): boolean {\n if (allowed === origin) {\n return true;\n }\n const wildcardSuffix = ':*';\n if (!allowed.endsWith(wildcardSuffix)) {\n return false;\n }\n const prefix = allowed.slice(0, -wildcardSuffix.length);\n if (!origin.startsWith(`${prefix}:`)) {\n return false;\n }\n const port = origin.slice(prefix.length + 1);\n return /^\\d+$/.test(port);\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design): it publishes the\n * HttpRequest + fills the context, then invokes the api client method (the proxy).\n *\n * @param clientMethod - The api client's method for this route (dto → response); the proxy\n * runs the filter chain + controller.\n * @param path - The route path (used to build the HttpRequest).\n * @param formPost - True for an @Endpoint(..., { formPost: true }) route (parse body as\n * urlencoded, not JSON). Default false = JSON.\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n clientMethod: (requestDto: unknown) => Promise<unknown>,\n path: string,\n formPost: boolean = false,\n ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path, this.headers, formPost);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,0DAAqF;AACrF,oDAA+C;AAC/C,0DAAgE;AAChE,oDAAkD;AAClD,qDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AACxD,iGAAiG;AACjG,+FAA+F;AAC/F,MAAM,OAAO,GAAG,sBAAU,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAa7C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAC5B,0FAA0F;IACzE,OAAO,GAAG,IAAI,oCAAqB,EAAE,CAAC;IAGvD;;;;;;;;;;;;;OAaG;IACH,2GAA2G;IAC3G,gKAAgK;IAChK,YAAY,CAAC,GAAY,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB;QACtE,MAAM,KAAK,GAAG,IAAA,mBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,GAAG,CAAC,KAAK,CAAC,oBAAoB,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;QAC/D,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;YAClB,OAAO;QACX,CAAC;QACD,6FAA6F;QAC7F,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;;;;;;;mBAOV,KAAK,CAAC,OAAO;;;SAGvB,CAAC,CAAC;IACP,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,cAAc,CAAC,MAAwB;QACnC,MAAM,cAAc,GAAG,MAAM,EAAE,WAAW,IAAI,EAAE,CAAC;QACjD,OAAO,CAAC,IAAI,CACR,yCAAyC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK;Y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AC,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACnF,CAAC;CACJ,CAAA;AA9KY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;GACf,mBAAmB,CA8K/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { ExpressWrapper } from './ExpressWrapper';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n// CORS mount/allow/block lines log under their own name (not [WebpiecesMiddleware]); the backend\n// prepends \"[CORS]\" for us, so the message strings below carry no literal prefix of their own.\nconst corsLog = LogManager.getLogger('CORS');\n\n/**\n * Express route handler function type. Lives in http-server (the express adapter),\n * NOT in the node-only http-routing package, so http-routing stays express-free.\n * Used by WebpiecesExpressRouter to register handlers Express can call.\n */\nexport type ExpressRouteHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => Promise<void>;\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. errorHandler - Top-level 4-arg error middleware, returns HTML 500 page. Mounted AFTER the\n * routes so express can forward downstream failures to it (express routes errors DOWN a\n * separate pipeline, it does not bubble them back up through next()). Last-resort net only:\n * api routes translate their own errors to JSON inside the filter chain (ExpressWrapper).\n * 2. corsMiddleware - Opt-in CORS (mounted only when corsOrigins is non-empty).\n *\n * Per-request logging is intentionally NOT here — the api filter chain's LogApiCall already logs\n * every request/response with full context (requestId, method, path, body), so a plain express\n * START/END line would only duplicate it with less information.\n *\n * Route dispatch happens via Express's registered route handlers (the per-route ExpressWrapper),\n * NOT via this middleware.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideFrameworkSingleton()\nexport class WebpiecesMiddleware {\n /** The ONE wire<->context transfer, handed to every route's ExpressWrapper. Stateless. */\n private readonly headers = new RequestContextHeaders();\n\n\n /**\n * Top-level error handler — the last-ditch catch-all. MUST be mounted AFTER all routes (see\n * {@link WebpiecesExpressRouter}). The 4-argument `(err, req, res, next)` signature is what\n * tells express this is an error-handling middleware: express's router forwards ANY downstream\n * failure to it — synchronous throws AND rejected async-handler promises alike (the router does\n * `promise.then(null, err => next(err))`, and a `next(err)` with a truthy arg jumps straight to\n * the first 4-arg middleware). This is why a `try { await next() } catch` wrapper is NOT needed\n * (and would not work) — express `next()` is not promise-aware, so it never hands the parent the\n * downstream promise; errors travel down this separate pipeline instead of bubbling back up.\n *\n * Returns an HTML 500 page. Api routes translate their own errors to JSON inside the filter\n * chain (JsonFilter/ExpressWrapper), so this normally only fires for failures OUTSIDE a route\n * (body parsing, unmatched paths, a bug in the wrapper itself).\n */\n // webpieces-disable no-any-unknown -- a thrown/forwarded express error is genuinely unknown until narrowed\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- express needs the 4-arg (err,req,res,next) arity to recognize this as error-handling middleware\n errorHandler(err: unknown, req: Request, res: Response, next: NextFunction): void {\n const error = toError(err);\n log.error(`Unhandled error: ${req.method} ${req.path}`, error);\n if (res.headersSent) {\n return;\n }\n // Return HTML error page (not JSON - api routes translate JSON errors in their filter chain)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n <pre>${error.message}</pre>\n </body>\n </html>\n `);\n }\n\n /**\n * CORS middleware. DO NOT MOUNT UNCONDITIONALLY — {@link WebpiecesExpressRouter.bindAndStartExpress}\n * mounts it ONLY when {@link WebpiecesConfig.corsOrigins} is non-empty, and that is the point.\n *\n * CORS exists solely to let a browser on a DIFFERENT origin call this api — in practice\n * `ng serve` on :4200 hitting an api on :8080 during development, or a UI hosted on a different\n * host than the api. A server that serves its own browser app needs NO cors at all, because a\n * browser does not apply cors to a same-origin request. So in production this middleware is\n * normally ABSENT, and absent is the safe state: every origin it allows gains the right to make\n * CREDENTIALED cross-origin calls and READ the responses. Mounting it unconditionally (as the\n * old corsForLocalhost did) handed that right to anything on the victim's localhost, in prod,\n * for no benefit whatsoever.\n *\n * When mounted, allows: a request with NO Origin (curl, server-to-server, a CLI); the server's\n * OWN origin; and EXACTLY the origins in `corsOrigins` — nothing is implicit. Anything else gets\n * a clean 403, never the HTML 500 the old `callback(new Error(...))` produced.\n *\n * SAME-ORIGIN MUST STAY ALLOWED even though a same-origin request needs no cors headers, because\n * a browser attaches an `Origin` header to EVERY POST — including a same-origin POST — and every\n * webpieces route is a POST. Once mounted, this middleware SEES that origin, so if it did not\n * allow it, it would 403 the server's own UI. That was the production bug.\n *\n * The same-origin test compares HOST ONLY, deliberately. Behind a TLS-terminating proxy (Cloud\n * Run, any load balancer) `req.protocol` is `http` while the browser's `Origin` says `https`, so\n * comparing full origins would reject the server's own origin on every deploy.\n *\n * @returns Express middleware handler for CORS\n */\n corsMiddleware(config?: WebpiecesConfig): RequestHandler {\n const allowedOrigins = config?.corsOrigins ?? [];\n corsLog.info(\n `CORS MOUNTED. Allowing same-origin + [${allowedOrigins.join(', ')}]. ` +\n `Every other browser origin gets a 403.`,\n );\n\n const handler = cors({\n origin: true, // reflect the request origin — we have already vetted it below\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*',\n exposedHeaders: '*',\n maxAge: 3600,\n });\n\n return (req: Request, res: Response, next: NextFunction): void => {\n const origin = req.headers.origin;\n if (!origin) {\n // No Origin -> not a browser cross-origin request; nothing to negotiate.\n next();\n return;\n }\n if (this.isOriginAllowed(origin, req.get('host'), allowedOrigins)) {\n handler(req, res, next);\n return;\n }\n corsLog.info(`Blocked origin: ${origin}`);\n res.status(403).json({\n name: 'CorsError',\n message: `CORS not allowed for origin: ${origin}`,\n });\n };\n }\n\n /**\n * Same-origin (HOST ONLY — see corsMiddleware() on why the scheme is deliberately ignored), or an\n * explicit entry in corsOrigins. NOTHING is implicit: localhost is allowed only if the config\n * asked for it, so a production server that enables cors for a cross-host UI does not silently\n * open the door to localhost as well.\n */\n private isOriginAllowed(origin: string, host: string | undefined, allowedOrigins: string[]): boolean {\n let originHost: string;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a malformed Origin is untrusted browser input, not a server fault; it must become a 403 here, never bubble to the 500 chokepoint\n try {\n originHost = new URL(origin).host;\n } catch (err: unknown) {\n const error = toError(err);\n corsLog.info(`Malformed Origin header '${origin}': ${error.message}`);\n return false;\n }\n if (host !== undefined && originHost === host) {\n return true; // same-origin: the server's own UI calling its own api\n }\n return allowedOrigins.some((allowed: string): boolean => this.matchesOrigin(origin, allowed));\n }\n\n /**\n * Exact origin match, except a `*` in the PORT position matches any port: `http://localhost:*`\n * is what a developer writes, because the angular dev-server port moves around.\n *\n * The `*` is deliberately NOT a general wildcard — it never spans a host, and what follows the\n * prefix must be a real (digits-only) port. So `http://localhost:*` cannot be tricked into\n * matching `http://localhost.evil.com`, and a bare `*` matches nothing at all.\n */\n private matchesOrigin(origin: string, allowed: string): boolean {\n if (allowed === origin) {\n return true;\n }\n const wildcardSuffix = ':*';\n if (!allowed.endsWith(wildcardSuffix)) {\n return false;\n }\n const prefix = allowed.slice(0, -wildcardSuffix.length);\n if (!origin.startsWith(`${prefix}:`)) {\n return false;\n }\n const port = origin.slice(prefix.length + 1);\n return /^\\d+$/.test(port);\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design): it publishes the\n * HttpRequest + fills the context, then invokes the api client method (the proxy).\n *\n * @param clientMethod - The api client's method for this route (dto → response); the proxy\n * runs the filter chain + controller.\n * @param path - The route path (used to build the HttpRequest).\n * @param formPost - True for an @Endpoint(..., { formPost: true }) route (parse body as\n * urlencoded, not JSON). Default false = JSON.\n * @param rawBody - True for an @Endpoint(..., { rawBody: true }) route: retain the verbatim\n * bytes + absolute url on the HttpRequest so an @AuthWebhook hook can verify a vendor\n * signature over them. Default false = the bytes are dropped once parsed.\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n // webpieces-disable no-any-unknown -- request/response DTOs are erased at the routing boundary\n clientMethod: (requestDto: unknown) => Promise<unknown>,\n path: string,\n formPost: boolean = false,\n rawBody: boolean = false,\n ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path, this.headers, formPost, rawBody);\n }\n}\n"]}
|