@webpieces/http-server 0.3.379 → 0.3.380
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-server",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.380",
|
|
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.3.
|
|
26
|
-
"@webpieces/core-util": "0.3.
|
|
27
|
-
"@webpieces/gcp-identity": "0.3.
|
|
28
|
-
"@webpieces/http-routing": "0.3.
|
|
25
|
+
"@webpieces/core-context": "0.3.380",
|
|
26
|
+
"@webpieces/core-util": "0.3.380",
|
|
27
|
+
"@webpieces/gcp-identity": "0.3.380",
|
|
28
|
+
"@webpieces/http-routing": "0.3.380",
|
|
29
29
|
"cors": "2.8.5",
|
|
30
30
|
"express": "5.1.0",
|
|
31
31
|
"inversify": "7.10.4"
|
|
@@ -36,12 +36,12 @@ export declare class WebpiecesExpressRouter {
|
|
|
36
36
|
*/
|
|
37
37
|
bindExpress(app: Express): void;
|
|
38
38
|
/**
|
|
39
|
-
* Add the webpieces global middleware (HTML error page, CORS, request logging), bind
|
|
40
|
-
* then app.listen(port). Convenience for a non-legacy webpieces server where
|
|
41
|
-
* whole express app. Resolves with the http.Server once listening.
|
|
39
|
+
* Add the webpieces global middleware (HTML error page, optional CORS, request logging), bind
|
|
40
|
+
* the routes, then app.listen(port). Convenience for a non-legacy webpieces server where
|
|
41
|
+
* webpieces owns the whole express app. Resolves with the http.Server once listening.
|
|
42
42
|
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
43
|
+
* CORS is mounted ONLY when `config.corsOrigins` is non-empty — see the note below and
|
|
44
|
+
* {@link WebpiecesMiddleware.corsMiddleware}.
|
|
45
45
|
*/
|
|
46
46
|
bindAndStartExpress(app: Express, port?: number, config?: WebpiecesConfig): Promise<HttpServer>;
|
|
47
47
|
/**
|
|
@@ -47,17 +47,25 @@ class WebpiecesExpressRouter {
|
|
|
47
47
|
log.info(`[WebpiecesExpressRouter] Mounted ${count} webpieces route(s) onto express`);
|
|
48
48
|
}
|
|
49
49
|
/**
|
|
50
|
-
* Add the webpieces global middleware (HTML error page, CORS, request logging), bind
|
|
51
|
-
* then app.listen(port). Convenience for a non-legacy webpieces server where
|
|
52
|
-
* whole express app. Resolves with the http.Server once listening.
|
|
50
|
+
* Add the webpieces global middleware (HTML error page, optional CORS, request logging), bind
|
|
51
|
+
* the routes, then app.listen(port). Convenience for a non-legacy webpieces server where
|
|
52
|
+
* webpieces owns the whole express app. Resolves with the http.Server once listening.
|
|
53
53
|
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
54
|
+
* CORS is mounted ONLY when `config.corsOrigins` is non-empty — see the note below and
|
|
55
|
+
* {@link WebpiecesMiddleware.corsMiddleware}.
|
|
56
56
|
*/
|
|
57
57
|
async bindAndStartExpress(app, port = 8080, config) {
|
|
58
58
|
// Global middleware layers (outermost first) — only for a webpieces-owned app.
|
|
59
59
|
app.use(this.middleware.globalErrorHandler.bind(this.middleware));
|
|
60
|
-
app
|
|
60
|
+
// CORS is OPT-IN, and stays OFF in production. A server that serves its own browser app does
|
|
61
|
+
// not need it — a browser applies no cors check to a same-origin request — so mounting it
|
|
62
|
+
// would only hand credentialed cross-origin read access to whatever it allows, for nothing.
|
|
63
|
+
// It is needed solely when a browser on ANOTHER origin calls this api: `ng serve` in dev, or
|
|
64
|
+
// a UI hosted on a different host. Those say so via corsOrigins.
|
|
65
|
+
const corsOrigins = config?.corsOrigins ?? [];
|
|
66
|
+
if (corsOrigins.length > 0) {
|
|
67
|
+
app.use(this.middleware.corsMiddleware(config));
|
|
68
|
+
}
|
|
61
69
|
app.use(this.middleware.logNextLayer.bind(this.middleware));
|
|
62
70
|
this.bindExpress(app);
|
|
63
71
|
return new Promise((resolve, reject) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebpiecesExpressRouter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesExpressRouter.ts"],"names":[],"mappings":";;;AACA,0DAA2G;AAC3G,oDAAkD;AAClD,+DAAiF;AAEjF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAK3D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,sBAAsB;IAGF;IAFZ,UAAU,GAAG,IAAI,yCAAmB,EAAE,CAAC;IAExD,YAA6B,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;IAAG,CAAC;IAEvD;;;;;;OAMG;IACH,WAAW,CAAC,GAAY;QACpB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,EAAE,CAAC;YACnD,KAAK,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QACjD,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,oCAAoC,KAAK,kCAAkC,CAAC,CAAC;IAC1F,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,mBAAmB,CACrB,GAAY,EACZ,OAAe,IAAI,EACnB,MAAwB;QAExB,+EAA+E;QAC/E,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"WebpiecesExpressRouter.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesExpressRouter.ts"],"names":[],"mappings":";;;AACA,0DAA2G;AAC3G,oDAAkD;AAClD,+DAAiF;AA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AEO,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,iDAAiD,UAAU,EAAE,CAAC,CAAC;QAChF,CAAC;IACL,CAAC;CACJ;AAjHD,wDAiHC","sourcesContent":["import { Express } from 'express';\nimport { ApiFactory, ApiClient, getApiPath, getEndpoints, 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(`[WebpiecesExpressRouter] Mounted ${count} webpieces route(s) onto express`);\n }\n\n /**\n * Add the webpieces global middleware (HTML error page, optional CORS, request logging), bind\n * the routes, 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 app.use(this.middleware.globalErrorHandler.bind(this.middleware));\n\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 app.use(this.middleware.logNextLayer.bind(this.middleware));\n\n this.bindExpress(app);\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(`[WebpiecesExpressRouter] Failed to start on port ${port}:`, error);\n reject(error);\n return;\n }\n log.info(`[WebpiecesExpressRouter] Listening on http://localhost:${port}`);\n resolve(server);\n });\n },\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 const wrapper = this.middleware.createExpressWrapper(apiClient.client[methodName], path);\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(`[WebpiecesExpressRouter] Unknown HTTP method: ${httpMethod}`);\n }\n }\n}\n"]}
|
|
@@ -97,17 +97,26 @@ export declare class WebpiecesMiddleware {
|
|
|
97
97
|
*/
|
|
98
98
|
logNextLayer(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
99
99
|
/**
|
|
100
|
-
* CORS middleware.
|
|
100
|
+
* CORS middleware. DO NOT MOUNT UNCONDITIONALLY — {@link WebpiecesExpressRouter.bindAndStartExpress}
|
|
101
|
+
* mounts it ONLY when {@link WebpiecesConfig.corsOrigins} is non-empty, and that is the point.
|
|
101
102
|
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
103
|
+
* CORS exists solely to let a browser on a DIFFERENT origin call this api — in practice
|
|
104
|
+
* `ng serve` on :4200 hitting an api on :8080 during development, or a UI hosted on a different
|
|
105
|
+
* host than the api. A server that serves its own browser app needs NO cors at all, because a
|
|
106
|
+
* browser does not apply cors to a same-origin request. So in production this middleware is
|
|
107
|
+
* normally ABSENT, and absent is the safe state: every origin it allows gains the right to make
|
|
108
|
+
* CREDENTIALED cross-origin calls and READ the responses. Mounting it unconditionally (as the
|
|
109
|
+
* old corsForLocalhost did) handed that right to anything on the victim's localhost, in prod,
|
|
110
|
+
* for no benefit whatsoever.
|
|
105
111
|
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
112
|
+
* When mounted, allows: a request with NO Origin (curl, server-to-server, a CLI); the server's
|
|
113
|
+
* OWN origin; and EXACTLY the origins in `corsOrigins` — nothing is implicit. Anything else gets
|
|
114
|
+
* a clean 403, never the HTML 500 the old `callback(new Error(...))` produced.
|
|
115
|
+
*
|
|
116
|
+
* SAME-ORIGIN MUST STAY ALLOWED even though a same-origin request needs no cors headers, because
|
|
117
|
+
* a browser attaches an `Origin` header to EVERY POST — including a same-origin POST — and every
|
|
118
|
+
* webpieces route is a POST. Once mounted, this middleware SEES that origin, so if it did not
|
|
119
|
+
* allow it, it would 403 the server's own UI. That was the production bug.
|
|
111
120
|
*
|
|
112
121
|
* The same-origin test compares HOST ONLY, deliberately. Behind a TLS-terminating proxy (Cloud
|
|
113
122
|
* Run, any load balancer) `req.protocol` is `http` while the browser's `Origin` says `https`, so
|
|
@@ -117,12 +126,21 @@ export declare class WebpiecesMiddleware {
|
|
|
117
126
|
*/
|
|
118
127
|
corsMiddleware(config?: WebpiecesConfig): RequestHandler;
|
|
119
128
|
/**
|
|
120
|
-
*
|
|
121
|
-
*
|
|
129
|
+
* Same-origin (HOST ONLY — see corsMiddleware() on why the scheme is deliberately ignored), or an
|
|
130
|
+
* explicit entry in corsOrigins. NOTHING is implicit: localhost is allowed only if the config
|
|
131
|
+
* asked for it, so a production server that enables cors for a cross-host UI does not silently
|
|
132
|
+
* open the door to localhost as well.
|
|
122
133
|
*/
|
|
123
|
-
corsForLocalhost(): RequestHandler;
|
|
124
|
-
/** Host-only comparison — see corsMiddleware() on why the scheme is deliberately ignored. */
|
|
125
134
|
private isOriginAllowed;
|
|
135
|
+
/**
|
|
136
|
+
* Exact origin match, except a `*` in the PORT position matches any port: `http://localhost:*`
|
|
137
|
+
* is what a developer writes, because the angular dev-server port moves around.
|
|
138
|
+
*
|
|
139
|
+
* The `*` is deliberately NOT a general wildcard — it never spans a host, and what follows the
|
|
140
|
+
* prefix must be a real (digits-only) port. So `http://localhost:*` cannot be tricked into
|
|
141
|
+
* matching `http://localhost.evil.com`, and a bare `*` matches nothing at all.
|
|
142
|
+
*/
|
|
143
|
+
private matchesOrigin;
|
|
126
144
|
/**
|
|
127
145
|
* Create an ExpressWrapper for a route.
|
|
128
146
|
* The wrapper handles the full request/response cycle (symmetric design): it publishes the
|
|
@@ -265,17 +265,26 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
|
265
265
|
log.info(`🟡 [Layer 2: LogNextLayer] After next() - ${req.method} ${req.path}`);
|
|
266
266
|
}
|
|
267
267
|
/**
|
|
268
|
-
* CORS middleware.
|
|
268
|
+
* CORS middleware. DO NOT MOUNT UNCONDITIONALLY — {@link WebpiecesExpressRouter.bindAndStartExpress}
|
|
269
|
+
* mounts it ONLY when {@link WebpiecesConfig.corsOrigins} is non-empty, and that is the point.
|
|
269
270
|
*
|
|
270
|
-
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
271
|
+
* CORS exists solely to let a browser on a DIFFERENT origin call this api — in practice
|
|
272
|
+
* `ng serve` on :4200 hitting an api on :8080 during development, or a UI hosted on a different
|
|
273
|
+
* host than the api. A server that serves its own browser app needs NO cors at all, because a
|
|
274
|
+
* browser does not apply cors to a same-origin request. So in production this middleware is
|
|
275
|
+
* normally ABSENT, and absent is the safe state: every origin it allows gains the right to make
|
|
276
|
+
* CREDENTIALED cross-origin calls and READ the responses. Mounting it unconditionally (as the
|
|
277
|
+
* old corsForLocalhost did) handed that right to anything on the victim's localhost, in prod,
|
|
278
|
+
* for no benefit whatsoever.
|
|
273
279
|
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
*
|
|
280
|
+
* When mounted, allows: a request with NO Origin (curl, server-to-server, a CLI); the server's
|
|
281
|
+
* OWN origin; and EXACTLY the origins in `corsOrigins` — nothing is implicit. Anything else gets
|
|
282
|
+
* a clean 403, never the HTML 500 the old `callback(new Error(...))` produced.
|
|
283
|
+
*
|
|
284
|
+
* SAME-ORIGIN MUST STAY ALLOWED even though a same-origin request needs no cors headers, because
|
|
285
|
+
* a browser attaches an `Origin` header to EVERY POST — including a same-origin POST — and every
|
|
286
|
+
* webpieces route is a POST. Once mounted, this middleware SEES that origin, so if it did not
|
|
287
|
+
* allow it, it would 403 the server's own UI. That was the production bug.
|
|
279
288
|
*
|
|
280
289
|
* The same-origin test compares HOST ONLY, deliberately. Behind a TLS-terminating proxy (Cloud
|
|
281
290
|
* Run, any load balancer) `req.protocol` is `http` while the browser's `Origin` says `https`, so
|
|
@@ -284,9 +293,9 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
|
284
293
|
* @returns Express middleware handler for CORS
|
|
285
294
|
*/
|
|
286
295
|
corsMiddleware(config) {
|
|
287
|
-
const
|
|
288
|
-
log.info(`[WebpiecesMiddleware] CORS
|
|
289
|
-
|
|
296
|
+
const allowedOrigins = config?.corsOrigins ?? [];
|
|
297
|
+
log.info(`[WebpiecesMiddleware] CORS MOUNTED. Allowing same-origin + [${allowedOrigins.join(', ')}]. ` +
|
|
298
|
+
`Every other browser origin gets a 403.`);
|
|
290
299
|
const handler = (0, cors_1.default)({
|
|
291
300
|
origin: true, // reflect the request origin — we have already vetted it below
|
|
292
301
|
credentials: true,
|
|
@@ -302,7 +311,7 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
|
302
311
|
next();
|
|
303
312
|
return;
|
|
304
313
|
}
|
|
305
|
-
if (this.isOriginAllowed(origin, req.get('host'),
|
|
314
|
+
if (this.isOriginAllowed(origin, req.get('host'), allowedOrigins)) {
|
|
306
315
|
handler(req, res, next);
|
|
307
316
|
return;
|
|
308
317
|
}
|
|
@@ -314,17 +323,12 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
|
314
323
|
};
|
|
315
324
|
}
|
|
316
325
|
/**
|
|
317
|
-
*
|
|
318
|
-
*
|
|
326
|
+
* Same-origin (HOST ONLY — see corsMiddleware() on why the scheme is deliberately ignored), or an
|
|
327
|
+
* explicit entry in corsOrigins. NOTHING is implicit: localhost is allowed only if the config
|
|
328
|
+
* asked for it, so a production server that enables cors for a cross-host UI does not silently
|
|
329
|
+
* open the door to localhost as well.
|
|
319
330
|
*/
|
|
320
|
-
|
|
321
|
-
return this.corsMiddleware();
|
|
322
|
-
}
|
|
323
|
-
/** Host-only comparison — see corsMiddleware() on why the scheme is deliberately ignored. */
|
|
324
|
-
isOriginAllowed(origin, host, extraOrigins) {
|
|
325
|
-
if (extraOrigins.includes(origin)) {
|
|
326
|
-
return true;
|
|
327
|
-
}
|
|
331
|
+
isOriginAllowed(origin, host, allowedOrigins) {
|
|
328
332
|
let originHost;
|
|
329
333
|
// 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
|
|
330
334
|
try {
|
|
@@ -338,8 +342,30 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
|
|
|
338
342
|
if (host !== undefined && originHost === host) {
|
|
339
343
|
return true; // same-origin: the server's own UI calling its own api
|
|
340
344
|
}
|
|
341
|
-
|
|
342
|
-
|
|
345
|
+
return allowedOrigins.some((allowed) => this.matchesOrigin(origin, allowed));
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Exact origin match, except a `*` in the PORT position matches any port: `http://localhost:*`
|
|
349
|
+
* is what a developer writes, because the angular dev-server port moves around.
|
|
350
|
+
*
|
|
351
|
+
* The `*` is deliberately NOT a general wildcard — it never spans a host, and what follows the
|
|
352
|
+
* prefix must be a real (digits-only) port. So `http://localhost:*` cannot be tricked into
|
|
353
|
+
* matching `http://localhost.evil.com`, and a bare `*` matches nothing at all.
|
|
354
|
+
*/
|
|
355
|
+
matchesOrigin(origin, allowed) {
|
|
356
|
+
if (allowed === origin) {
|
|
357
|
+
return true;
|
|
358
|
+
}
|
|
359
|
+
const wildcardSuffix = ':*';
|
|
360
|
+
if (!allowed.endsWith(wildcardSuffix)) {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
const prefix = allowed.slice(0, -wildcardSuffix.length);
|
|
364
|
+
if (!origin.startsWith(`${prefix}:`)) {
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
const port = origin.slice(prefix.length + 1);
|
|
368
|
+
return /^\d+$/.test(port);
|
|
343
369
|
}
|
|
344
370
|
/**
|
|
345
371
|
* Create an ExpressWrapper for a route.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,yCAAuC;AACvC,0DAAqF;AACrF,oDAa8B;AAC9B,oDAA+C;AAC/C,0DAA6F;AAC7F,oDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,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AAE,IAAwB,EAAE,YAAsB;QACpF,IAAI,YAAY,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAChC,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,IAAI,UAAkB,CAAC;QACvB,kMAAkM;QAClM,IAAI,CAAC;YACD,UAAU,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;QACtC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,mBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,GAAG,CAAC,IAAI,CAAC,mCAAmC,MAAM,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YACzE,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,IAAI,IAAI,KAAK,SAAS,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;YAC5C,OAAO,IAAI,CAAC,CAAC,uDAAuD;QACxE,CAAC;QACD,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1C,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,WAAW,CAAC;IAChE,CAAC;IAED;;;;;;;;;OASG;IACH,oBAAoB;IAChB,+FAA+F;IAC/F,YAAuD,EACvD,IAAY;QAEZ,OAAO,IAAI,cAAc,CAAC,YAAY,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAChE,CAAC;CACJ,CAAA;AAlKY,kDAAmB;8BAAnB,mBAAmB;IAF/B,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;GACA,mBAAmB,CAkK/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { injectable } from 'inversify';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport {\n ProtocolError,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n} from '@webpieces/core-util';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContext, HttpRequest, RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\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\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 }\n\n public async execute(req: Request, res: Response, next: NextFunction) {\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 JSON request body manually (SYMMETRIC with client's JSON.stringify)\n let requestDto: unknown = {};\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n // Read raw body as text\n const bodyText = await this.readRequestBody(req);\n // Parse JSON\n requestDto = bodyText ? JSON.parse(bodyText) : {};\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, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\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 public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\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(`[ExpressWrapper] User Error: ${error.message}`);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info(`[ExpressWrapper] Bad Request: ${error.message}`);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info(`[ExpressWrapper] Not Found: ${error.message}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`[ExpressWrapper] Timeout Error: ${error.message}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`[ExpressWrapper] Vendor Error: ${error.message}`);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`[ExpressWrapper] Unauthorized: ${error.message}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`[ExpressWrapper] Forbidden: ${error.message}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`[ExpressWrapper] Internal Server Error: ${error.message}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`[ExpressWrapper] Bad Gateway: ${error.message}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error(`[ExpressWrapper] Gateway Timeout: ${error.message}`);\n } else {\n log.info(`[ExpressWrapper] 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('[ExpressWrapper] Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. globalErrorHandler - Outermost error handler, returns HTML 500 page\n * 2. logNextLayer - Request/response logging\n * 3. jsonTranslator - JSON Content-Type validation and error translation\n *\n * The middleware is injected into WebpiecesServerImpl and registered with Express\n * in the start() method.\n *\n * IMPORTANT: jsonTranslator does NOT dispatch routes - route dispatch happens via\n * Express's registered route handlers (created by RouteBuilder.createHandler()).\n * jsonTranslator only validates Content-Type and translates errors to JSON.\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()\n@injectable()\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 * Global error handler middleware - catches ALL unhandled errors.\n * Returns HTML 500 error page for any errors that escape the filter chain.\n *\n * This is the outermost safety net - JsonTranslator catches JSON API errors,\n * this catches everything else.\n */\n async globalErrorHandler(\n req: Request,\n res: Response,\n next: NextFunction,\n ): Promise<void> {\n log.info(`🔴 [Layer 1: GlobalErrorHandler] Request START: ${req.method} ${req.path}`);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- Global error handler IS the top-level catch-all\n try {\n // await next() catches BOTH:\n // 1. Synchronous throws from next() itself\n // 2. Rejected promises from downstream async middleware\n await next();\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (success): ${req.method} ${req.path}`,\n );\n } catch (err: unknown) {\n const error = toError(err);\n log.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);\n if (!res.headersSent) {\n // Return HTML error page (not JSON - JsonTranslator handles JSON errors)\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 log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (error): ${req.method} ${req.path}`,\n );\n }\n }\n\n /**\n * Logging middleware - logs request/response flow.\n * Demonstrates middleware execution order.\n * IMPORTANT: Must be async and await next() to properly chain with async middleware.\n */\n async logNextLayer(req: Request, res: Response, next: NextFunction): Promise<void> {\n log.info(`🟡 [Layer 2: LogNextLayer] Before next() - ${req.method} ${req.path}`);\n await next();\n log.info(`🟡 [Layer 2: LogNextLayer] After next() - ${req.method} ${req.path}`);\n }\n\n /**\n * CORS middleware.\n *\n * Allows, in order: a request with NO Origin (curl, server-to-server, a CLI); the server's OWN\n * origin; any `localhost:*` / `127.0.0.1:*` origin (dev); and any origin listed in\n * {@link WebpiecesConfig.corsOrigins}. Anything else gets a clean 403.\n *\n * SAME-ORIGIN IS THE SUBTLE ONE, and it is why this is not localhost-only. A browser attaches an\n * `Origin` header to EVERY POST — including a same-origin POST — and every webpieces route is a\n * POST. So a server that also serves its own UI (one container, one origin) receives its own\n * origin on every api call it makes to itself. Rejecting it, as the old localhost-only rule did,\n * broke every api call the moment a webpieces server served a browser app in production.\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 extraOrigins = config?.corsOrigins ?? [];\n log.info(\n `[WebpiecesMiddleware] CORS: same-origin + localhost:* always allowed` +\n (extraOrigins.length > 0 ? `, plus ${extraOrigins.join(', ')}` : ''),\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'), extraOrigins)) {\n handler(req, res, next);\n return;\n }\n log.info(`[CORS] 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 * @deprecated Use {@link corsMiddleware}. Kept so existing callers keep compiling; it now also\n * allows the server's own origin, which the localhost-only rule wrongly rejected.\n */\n corsForLocalhost(): RequestHandler {\n return this.corsMiddleware();\n }\n\n /** Host-only comparison — see corsMiddleware() on why the scheme is deliberately ignored. */\n private isOriginAllowed(origin: string, host: string | undefined, extraOrigins: string[]): boolean {\n if (extraOrigins.includes(origin)) {\n return true;\n }\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 log.info(`[CORS] 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 const hostname = originHost.split(':')[0];\n return hostname === 'localhost' || hostname === '127.0.0.1';\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 * @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 ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path, this.headers);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,yCAAuC;AACvC,0DAAqF;AACrF,oDAa8B;AAC9B,oDAA+C;AAC/C,0DAA6F;AAC7F,oDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAaxD,MAAa,cAAc;IAGX;IACA;IAEA;IALZ;IACI,+FAA+F;IACvF,YAAuD,EACvD,IAAY;IACpB,wFAAwF;IAChF,OAA8B;QAH9B,iBAAY,GAAZ,YAAY,CAA2C;QACvD,SAAI,GAAJ,IAAI,CAAQ;QAEZ,YAAO,GAAP,OAAO,CAAuB;IAE1C,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,8HAA8H;QAC9H,IAA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O,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;;;;;;;;;OASG;IACH,oBAAoB;IAChB,+FAA+F;IAC/F,YAAuD,EACvD,IAAY;QAEZ,OAAO,IAAI,cAAc,CAAC,YAAY,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAChE,CAAC;CACJ,CAAA;AA5LY,kDAAmB;8BAAnB,mBAAmB;IAF/B,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;GACA,mBAAmB,CA4L/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { injectable } from 'inversify';\nimport { provideFrameworkSingleton, WebpiecesConfig } from '@webpieces/http-routing';\nimport {\n ProtocolError,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n} from '@webpieces/core-util';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContext, HttpRequest, RequestContextHeaders } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\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\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 }\n\n public async execute(req: Request, res: Response, next: NextFunction) {\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 JSON request body manually (SYMMETRIC with client's JSON.stringify)\n let requestDto: unknown = {};\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n // Read raw body as text\n const bodyText = await this.readRequestBody(req);\n // Parse JSON\n requestDto = bodyText ? JSON.parse(bodyText) : {};\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, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\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 public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\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(`[ExpressWrapper] User Error: ${error.message}`);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info(`[ExpressWrapper] Bad Request: ${error.message}`);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info(`[ExpressWrapper] Not Found: ${error.message}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`[ExpressWrapper] Timeout Error: ${error.message}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`[ExpressWrapper] Vendor Error: ${error.message}`);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`[ExpressWrapper] Unauthorized: ${error.message}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`[ExpressWrapper] Forbidden: ${error.message}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`[ExpressWrapper] Internal Server Error: ${error.message}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`[ExpressWrapper] Bad Gateway: ${error.message}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error(`[ExpressWrapper] Gateway Timeout: ${error.message}`);\n } else {\n log.info(`[ExpressWrapper] 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('[ExpressWrapper] Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. globalErrorHandler - Outermost error handler, returns HTML 500 page\n * 2. logNextLayer - Request/response logging\n * 3. jsonTranslator - JSON Content-Type validation and error translation\n *\n * The middleware is injected into WebpiecesServerImpl and registered with Express\n * in the start() method.\n *\n * IMPORTANT: jsonTranslator does NOT dispatch routes - route dispatch happens via\n * Express's registered route handlers (created by RouteBuilder.createHandler()).\n * jsonTranslator only validates Content-Type and translates errors to JSON.\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()\n@injectable()\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 * Global error handler middleware - catches ALL unhandled errors.\n * Returns HTML 500 error page for any errors that escape the filter chain.\n *\n * This is the outermost safety net - JsonTranslator catches JSON API errors,\n * this catches everything else.\n */\n async globalErrorHandler(\n req: Request,\n res: Response,\n next: NextFunction,\n ): Promise<void> {\n log.info(`🔴 [Layer 1: GlobalErrorHandler] Request START: ${req.method} ${req.path}`);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- Global error handler IS the top-level catch-all\n try {\n // await next() catches BOTH:\n // 1. Synchronous throws from next() itself\n // 2. Rejected promises from downstream async middleware\n await next();\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (success): ${req.method} ${req.path}`,\n );\n } catch (err: unknown) {\n const error = toError(err);\n log.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);\n if (!res.headersSent) {\n // Return HTML error page (not JSON - JsonTranslator handles JSON errors)\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 log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (error): ${req.method} ${req.path}`,\n );\n }\n }\n\n /**\n * Logging middleware - logs request/response flow.\n * Demonstrates middleware execution order.\n * IMPORTANT: Must be async and await next() to properly chain with async middleware.\n */\n async logNextLayer(req: Request, res: Response, next: NextFunction): Promise<void> {\n log.info(`🟡 [Layer 2: LogNextLayer] Before next() - ${req.method} ${req.path}`);\n await next();\n log.info(`🟡 [Layer 2: LogNextLayer] After next() - ${req.method} ${req.path}`);\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 log.info(\n `[WebpiecesMiddleware] 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 log.info(`[CORS] 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 log.info(`[CORS] 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 * @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 ): ExpressWrapper {\n return new ExpressWrapper(clientMethod, path, this.headers);\n }\n}\n"]}
|