@gasket/plugin-https-proxy 7.5.1 → 7.6.0

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,152 @@ 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
+ * Serve the proxy on a node http(s) server.
78
+ * http-proxy-3 would serve HTTP/2 over TLS, and its passes can throw synchronously on a
79
+ * malformed request URL, which would crash the process.
80
+ * @param {import('http-proxy-3').ProxyServer} proxy - Proxy to serve
81
+ * @param {{ ssl?: object, ws?: boolean, port: number, logger: { error: Function } }} options - Listener options
82
+ */ function listen(proxy, { ssl, ws, port, logger }) {
83
+ // A target that drops mid-response emits no proxy error, so close the client too.
84
+ proxy.on('proxyRes', (proxyRes, req, res)=>{
85
+ proxyRes.on('close', ()=>{
86
+ if (!proxyRes.complete) res.destroy();
87
+ });
88
+ });
89
+ /** @type {http.RequestListener} */ const onRequest = (req, res)=>{
90
+ try {
91
+ proxy.web(req, res);
92
+ } catch (err) {
93
+ logger.error('Request failed to proxy:', err);
94
+ if (res.headersSent) return void res.destroy();
95
+ res.writeHead(400, {
96
+ 'content-type': 'text/plain'
97
+ });
98
+ res.end('Bad Request');
99
+ }
100
+ };
101
+ const listener = ssl ? _nodehttps.default.createServer(ssl, onRequest) : _nodehttp.default.createServer(onRequest);
102
+ if (ws) {
103
+ listener.on('upgrade', (req, socket, head)=>{
104
+ try {
105
+ proxy.ws(req, socket, head);
106
+ } catch (err) {
107
+ logger.error('Request failed to proxy:', err);
108
+ socket.destroy();
109
+ }
110
+ });
111
+ }
112
+ listener.on('error', (err)=>{
113
+ logger.error('Proxy server failed:', err);
114
+ });
115
+ listener.listen(port);
116
+ proxy.address = ()=>listener.address();
117
+ proxy.close = (cb)=>{
118
+ listener.close((err)=>cb?.(err));
119
+ };
120
+ }
24
121
  async function startProxyServer(gasket) {
122
+ var // The documented 2-minute default, which http-proxy-3 does not apply; without it a silent target holds the client open.
123
+ _proxyOpts;
25
124
  await gasket.isReady;
26
125
  await gasket.exec('prebootHttpsProxy');
27
126
  const { httpsProxy } = gasket.config;
28
127
  const { logger } = gasket;
29
128
  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)=>{
129
+ const { protocol = 'http', hostname = 'localhost', port = 8080, ssl, ...proxyOpts } = opts;
130
+ (_proxyOpts = proxyOpts).proxyTimeout ?? (_proxyOpts.proxyTimeout = 120000);
131
+ if (proxyOpts.target) proxyOpts.target = withPathname(proxyOpts.target);
132
+ if (proxyOpts.forward) proxyOpts.forward = withPathname(proxyOpts.forward);
133
+ const proxy = (0, _httpproxy3.createServer)(proxyOpts).on('error', (err, req, res)=>{
32
134
  logger.error('Request failed to proxy:', err);
33
- }).listen(port);
135
+ // Answer the client so a failing target does not leave its connection open.
136
+ if (res instanceof _nodehttp.ServerResponse && !res.headersSent) {
137
+ res.writeHead(502, {
138
+ 'content-type': 'text/plain'
139
+ });
140
+ res.end('Bad Gateway');
141
+ } else {
142
+ res?.destroy();
143
+ }
144
+ });
145
+ listen(proxy, {
146
+ ssl,
147
+ ws: proxyOpts.ws,
148
+ port,
149
+ logger
150
+ });
34
151
  logger.info(`Proxy server started: ${protocol}://${hostname}:${port}`);
35
- return server;
152
+ return proxy;
36
153
  }
