@gasket/plugin-https-proxy 7.5.2 → 7.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@ export default makeGasket({
31
31
 
32
32
  To be set under `httpsProxy` in the `gasket.js` file.
33
33
 
34
- This uses the [http-proxy] package and its complete set of available [options].
34
+ This uses the [http-proxy-3] package and its complete set of available [options].
35
35
 
36
36
  ```diff
37
37
  // gasket.js
@@ -58,8 +58,7 @@ are used for the actual destination server.
58
58
 
59
59
  ### Example SNI Config
60
60
 
61
- While not specifically called out in the [http-proxy] documentation, the
62
- `ssl` settings are what get passed to node's `createServer` method.
61
+ The `ssl` settings are passed to node's `https.createServer`, which serves HTTP/1.1.
63
62
  As such, you can use `SNICallback` from the [createServer options].
64
63
 
65
64
  ```diff
@@ -109,6 +108,11 @@ The complete flow is:
109
108
  2. Executes the `prebootHttpsProxy` lifecycle (one-time initialization)
110
109
  3. Executes the `httpsProxy` lifecycle for dynamic configuration
111
110
  4. Creates and starts the proxy server
111
+
112
+ When a request fails to reach the target, the proxy logs the error and responds with `502 Bad Gateway`.
113
+ A target that does not respond within `proxyTimeout` (default 2 minutes) also gets a 502.
114
+ If the response has already started, or the request is a WebSocket upgrade, it closes the connection instead.
115
+
112
116
  ## Lifecycles
113
117
 
114
118
  ### prebootHttpsProxy
@@ -169,6 +173,6 @@ export default {
169
173
 
170
174
  [MIT](./LICENSE.md)
171
175
 
172
- [http-proxy]: https://www.npmjs.com/package/http-proxy
173
- [options]: https://www.npmjs.com/package/http-proxy#options
176
+ [http-proxy-3]: https://www.npmjs.com/package/http-proxy-3
177
+ [options]: https://www.npmjs.com/package/http-proxy-3#options
174
178
  [createServer options]: https://nodejs.org/docs/latest-v22.x/api/tls.html#tlscreateserveroptions-secureconnectionlistener
package/cjs/actions.cjs CHANGED
@@ -4,35 +4,163 @@ Object.defineProperty(exports, "__esModule", {
4
4
  function _export(target, all) {
5
5
  for(var name in all)Object.defineProperty(target, name, {
6
6
  enumerable: true,
7
- get: all[name]
7
+ get: Object.getOwnPropertyDescriptor(all, name).get
8
8
  });
9
9
  }
10
10
  _export(exports, {
11
- actions: function() {
11
+ get actions () {
12
12
  return actions;
13
13
  },
14
- startProxyServer: function() {
14
+ get startProxyServer () {
15
15
  return startProxyServer;
16
16
  }
17
17
  });
18
- const _httpproxy = /*#__PURE__*/ _interop_require_default(require("http-proxy"));
18
+ const _nodehttp = /*#__PURE__*/ _interop_require_wildcard(require("node:http"));
19
+ const _nodehttps = /*#__PURE__*/ _interop_require_default(require("node:https"));
20
+ const _httpproxy3 = require("http-proxy-3");
19
21
  function _interop_require_default(obj) {
20
22
  return obj && obj.__esModule ? obj : {
21
23
  default: obj
22
24
  };
23
25
  }
26
+ function _getRequireWildcardCache(nodeInterop) {
27
+ if (typeof WeakMap !== "function") return null;
28
+ var cacheBabelInterop = new WeakMap();
29
+ var cacheNodeInterop = new WeakMap();
30
+ return (_getRequireWildcardCache = function(nodeInterop) {
31
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
32
+ })(nodeInterop);
33
+ }
34
+ function _interop_require_wildcard(obj, nodeInterop) {
35
+ if (!nodeInterop && obj && obj.__esModule) return obj;
36
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") return {
37
+ default: obj
38
+ };
39
+ var cache = _getRequireWildcardCache(nodeInterop);
40
+ if (cache && cache.has(obj)) return cache.get(obj);
41
+ var newObj = {
42
+ __proto__: null
43
+ };
44
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
45
+ for(var key in obj){
46
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
47
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
48
+ if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
49
+ else newObj[key] = obj[key];
50
+ }
51
+ }
52
+ newObj.default = obj;
53
+ if (cache) cache.set(obj, newObj);
54
+ return newObj;
55
+ }
56
+ /**
57
+ * http-proxy-3 reads `pathname` and `search` from object targets, so map the `path` that http-proxy read.
58
+ * A `path` wins over any `pathname`/`search` on the same object, as it did with http-proxy.
59
+ * @param {any} target - target or forward option
60
+ * @returns {any} target with `pathname` and `search` set from `path`
61
+ */ function withPathname(target) {
62
+ if (!target || typeof target !== 'object' || target instanceof URL || typeof target.path !== 'string') return target;
63
+ const { path, ...rest } = target;
64
+ const queryAt = path.indexOf('?');
65
+ if (queryAt === -1) return {
66
+ ...rest,
67
+ pathname: path,
68
+ search: ''
69
+ };
70
+ return {
71
+ ...rest,
72
+ pathname: path.slice(0, queryAt),
73
+ search: path.slice(queryAt)
74
+ };
75
+ }
76
+ /**
77
+ * Summarize a request failure for the log. Error properties and messages can hold request data,
78
+ * such as the full URL in the `input` of an invalid-URL error.
79
+ * @param {any} err - Error from proxying a request
80
+ * @returns {{ name?: string, code?: string }} Error name and code
81
+ */ function requestFailure(err) {
82
+ return {
83
+ name: err?.name,
84
+ code: err?.code
85
+ };
86
+ }
87
+ /**
88
+ * Serve the proxy on a node http(s) server.
89
+ * http-proxy-3 would serve HTTP/2 over TLS, and its passes can throw synchronously on a
90
+ * malformed request URL, which would crash the process.
91
+ * @param {import('http-proxy-3').ProxyServer} proxy - Proxy to serve
92
+ * @param {{ ssl?: object, ws?: boolean, port: number, logger: { error: Function } }} options - Listener options
93
+ */ function listen(proxy, { ssl, ws, port, logger }) {
94
+ // A target that drops mid-response emits no proxy error, so close the client too.
95
+ proxy.on('proxyRes', (proxyRes, req, res)=>{
96
+ proxyRes.on('close', ()=>{
97
+ if (!proxyRes.complete) res.destroy();
98
+ });
99
+ });
100
+ /** @type {http.RequestListener} */ const onRequest = (req, res)=>{
101
+ try {
102
+ proxy.web(req, res);
103
+ } catch (err) {
104
+ logger.error('Request failed to proxy:', requestFailure(err));
105
+ if (res.headersSent) return void res.destroy();
106
+ res.writeHead(400, {
107
+ 'content-type': 'text/plain'
108
+ });
109
+ res.end('Bad Request');
110
+ }
111
+ };
112
+ const listener = ssl ? _nodehttps.default.createServer(ssl, onRequest) : _nodehttp.default.createServer(onRequest);
113
+ if (ws) {
114
+ listener.on('upgrade', (req, socket, head)=>{
115
+ try {
116
+ proxy.ws(req, socket, head);
117
+ } catch (err) {
118
+ logger.error('Request failed to proxy:', requestFailure(err));
119
+ socket.destroy();
120
+ }
121
+ });
122
+ }
123
+ listener.on('error', (err)=>{
124
+ logger.error('Proxy server failed:', err);
125
+ });
126
+ listener.listen(port);
127
+ proxy.address = ()=>listener.address();
128
+ proxy.close = (cb)=>{
129
+ listener.close((err)=>cb?.(err));
130
+ };
131
+ }
24
132
  async function startProxyServer(gasket) {
133
+ var // The documented 2-minute default, which http-proxy-3 does not apply; without it a silent target holds the client open.
134
+ _proxyOpts;
25
135
  await gasket.isReady;
26
136
  await gasket.exec('prebootHttpsProxy');
27
137
  const { httpsProxy } = gasket.config;
28
138
  const { logger } = gasket;
29
139
  const opts = await gasket.execWaterfall('httpsProxy', httpsProxy);
30
- const { protocol = 'http', hostname = 'localhost', port = 8080, ...proxyOpts } = opts;
31
- const server = _httpproxy.default.createServer(proxyOpts).on('error', (err)=>{
32
- logger.error('Request failed to proxy:', err);
33
- }).listen(port);
140
+ const { protocol = 'http', hostname = 'localhost', port = 8080, ssl, ...proxyOpts } = opts;
141
+ (_proxyOpts = proxyOpts).proxyTimeout ?? (_proxyOpts.proxyTimeout = 120000);
142
+ if (proxyOpts.target) proxyOpts.target = withPathname(proxyOpts.target);
143
+ if (proxyOpts.forward) proxyOpts.forward = withPathname(proxyOpts.forward);
144
+ const proxy = (0, _httpproxy3.createServer)(proxyOpts).on('error', (err, req, res)=>{
145
+ logger.error('Request failed to proxy:', requestFailure(err));
146
+ // Answer the client so a failing target does not leave its connection open.
147
+ if (res instanceof _nodehttp.ServerResponse && !res.headersSent) {
148
+ res.writeHead(502, {
149
+ 'content-type': 'text/plain'
150
+ });
151
+ res.end('Bad Gateway');
152
+ } else {
153
+ res?.destroy();
154
+ }
155
+ });
156
+ listen(proxy, {
157
+ ssl,
158
+ ws: proxyOpts.ws,
159
+ port,
160
+ logger
161
+ });
34
162
  logger.info(`Proxy server started: ${protocol}://${hostname}:${port}`);
35
- return server;
163
+ return proxy;
36
164
  }
37
165
  const actions = {
38
166
  startProxyServer
package/cjs/index.cjs CHANGED
@@ -52,7 +52,7 @@ const _default = {
52
52
  {
53
53
  name: 'httpsProxy',
54
54
  link: 'README.md#configuration',
55
- description: 'http-proxy config object',
55
+ description: 'http-proxy-3 config object',
56
56
  type: 'object'
57
57
  }
58
58
  ]
package/lib/actions.js CHANGED
@@ -1,4 +1,78 @@
1
- import proxy from 'http-proxy';
1
+ import http, { ServerResponse } from 'node:http';
2
+ import https from 'node:https';
3
+ import { createServer } from 'http-proxy-3';
4
+
5
+ /**
6
+ * http-proxy-3 reads `pathname` and `search` from object targets, so map the `path` that http-proxy read.
7
+ * A `path` wins over any `pathname`/`search` on the same object, as it did with http-proxy.
8
+ * @param {any} target - target or forward option
9
+ * @returns {any} target with `pathname` and `search` set from `path`
10
+ */
11
+ function withPathname(target) {
12
+ if (!target || typeof target !== 'object' || target instanceof URL || typeof target.path !== 'string') return target;
13
+ const { path, ...rest } = target;
14
+ const queryAt = path.indexOf('?');
15
+ if (queryAt === -1) return { ...rest, pathname: path, search: '' };
16
+ return { ...rest, pathname: path.slice(0, queryAt), search: path.slice(queryAt) };
17
+ }
18
+
19
+ /**
20
+ * Summarize a request failure for the log. Error properties and messages can hold request data,
21
+ * such as the full URL in the `input` of an invalid-URL error.
22
+ * @param {any} err - Error from proxying a request
23
+ * @returns {{ name?: string, code?: string }} Error name and code
24
+ */
25
+ function requestFailure(err) {
26
+ return { name: err?.name, code: err?.code };
27
+ }
28
+
29
+ /**
30
+ * Serve the proxy on a node http(s) server.
31
+ * http-proxy-3 would serve HTTP/2 over TLS, and its passes can throw synchronously on a
32
+ * malformed request URL, which would crash the process.
33
+ * @param {import('http-proxy-3').ProxyServer} proxy - Proxy to serve
34
+ * @param {{ ssl?: object, ws?: boolean, port: number, logger: { error: Function } }} options - Listener options
35
+ */
36
+ function listen(proxy, { ssl, ws, port, logger }) {
37
+ // A target that drops mid-response emits no proxy error, so close the client too.
38
+ proxy.on('proxyRes', (proxyRes, req, res) => {
39
+ proxyRes.on('close', () => {
40
+ if (!proxyRes.complete) res.destroy();
41
+ });
42
+ });
43
+
44
+ /** @type {http.RequestListener} */
45
+ const onRequest = (req, res) => {
46
+ try {
47
+ proxy.web(req, res);
48
+ } catch (err) {
49
+ logger.error('Request failed to proxy:', requestFailure(err));
50
+ if (res.headersSent) return void res.destroy();
51
+ res.writeHead(400, { 'content-type': 'text/plain' });
52
+ res.end('Bad Request');
53
+ }
54
+ };
55
+ const listener = ssl ? https.createServer(ssl, onRequest) : http.createServer(onRequest);
56
+ if (ws) {
57
+ listener.on('upgrade', (req, socket, head) => {
58
+ try {
59
+ proxy.ws(req, socket, head);
60
+ } catch (err) {
61
+ logger.error('Request failed to proxy:', requestFailure(err));
62
+ socket.destroy();
63
+ }
64
+ });
65
+ }
66
+ listener.on('error', (err) => {
67
+ logger.error('Proxy server failed:', err);
68
+ });
69
+ listener.listen(port);
70
+
71
+ proxy.address = () => listener.address();
72
+ proxy.close = (cb) => {
73
+ listener.close((err) => cb?.(err));
74
+ };
75
+ }
2
76
 
3
77
  /** @type {import('@gasket/core').ActionHandler<'startProxyServer'>} */
4
78
  export async function startProxyServer(gasket) {
@@ -9,17 +83,26 @@ export async function startProxyServer(gasket) {
9
83
 
10
84
  const opts = await gasket.execWaterfall('httpsProxy', httpsProxy);
11
85
 
12
- const { protocol = 'http', hostname = 'localhost', port = 8080, ...proxyOpts } = opts;
13
- const server = proxy.createServer(
14
- proxyOpts
15
- ).on('error', (err) => {
16
- logger.error('Request failed to proxy:', err);
17
- }).listen(
18
- port
19
- );
86
+ const { protocol = 'http', hostname = 'localhost', port = 8080, ssl, ...proxyOpts } = opts;
87
+ // The documented 2-minute default, which http-proxy-3 does not apply; without it a silent target holds the client open.
88
+ proxyOpts.proxyTimeout ??= 120000;
89
+ if (proxyOpts.target) proxyOpts.target = withPathname(proxyOpts.target);
90
+ if (proxyOpts.forward) proxyOpts.forward = withPathname(proxyOpts.forward);
91
+
92
+ const proxy = createServer(proxyOpts).on('error', (err, req, res) => {
93
+ logger.error('Request failed to proxy:', requestFailure(err));
94
+ // Answer the client so a failing target does not leave its connection open.
95
+ if (res instanceof ServerResponse && !res.headersSent) {
96
+ res.writeHead(502, { 'content-type': 'text/plain' });
97
+ res.end('Bad Gateway');
98
+ } else {
99
+ res?.destroy();
100
+ }
101
+ });
102
+ listen(proxy, { ssl, ws: proxyOpts.ws, port, logger });
20
103
 
21
104
  logger.info(`Proxy server started: ${protocol}://${hostname}:${port}`);
22
- return server;
105
+ return proxy;
23
106
  }
24
107
 
25
108
  export const actions = {
package/lib/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  import type { Plugin, MaybeAsync } from '@gasket/core';
2
- import type { Url } from 'url';
3
- import type { Stream } from 'stream';
4
- import ProxyServer from 'http-proxy';
2
+ import type { ProxyServer, ProxyTarget, ServerOptions } from 'http-proxy-3';
5
3
 
6
4
  type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
7
5
  Pick<T, Exclude<keyof T, Keys>> &
@@ -9,93 +7,26 @@ type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
9
7
  [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
10
8
  }[Keys];
11
9
 
12
- /**
13
- * http-proxy does not export types.
14
- * Any Proxy* types have been lifted from @types/http-proxy
15
- * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/http-proxy/index.d.ts
16
- */
17
-
18
- interface ProxyTargetDetailed {
19
- host: string;
20
- port: number;
21
- protocol?: string | undefined;
22
- hostname?: string | undefined;
23
- socketPath?: string | undefined;
24
- key?: string | undefined;
25
- passphrase?: string | undefined;
26
- pfx?: Buffer | string | undefined;
27
- cert?: string | undefined;
28
- ca?: string | undefined;
29
- ciphers?: string | undefined;
30
- secureProtocol?: string | undefined;
31
- }
32
-
33
- type ProxyTargetUrl = string | Partial<Url>;
34
- type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed;
10
+ /** Object target in the shape http-proxy accepted: every field optional, `port` may be a string. */
11
+ type HttpsProxyTargetDetailed = Partial<Omit<Exclude<ProxyTarget, string | URL>, 'port'>> & {
12
+ port?: number | string;
13
+ /** Prepended to the request path. */
14
+ path?: string;
15
+ pathname?: string;
16
+ search?: string;
17
+ /** Ignored by http-proxy-3; use the top-level `auth` option. */
18
+ auth?: string;
19
+ };
35
20
 
36
- interface ProxyServerOptions {
37
- /** URL string to be parsed with the url module. */
38
- target?: ProxyTarget | undefined;
39
- /** URL string to be parsed with the url module. */
40
- forward?: ProxyTargetUrl | undefined;
41
- /** Object to be passed to http(s).request. */
42
- agent?: any;
43
- /** Object to be passed to https.createServer(). */
44
- ssl?: any;
45
- /** If you want to proxy websockets. */
46
- ws?: boolean | undefined;
47
- /** Adds x- forward headers. */
48
- xfwd?: boolean | undefined;
49
- /** Verify SSL certificate. */
50
- secure?: boolean | undefined;
51
- /** Explicitly specify if we are proxying to another proxy. */
52
- toProxy?: boolean | undefined;
53
- /** Specify whether you want to prepend the target's path to the proxy path. */
54
- prependPath?: boolean | undefined;
55
- /** Specify whether you want to ignore the proxy path of the incoming request. */
56
- ignorePath?: boolean | undefined;
57
- /** Local interface string to bind for outgoing connections. */
58
- localAddress?: string | undefined;
59
- /** Changes the origin of the host header to the target URL. */
60
- changeOrigin?: boolean | undefined;
61
- /** specify whether you want to keep letter case of response header key */
62
- preserveHeaderKeyCase?: boolean | undefined;
63
- /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
64
- auth?: string | undefined;
65
- /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
66
- hostRewrite?: string | undefined;
67
- /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
68
- autoRewrite?: boolean | undefined;
69
- /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
70
- protocolRewrite?: string | undefined;
71
- /** rewrites domain of set-cookie headers. */
72
- cookieDomainRewrite?: false | string | { [oldDomain: string]: string } | undefined;
73
- /** rewrites path of set-cookie headers. Default: false */
74
- cookiePathRewrite?: false | string | { [oldPath: string]: string } | undefined;
75
- /** object with extra headers to be added to target requests. */
76
- headers?: { [header: string]: string } | undefined;
77
- /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
78
- proxyTimeout?: number | undefined;
79
- /** Timeout (in milliseconds) for incoming requests */
80
- timeout?: number | undefined;
81
- /** Specify whether you want to follow redirects. Default: false */
82
- followRedirects?: boolean | undefined;
83
- /**
84
- * If set to true, none of the webOutgoing passes are called and it's your responsibility
85
- * to appropriately return the response by listening and acting on the proxyRes event
86
- */
87
- selfHandleResponse?: boolean | undefined;
88
- /** Buffer */
89
- buffer?: Stream | undefined;
90
- /** Explicitly set the method type of the ProxyReq */
91
- method?: string | undefined;
92
- }
21
+ type HttpsProxyTarget = string | URL | HttpsProxyTargetDetailed;
93
22
 
94
23
  /**
95
- * Extends the ProxyServerOptions with some additional properties
24
+ * Extends the http-proxy-3 ServerOptions with some additional properties
96
25
  * for configuring the HTTPS proxy server.
97
26
  */
98
- interface BaseHttpsProxyConfig extends ProxyServerOptions {
27
+ interface BaseHttpsProxyConfig extends Omit<ServerOptions, 'target' | 'forward'> {
28
+ target?: HttpsProxyTarget | ServerOptions['target'];
29
+ forward?: HttpsProxyTarget;
99
30
  protocol?: string;
100
31
  /** defaults to 'localhost' */
101
32
  hostname?: string;
package/lib/index.js CHANGED
@@ -41,7 +41,7 @@ export default {
41
41
  {
42
42
  name: 'httpsProxy',
43
43
  link: 'README.md#configuration',
44
- description: 'http-proxy config object',
44
+ description: 'http-proxy-3 config object',
45
45
  type: 'object'
46
46
  }
47
47
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gasket/plugin-https-proxy",
3
- "version": "7.5.2",
3
+ "version": "7.6.1",
4
4
  "description": "Adds support for running an https proxy",
5
5
  "type": "module",
6
6
  "types": "lib/index.d.ts",
@@ -33,16 +33,17 @@
33
33
  "bugs": "https://github.com/godaddy/gasket/issues",
34
34
  "homepage": "https://github.com/godaddy/gasket/tree/main/packages/gasket-plugin-https-proxy",
35
35
  "dependencies": {
36
- "http-proxy": "^1.18.1"
36
+ "http-proxy-3": "^1.23.3"
37
37
  },
38
38
  "devDependencies": {
39
+ "selfsigned": "^5.5.0",
39
40
  "vitest": "^3.2.0",
40
- "@gasket/cjs": "^7.1.2",
41
- "@gasket/core": "^7.7.6",
42
- "@gasket/plugin-https": "^7.4.2",
41
+ "@gasket/cjs": "^7.1.3",
42
+ "@gasket/core": "^7.7.7",
43
+ "@gasket/plugin-https": "^7.5.1",
43
44
  "@gasket/plugin-logger": "^7.5.1",
44
- "@gasket/plugin-metadata": "^7.5.13",
45
- "create-gasket-app": "^7.4.24"
45
+ "@gasket/plugin-metadata": "^7.5.14",
46
+ "create-gasket-app": "^7.4.29"
46
47
  },
47
48
  "scripts": {
48
49
  "build": "gasket-cjs ./lib",