37
154
  const actions = {
38
155
  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,68 @@
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
+ * Serve the proxy on a node http(s) server.
21
+ * http-proxy-3 would serve HTTP/2 over TLS, and its passes can throw synchronously on a
22
+ * malformed request URL, which would crash the process.
23
+ * @param {import('http-proxy-3').ProxyServer} proxy - Proxy to serve
24
+ * @param {{ ssl?: object, ws?: boolean, port: number, logger: { error: Function } }} options - Listener options
25
+ */
26
+ function listen(proxy, { ssl, ws, port, logger }) {
27
+ // A target that drops mid-response emits no proxy error, so close the client too.
28
+ proxy.on('proxyRes', (proxyRes, req, res) => {
29
+ proxyRes.on('close', () => {
30
+ if (!proxyRes.complete) res.destroy();
31
+ });
32
+ });
33
+
34
+ /** @type {http.RequestListener} */
35
+ const onRequest = (req, res) => {
36
+ try {
37
+ proxy.web(req, res);
38
+ } catch (err) {
39
+ logger.error('Request failed to proxy:', err);
40
+ if (res.headersSent) return void res.destroy();
41
+ res.writeHead(400, { 'content-type': 'text/plain' });
42
+ res.end('Bad Request');
43
+ }
44
+ };
45
+ const listener = ssl ? https.createServer(ssl, onRequest) : http.createServer(onRequest);
46
+ if (ws) {
47
+ listener.on('upgrade', (req, socket, head) => {
48
+ try {
49
+ proxy.ws(req, socket, head);
50
+ } catch (err) {
51
+ logger.error('Request failed to proxy:', err);
52
+ socket.destroy();
53
+ }
54
+ });
55
+ }
56
+ listener.on('error', (err) => {
57
+ logger.error('Proxy server failed:', err);
58
+ });
59
+ listener.listen(port);
60
+
61
+ proxy.address = () => listener.address();
62
+ proxy.close = (cb) => {
63
+ listener.close((err) => cb?.(err));
64
+ };
65
+ }
2
66
 
3
67
  /** @type {import('@gasket/core').ActionHandler<'startProxyServer'>} */
4
68
  export async function startProxyServer(gasket) {
@@ -9,17 +73,26 @@ export async function startProxyServer(gasket) {
9
73
 
10
74
  const opts = await gasket.execWaterfall('httpsProxy', httpsProxy);
11
75
 
12
- const { protocol = 'http', hostname = 'localhost', port = 8080, ...proxyOpts } = opts;
13
- const server = proxy.createServer(
14
- proxyOpts
15
- ).on('error', (err) => {
76
+ const { protocol = 'http', hostname = 'localhost', port = 8080, ssl, ...proxyOpts } = opts;
77
+ // The documented 2-minute default, which http-proxy-3 does not apply; without it a silent target holds the client open.
78
+ proxyOpts.proxyTimeout ??= 120000;
79
+ if (proxyOpts.target) proxyOpts.target = withPathname(proxyOpts.target);
80
+ if (proxyOpts.forward) proxyOpts.forward = withPathname(proxyOpts.forward);
81
+
82
+ const proxy = createServer(proxyOpts).on('error', (err, req, res) => {
16
83
  logger.error('Request failed to proxy:', err);
17
- }).listen(
18
- port
19
- );
84
+ // Answer the client so a failing target does not leave its connection open.
85
+ if (res instanceof ServerResponse && !res.headersSent) {
86
+ res.writeHead(502, { 'content-type': 'text/plain' });
87
+ res.end('Bad Gateway');
88
+ } else {
89
+ res?.destroy();
90
+ }
91
+ });
92
+ listen(proxy, { ssl, ws: proxyOpts.ws, port, logger });
20
93
 
21
94
  logger.info(`Proxy server started: ${protocol}://${hostname}:${port}`);
22
- return server;
95
+ return proxy;
23
96
  }
24
97
 
25
98
  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.1",
3
+ "version": "7.6.0",
4
4
  "description": "Adds support for running an https proxy",
5
5
  "type": "module",
6
6
  "types": "lib/index.d.ts",
@@ -33,20 +33,20 @@
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.1",
41
- "@gasket/core": "^7.7.3",
42
- "@gasket/plugin-logger": "^7.4.0",
43
- "@gasket/plugin-https": "^7.4.1",
44
- "create-gasket-app": "^7.4.20",
45
- "@gasket/plugin-metadata": "^7.5.9"
41
+ "@gasket/cjs": "^7.1.3",
42
+ "@gasket/core": "^7.7.7",
43
+ "@gasket/plugin-https": "^7.5.0",
44
+ "@gasket/plugin-logger": "^7.5.1",
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",
49
- "build:watch": "pnpm run build --watch",
50
50
  "lint": "eslint .",
51
51
  "lint:fix": "pnpm run lint --fix",
52
52
  "posttest": "pnpm run lint && pnpm run typecheck",