@backstage/plugin-proxy-backend 0.4.3 → 0.4.4
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/CHANGELOG.md +9 -0
- package/alpha/package.json +3 -3
- package/dist/alpha.cjs.js +35 -0
- package/dist/alpha.cjs.js.map +1 -0
- package/dist/alpha.d.ts +10 -0
- package/dist/cjs/router-6fef2ff7.cjs.js +181 -0
- package/dist/cjs/router-6fef2ff7.cjs.js.map +1 -0
- package/dist/index.cjs.js +4 -201
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +10 -20
- package/package.json +18 -8
- package/dist/index.alpha.d.ts +0 -50
- package/dist/index.beta.d.ts +0 -44
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# @backstage/plugin-proxy-backend
|
|
2
2
|
|
|
3
|
+
## 0.4.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- f6c651fe3c6c: Switched to using `"exports"` field for `/alpha` subpath export.
|
|
8
|
+
- Updated dependencies
|
|
9
|
+
- @backstage/backend-common@0.19.9
|
|
10
|
+
- @backstage/backend-plugin-api@0.6.7
|
|
11
|
+
|
|
3
12
|
## 0.4.3
|
|
4
13
|
|
|
5
14
|
### Patch Changes
|
package/alpha/package.json
CHANGED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var backendCommon = require('@backstage/backend-common');
|
|
6
|
+
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
7
|
+
var router = require('./cjs/router-6fef2ff7.cjs.js');
|
|
8
|
+
require('express-promise-router');
|
|
9
|
+
require('http-proxy-middleware');
|
|
10
|
+
|
|
11
|
+
var alpha = backendPluginApi.createBackendPlugin({
|
|
12
|
+
pluginId: "proxy",
|
|
13
|
+
register(env) {
|
|
14
|
+
env.registerInit({
|
|
15
|
+
deps: {
|
|
16
|
+
config: backendPluginApi.coreServices.rootConfig,
|
|
17
|
+
discovery: backendPluginApi.coreServices.discovery,
|
|
18
|
+
logger: backendPluginApi.coreServices.logger,
|
|
19
|
+
httpRouter: backendPluginApi.coreServices.httpRouter
|
|
20
|
+
},
|
|
21
|
+
async init({ config, discovery, logger, httpRouter }) {
|
|
22
|
+
httpRouter.use(
|
|
23
|
+
await router.createRouter({
|
|
24
|
+
config,
|
|
25
|
+
discovery,
|
|
26
|
+
logger: backendCommon.loggerToWinstonLogger(logger)
|
|
27
|
+
})
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
exports["default"] = alpha;
|
|
35
|
+
//# sourceMappingURL=alpha.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"alpha.cjs.js","sources":["../src/alpha.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport {\n createBackendPlugin,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { createRouter } from './service/router';\n\n/**\n * The proxy backend plugin.\n *\n * @alpha\n */\nexport default createBackendPlugin({\n pluginId: 'proxy',\n register(env) {\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n discovery: coreServices.discovery,\n logger: coreServices.logger,\n httpRouter: coreServices.httpRouter,\n },\n async init({ config, discovery, logger, httpRouter }) {\n httpRouter.use(\n await createRouter({\n config,\n discovery,\n logger: loggerToWinstonLogger(logger),\n }),\n );\n },\n });\n },\n});\n"],"names":["createBackendPlugin","coreServices","createRouter","loggerToWinstonLogger"],"mappings":";;;;;;;;;;AA4BA,YAAeA,oCAAoB,CAAA;AAAA,EACjC,QAAU,EAAA,OAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,QAAQC,6BAAa,CAAA,UAAA;AAAA,QACrB,WAAWA,6BAAa,CAAA,SAAA;AAAA,QACxB,QAAQA,6BAAa,CAAA,MAAA;AAAA,QACrB,YAAYA,6BAAa,CAAA,UAAA;AAAA,OAC3B;AAAA,MACA,MAAM,IAAK,CAAA,EAAE,QAAQ,SAAW,EAAA,MAAA,EAAQ,YAAc,EAAA;AACpD,QAAW,UAAA,CAAA,GAAA;AAAA,UACT,MAAMC,mBAAa,CAAA;AAAA,YACjB,MAAA;AAAA,YACA,SAAA;AAAA,YACA,MAAA,EAAQC,oCAAsB,MAAM,CAAA;AAAA,WACrC,CAAA;AAAA,SACH,CAAA;AAAA,OACF;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC,CAAA;;;;"}
|
package/dist/alpha.d.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var Router = require('express-promise-router');
|
|
4
|
+
var httpProxyMiddleware = require('http-proxy-middleware');
|
|
5
|
+
|
|
6
|
+
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
7
|
+
|
|
8
|
+
var Router__default = /*#__PURE__*/_interopDefaultLegacy(Router);
|
|
9
|
+
|
|
10
|
+
const safeForwardHeaders = [
|
|
11
|
+
// https://fetch.spec.whatwg.org/#cors-safelisted-request-header
|
|
12
|
+
"cache-control",
|
|
13
|
+
"content-language",
|
|
14
|
+
"content-length",
|
|
15
|
+
"content-type",
|
|
16
|
+
"expires",
|
|
17
|
+
"last-modified",
|
|
18
|
+
"pragma",
|
|
19
|
+
// host is overridden by default. if changeOrigin is configured to false,
|
|
20
|
+
// we assume this is a intentional and should also be forwarded.
|
|
21
|
+
"host",
|
|
22
|
+
// other headers that we assume to be ok
|
|
23
|
+
"accept",
|
|
24
|
+
"accept-language",
|
|
25
|
+
"user-agent"
|
|
26
|
+
];
|
|
27
|
+
function buildMiddleware(pathPrefix, logger, route, config, reviveConsumedRequestBodies) {
|
|
28
|
+
var _a;
|
|
29
|
+
const fullConfig = typeof config === "string" ? { target: config } : { ...config };
|
|
30
|
+
const targetType = typeof fullConfig.target;
|
|
31
|
+
if (targetType !== "string") {
|
|
32
|
+
throw new Error(
|
|
33
|
+
`Proxy target for route "${route}" must be a string, but is of type ${targetType}`
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
new URL(fullConfig.target);
|
|
38
|
+
} catch {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`Proxy target is not a valid URL: ${(_a = fullConfig.target) != null ? _a : ""}`
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
if (fullConfig.pathRewrite === void 0) {
|
|
44
|
+
let routeWithSlash = route.endsWith("/") ? route : `${route}/`;
|
|
45
|
+
if (!pathPrefix.endsWith("/") && !routeWithSlash.startsWith("/")) {
|
|
46
|
+
routeWithSlash = `/${routeWithSlash}`;
|
|
47
|
+
} else if (pathPrefix.endsWith("/") && routeWithSlash.startsWith("/")) {
|
|
48
|
+
routeWithSlash = routeWithSlash.substring(1);
|
|
49
|
+
}
|
|
50
|
+
fullConfig.pathRewrite = {
|
|
51
|
+
[`^${pathPrefix}${routeWithSlash}?`]: "/"
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
if (fullConfig.changeOrigin === void 0) {
|
|
55
|
+
fullConfig.changeOrigin = true;
|
|
56
|
+
}
|
|
57
|
+
fullConfig.logProvider = () => logger;
|
|
58
|
+
fullConfig.logLevel = "debug";
|
|
59
|
+
const requestHeaderAllowList = new Set(
|
|
60
|
+
[
|
|
61
|
+
// allow all safe headers
|
|
62
|
+
...safeForwardHeaders,
|
|
63
|
+
// allow all headers that are set by the proxy
|
|
64
|
+
...fullConfig.headers && Object.keys(fullConfig.headers) || [],
|
|
65
|
+
// allow all configured headers
|
|
66
|
+
...fullConfig.allowedHeaders || []
|
|
67
|
+
].map((h) => h.toLocaleLowerCase())
|
|
68
|
+
);
|
|
69
|
+
const filter = (_pathname, req) => {
|
|
70
|
+
var _a2, _b;
|
|
71
|
+
const headerNames = Object.keys(req.headers);
|
|
72
|
+
headerNames.forEach((h) => {
|
|
73
|
+
if (!requestHeaderAllowList.has(h.toLocaleLowerCase())) {
|
|
74
|
+
delete req.headers[h];
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
return (_b = (_a2 = fullConfig == null ? void 0 : fullConfig.allowedMethods) == null ? void 0 : _a2.includes(req.method)) != null ? _b : true;
|
|
78
|
+
};
|
|
79
|
+
filter.toString = () => route;
|
|
80
|
+
const responseHeaderAllowList = new Set(
|
|
81
|
+
[
|
|
82
|
+
// allow all safe headers
|
|
83
|
+
...safeForwardHeaders,
|
|
84
|
+
// allow all configured headers
|
|
85
|
+
...fullConfig.allowedHeaders || []
|
|
86
|
+
].map((h) => h.toLocaleLowerCase())
|
|
87
|
+
);
|
|
88
|
+
fullConfig.onProxyRes = (proxyRes) => {
|
|
89
|
+
const headerNames = Object.keys(proxyRes.headers);
|
|
90
|
+
headerNames.forEach((h) => {
|
|
91
|
+
if (!responseHeaderAllowList.has(h.toLocaleLowerCase())) {
|
|
92
|
+
delete proxyRes.headers[h];
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
if (reviveConsumedRequestBodies) {
|
|
97
|
+
fullConfig.onProxyReq = httpProxyMiddleware.fixRequestBody;
|
|
98
|
+
}
|
|
99
|
+
return httpProxyMiddleware.createProxyMiddleware(filter, fullConfig);
|
|
100
|
+
}
|
|
101
|
+
function readProxyConfig(config, logger) {
|
|
102
|
+
var _a, _b;
|
|
103
|
+
const endpoints = (_a = config.getOptionalConfig("proxy.endpoints")) == null ? void 0 : _a.get();
|
|
104
|
+
if (endpoints) {
|
|
105
|
+
return endpoints;
|
|
106
|
+
}
|
|
107
|
+
const root = (_b = config.getOptionalConfig("proxy")) == null ? void 0 : _b.get();
|
|
108
|
+
if (!root) {
|
|
109
|
+
return {};
|
|
110
|
+
}
|
|
111
|
+
const rootEndpoints = Object.fromEntries(
|
|
112
|
+
Object.entries(root).filter(([key]) => key.startsWith("/"))
|
|
113
|
+
);
|
|
114
|
+
if (Object.keys(rootEndpoints).length === 0) {
|
|
115
|
+
return {};
|
|
116
|
+
}
|
|
117
|
+
logger.warn(
|
|
118
|
+
"Configuring proxy endpoints in the root 'proxy' configuration is deprecated. Move this configuration to 'proxy.endpoints' instead."
|
|
119
|
+
);
|
|
120
|
+
return rootEndpoints;
|
|
121
|
+
}
|
|
122
|
+
async function createRouter(options) {
|
|
123
|
+
var _a, _b, _c, _d;
|
|
124
|
+
const router = Router__default["default"]();
|
|
125
|
+
let currentRouter = Router__default["default"]();
|
|
126
|
+
const skipInvalidProxies = (_b = (_a = options.skipInvalidProxies) != null ? _a : options.config.getOptionalBoolean("proxy.skipInvalidProxies")) != null ? _b : false;
|
|
127
|
+
const reviveConsumedRequestBodies = (_d = (_c = options.reviveConsumedRequestBodies) != null ? _c : options.config.getOptionalBoolean("proxy.reviveConsumedRequestBodies")) != null ? _d : false;
|
|
128
|
+
const proxyOptions = {
|
|
129
|
+
skipInvalidProxies,
|
|
130
|
+
reviveConsumedRequestBodies,
|
|
131
|
+
logger: options.logger
|
|
132
|
+
};
|
|
133
|
+
const externalUrl = await options.discovery.getExternalBaseUrl("proxy");
|
|
134
|
+
const { pathname: pathPrefix } = new URL(externalUrl);
|
|
135
|
+
const proxyConfig = readProxyConfig(options.config, options.logger);
|
|
136
|
+
configureMiddlewares(proxyOptions, currentRouter, pathPrefix, proxyConfig);
|
|
137
|
+
router.use((...args) => currentRouter(...args));
|
|
138
|
+
if (options.config.subscribe) {
|
|
139
|
+
let currentKey = JSON.stringify(proxyConfig);
|
|
140
|
+
options.config.subscribe(() => {
|
|
141
|
+
const newProxyConfig = readProxyConfig(options.config, options.logger);
|
|
142
|
+
const newKey = JSON.stringify(newProxyConfig);
|
|
143
|
+
if (currentKey !== newKey) {
|
|
144
|
+
currentKey = newKey;
|
|
145
|
+
currentRouter = Router__default["default"]();
|
|
146
|
+
configureMiddlewares(
|
|
147
|
+
proxyOptions,
|
|
148
|
+
currentRouter,
|
|
149
|
+
pathPrefix,
|
|
150
|
+
newProxyConfig
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return router;
|
|
156
|
+
}
|
|
157
|
+
function configureMiddlewares(options, router, pathPrefix, proxyConfig) {
|
|
158
|
+
Object.entries(proxyConfig).forEach(([route, proxyRouteConfig]) => {
|
|
159
|
+
try {
|
|
160
|
+
router.use(
|
|
161
|
+
route,
|
|
162
|
+
buildMiddleware(
|
|
163
|
+
pathPrefix,
|
|
164
|
+
options.logger,
|
|
165
|
+
route,
|
|
166
|
+
proxyRouteConfig,
|
|
167
|
+
options.reviveConsumedRequestBodies
|
|
168
|
+
)
|
|
169
|
+
);
|
|
170
|
+
} catch (e) {
|
|
171
|
+
if (options.skipInvalidProxies) {
|
|
172
|
+
options.logger.warn(`skipped configuring ${route} due to ${e.message}`);
|
|
173
|
+
} else {
|
|
174
|
+
throw e;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
exports.createRouter = createRouter;
|
|
181
|
+
//# sourceMappingURL=router-6fef2ff7.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router-6fef2ff7.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport {\n createProxyMiddleware,\n fixRequestBody,\n Options,\n RequestHandler,\n} from 'http-proxy-middleware';\nimport { Logger } from 'winston';\nimport http from 'http';\nimport { PluginEndpointDiscovery } from '@backstage/backend-common';\n\n// A list of headers that are always forwarded to the proxy targets.\nconst safeForwardHeaders = [\n // https://fetch.spec.whatwg.org/#cors-safelisted-request-header\n 'cache-control',\n 'content-language',\n 'content-length',\n 'content-type',\n 'expires',\n 'last-modified',\n 'pragma',\n\n // host is overridden by default. if changeOrigin is configured to false,\n // we assume this is a intentional and should also be forwarded.\n 'host',\n\n // other headers that we assume to be ok\n 'accept',\n 'accept-language',\n 'user-agent',\n];\n\n/** @public */\nexport interface RouterOptions {\n logger: Logger;\n config: Config;\n discovery: PluginEndpointDiscovery;\n skipInvalidProxies?: boolean;\n reviveConsumedRequestBodies?: boolean;\n}\n\nexport interface ProxyConfig extends Options {\n allowedMethods?: string[];\n allowedHeaders?: string[];\n reviveRequestBody?: boolean;\n}\n\n// Creates a proxy middleware, possibly with defaults added on top of the\n// given config.\nexport function buildMiddleware(\n pathPrefix: string,\n logger: Logger,\n route: string,\n config: string | ProxyConfig,\n reviveConsumedRequestBodies?: boolean,\n): RequestHandler {\n const fullConfig =\n typeof config === 'string' ? { target: config } : { ...config };\n\n // Validate that target is a valid URL.\n const targetType = typeof fullConfig.target;\n if (targetType !== 'string') {\n throw new Error(\n `Proxy target for route \"${route}\" must be a string, but is of type ${targetType}`,\n );\n }\n try {\n // eslint-disable-next-line no-new\n new URL(fullConfig.target! as string);\n } catch {\n throw new Error(\n `Proxy target is not a valid URL: ${fullConfig.target ?? ''}`,\n );\n }\n\n // Default is to do a path rewrite that strips out the proxy's path prefix\n // and the rest of the route.\n if (fullConfig.pathRewrite === undefined) {\n let routeWithSlash = route.endsWith('/') ? route : `${route}/`;\n\n if (!pathPrefix.endsWith('/') && !routeWithSlash.startsWith('/')) {\n // Need to insert a / between pathPrefix and routeWithSlash\n routeWithSlash = `/${routeWithSlash}`;\n } else if (pathPrefix.endsWith('/') && routeWithSlash.startsWith('/')) {\n // Never expect this to happen at this point in time as\n // pathPrefix is set using `getExternalBaseUrl` which \"Returns the\n // external HTTP base backend URL for a given plugin,\n // **without a trailing slash.**\". But in case this changes in future, we\n // need to drop a / on either pathPrefix or routeWithSlash\n routeWithSlash = routeWithSlash.substring(1);\n }\n\n // The ? makes the slash optional for the rewrite, so that a base path without an ending slash\n // will also be matched (e.g. '/sample' and then requesting just '/api/proxy/sample' without an\n // ending slash). Otherwise the target gets called with the full '/api/proxy/sample' path\n // appended.\n fullConfig.pathRewrite = {\n [`^${pathPrefix}${routeWithSlash}?`]: '/',\n };\n }\n\n // Default is to update the Host header to the target\n if (fullConfig.changeOrigin === undefined) {\n fullConfig.changeOrigin = true;\n }\n\n // Attach the logger to the proxy config\n fullConfig.logProvider = () => logger;\n // http-proxy-middleware uses this log level to check if it should log the\n // requests that it proxies. Setting this to the most verbose log level\n // ensures that it always logs these requests. Our logger ends up deciding\n // if the logs are displayed or not.\n fullConfig.logLevel = 'debug';\n\n // Only return the allowed HTTP headers to not forward unwanted secret headers\n const requestHeaderAllowList = new Set<string>(\n [\n // allow all safe headers\n ...safeForwardHeaders,\n\n // allow all headers that are set by the proxy\n ...((fullConfig.headers && Object.keys(fullConfig.headers)) || []),\n\n // allow all configured headers\n ...(fullConfig.allowedHeaders || []),\n ].map(h => h.toLocaleLowerCase()),\n );\n\n // Use the custom middleware filter to do two things:\n // 1. Remove any headers not in the allow list to stop them being forwarded\n // 2. Only permit the allowed HTTP methods if configured\n //\n // We are filtering the proxy request headers here rather than in\n // `onProxyReq` because when global-agent is enabled then `onProxyReq`\n // fires _after_ the agent has already sent the headers to the proxy\n // target, causing a ERR_HTTP_HEADERS_SENT crash\n const filter = (_pathname: string, req: http.IncomingMessage): boolean => {\n const headerNames = Object.keys(req.headers);\n headerNames.forEach(h => {\n if (!requestHeaderAllowList.has(h.toLocaleLowerCase())) {\n delete req.headers[h];\n }\n });\n\n return fullConfig?.allowedMethods?.includes(req.method!) ?? true;\n };\n // Makes http-proxy-middleware logs look nicer and include the mount path\n filter.toString = () => route;\n\n // Only forward the allowed HTTP headers to not forward unwanted secret headers\n const responseHeaderAllowList = new Set<string>(\n [\n // allow all safe headers\n ...safeForwardHeaders,\n\n // allow all configured headers\n ...(fullConfig.allowedHeaders || []),\n ].map(h => h.toLocaleLowerCase()),\n );\n\n // only forward the allowed headers in backend->client\n fullConfig.onProxyRes = (proxyRes: http.IncomingMessage) => {\n const headerNames = Object.keys(proxyRes.headers);\n\n headerNames.forEach(h => {\n if (!responseHeaderAllowList.has(h.toLocaleLowerCase())) {\n delete proxyRes.headers[h];\n }\n });\n };\n\n if (reviveConsumedRequestBodies) {\n fullConfig.onProxyReq = fixRequestBody;\n }\n\n return createProxyMiddleware(filter, fullConfig);\n}\n\nfunction readProxyConfig(config: Config, logger: Logger): unknown {\n const endpoints = config.getOptionalConfig('proxy.endpoints')?.get();\n if (endpoints) {\n return endpoints;\n }\n\n const root = config.getOptionalConfig('proxy')?.get();\n if (!root) {\n return {};\n }\n\n const rootEndpoints = Object.fromEntries(\n Object.entries(root).filter(([key]) => key.startsWith('/')),\n );\n if (Object.keys(rootEndpoints).length === 0) {\n return {};\n }\n\n logger.warn(\n \"Configuring proxy endpoints in the root 'proxy' configuration is deprecated. Move this configuration to 'proxy.endpoints' instead.\",\n );\n\n return rootEndpoints;\n}\n\n/**\n * Creates a new {@link https://expressjs.com/en/api.html#router | \"express router\"} that proxy each target configured under the `proxy` key of the config\n * @example\n * ```ts\n * let router = await createRouter({logger, config, discovery});\n * ```\n * @config\n * ```yaml\n * proxy:\n * simple-example: http://simple.example.com:8080 # Opt 1 Simple URL String\n * '/larger-example/v1': # Opt 2 `http-proxy-middleware` compatible object\n * target: http://larger.example.com:8080/svc.v1\n * headers:\n * Authorization: Bearer ${EXAMPLE_AUTH_TOKEN}\n *```\n * @see https://backstage.io/docs/plugins/proxying\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const router = Router();\n let currentRouter = Router();\n\n const skipInvalidProxies =\n options.skipInvalidProxies ??\n options.config.getOptionalBoolean('proxy.skipInvalidProxies') ??\n false;\n const reviveConsumedRequestBodies =\n options.reviveConsumedRequestBodies ??\n options.config.getOptionalBoolean('proxy.reviveConsumedRequestBodies') ??\n false;\n const proxyOptions = {\n skipInvalidProxies,\n reviveConsumedRequestBodies,\n logger: options.logger,\n };\n\n const externalUrl = await options.discovery.getExternalBaseUrl('proxy');\n const { pathname: pathPrefix } = new URL(externalUrl);\n\n const proxyConfig = readProxyConfig(options.config, options.logger);\n configureMiddlewares(proxyOptions, currentRouter, pathPrefix, proxyConfig);\n router.use((...args) => currentRouter(...args));\n\n if (options.config.subscribe) {\n let currentKey = JSON.stringify(proxyConfig);\n\n options.config.subscribe(() => {\n const newProxyConfig = readProxyConfig(options.config, options.logger);\n const newKey = JSON.stringify(newProxyConfig);\n\n if (currentKey !== newKey) {\n currentKey = newKey;\n currentRouter = Router();\n configureMiddlewares(\n proxyOptions,\n currentRouter,\n pathPrefix,\n newProxyConfig,\n );\n }\n });\n }\n\n return router;\n}\n\nfunction configureMiddlewares(\n options: {\n reviveConsumedRequestBodies: boolean;\n skipInvalidProxies: boolean;\n logger: Logger;\n },\n router: express.Router,\n pathPrefix: string,\n proxyConfig: any,\n) {\n Object.entries<any>(proxyConfig).forEach(([route, proxyRouteConfig]) => {\n try {\n router.use(\n route,\n buildMiddleware(\n pathPrefix,\n options.logger,\n route,\n proxyRouteConfig,\n options.reviveConsumedRequestBodies,\n ),\n );\n } catch (e) {\n if (options.skipInvalidProxies) {\n options.logger.warn(`skipped configuring ${route} due to ${e.message}`);\n } else {\n throw e;\n }\n }\n });\n}\n"],"names":["_a","fixRequestBody","createProxyMiddleware","Router"],"mappings":";;;;;;;;;AA8BA,MAAM,kBAAqB,GAAA;AAAA;AAAA,EAEzB,eAAA;AAAA,EACA,kBAAA;AAAA,EACA,gBAAA;AAAA,EACA,cAAA;AAAA,EACA,SAAA;AAAA,EACA,eAAA;AAAA,EACA,QAAA;AAAA;AAAA;AAAA,EAIA,MAAA;AAAA;AAAA,EAGA,QAAA;AAAA,EACA,iBAAA;AAAA,EACA,YAAA;AACF,CAAA,CAAA;AAmBO,SAAS,eACd,CAAA,UAAA,EACA,MACA,EAAA,KAAA,EACA,QACA,2BACgB,EAAA;AAzElB,EAAA,IAAA,EAAA,CAAA;AA0EE,EAAM,MAAA,UAAA,GACJ,OAAO,MAAA,KAAW,QAAW,GAAA,EAAE,QAAQ,MAAO,EAAA,GAAI,EAAE,GAAG,MAAO,EAAA,CAAA;AAGhE,EAAM,MAAA,UAAA,GAAa,OAAO,UAAW,CAAA,MAAA,CAAA;AACrC,EAAA,IAAI,eAAe,QAAU,EAAA;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,wBAAA,EAA2B,KAAK,CAAA,mCAAA,EAAsC,UAAU,CAAA,CAAA;AAAA,KAClF,CAAA;AAAA,GACF;AACA,EAAI,IAAA;AAEF,IAAI,IAAA,GAAA,CAAI,WAAW,MAAiB,CAAA,CAAA;AAAA,GAC9B,CAAA,MAAA;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAoC,iCAAA,EAAA,CAAA,EAAA,GAAA,UAAA,CAAW,MAAX,KAAA,IAAA,GAAA,EAAA,GAAqB,EAAE,CAAA,CAAA;AAAA,KAC7D,CAAA;AAAA,GACF;AAIA,EAAI,IAAA,UAAA,CAAW,g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'__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
5
|
+
var router = require('./cjs/router-6fef2ff7.cjs.js');
|
|
6
|
+
require('express-promise-router');
|
|
7
|
+
require('http-proxy-middleware');
|
|
9
8
|
|
|
10
|
-
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
11
9
|
|
|
12
|
-
var Router__default = /*#__PURE__*/_interopDefaultLegacy(Router);
|
|
13
10
|
|
|
14
|
-
|
|
15
|
-
// https://fetch.spec.whatwg.org/#cors-safelisted-request-header
|
|
16
|
-
"cache-control",
|
|
17
|
-
"content-language",
|
|
18
|
-
"content-length",
|
|
19
|
-
"content-type",
|
|
20
|
-
"expires",
|
|
21
|
-
"last-modified",
|
|
22
|
-
"pragma",
|
|
23
|
-
// host is overridden by default. if changeOrigin is configured to false,
|
|
24
|
-
// we assume this is a intentional and should also be forwarded.
|
|
25
|
-
"host",
|
|
26
|
-
// other headers that we assume to be ok
|
|
27
|
-
"accept",
|
|
28
|
-
"accept-language",
|
|
29
|
-
"user-agent"
|
|
30
|
-
];
|
|
31
|
-
function buildMiddleware(pathPrefix, logger, route, config, reviveConsumedRequestBodies) {
|
|
32
|
-
var _a;
|
|
33
|
-
const fullConfig = typeof config === "string" ? { target: config } : { ...config };
|
|
34
|
-
const targetType = typeof fullConfig.target;
|
|
35
|
-
if (targetType !== "string") {
|
|
36
|
-
throw new Error(
|
|
37
|
-
`Proxy target for route "${route}" must be a string, but is of type ${targetType}`
|
|
38
|
-
);
|
|
39
|
-
}
|
|
40
|
-
try {
|
|
41
|
-
new URL(fullConfig.target);
|
|
42
|
-
} catch {
|
|
43
|
-
throw new Error(
|
|
44
|
-
`Proxy target is not a valid URL: ${(_a = fullConfig.target) != null ? _a : ""}`
|
|
45
|
-
);
|
|
46
|
-
}
|
|
47
|
-
if (fullConfig.pathRewrite === void 0) {
|
|
48
|
-
let routeWithSlash = route.endsWith("/") ? route : `${route}/`;
|
|
49
|
-
if (!pathPrefix.endsWith("/") && !routeWithSlash.startsWith("/")) {
|
|
50
|
-
routeWithSlash = `/${routeWithSlash}`;
|
|
51
|
-
} else if (pathPrefix.endsWith("/") && routeWithSlash.startsWith("/")) {
|
|
52
|
-
routeWithSlash = routeWithSlash.substring(1);
|
|
53
|
-
}
|
|
54
|
-
fullConfig.pathRewrite = {
|
|
55
|
-
[`^${pathPrefix}${routeWithSlash}?`]: "/"
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
if (fullConfig.changeOrigin === void 0) {
|
|
59
|
-
fullConfig.changeOrigin = true;
|
|
60
|
-
}
|
|
61
|
-
fullConfig.logProvider = () => logger;
|
|
62
|
-
fullConfig.logLevel = "debug";
|
|
63
|
-
const requestHeaderAllowList = new Set(
|
|
64
|
-
[
|
|
65
|
-
// allow all safe headers
|
|
66
|
-
...safeForwardHeaders,
|
|
67
|
-
// allow all headers that are set by the proxy
|
|
68
|
-
...fullConfig.headers && Object.keys(fullConfig.headers) || [],
|
|
69
|
-
// allow all configured headers
|
|
70
|
-
...fullConfig.allowedHeaders || []
|
|
71
|
-
].map((h) => h.toLocaleLowerCase())
|
|
72
|
-
);
|
|
73
|
-
const filter = (_pathname, req) => {
|
|
74
|
-
var _a2, _b;
|
|
75
|
-
const headerNames = Object.keys(req.headers);
|
|
76
|
-
headerNames.forEach((h) => {
|
|
77
|
-
if (!requestHeaderAllowList.has(h.toLocaleLowerCase())) {
|
|
78
|
-
delete req.headers[h];
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
return (_b = (_a2 = fullConfig == null ? void 0 : fullConfig.allowedMethods) == null ? void 0 : _a2.includes(req.method)) != null ? _b : true;
|
|
82
|
-
};
|
|
83
|
-
filter.toString = () => route;
|
|
84
|
-
const responseHeaderAllowList = new Set(
|
|
85
|
-
[
|
|
86
|
-
// allow all safe headers
|
|
87
|
-
...safeForwardHeaders,
|
|
88
|
-
// allow all configured headers
|
|
89
|
-
...fullConfig.allowedHeaders || []
|
|
90
|
-
].map((h) => h.toLocaleLowerCase())
|
|
91
|
-
);
|
|
92
|
-
fullConfig.onProxyRes = (proxyRes) => {
|
|
93
|
-
const headerNames = Object.keys(proxyRes.headers);
|
|
94
|
-
headerNames.forEach((h) => {
|
|
95
|
-
if (!responseHeaderAllowList.has(h.toLocaleLowerCase())) {
|
|
96
|
-
delete proxyRes.headers[h];
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
};
|
|
100
|
-
if (reviveConsumedRequestBodies) {
|
|
101
|
-
fullConfig.onProxyReq = httpProxyMiddleware.fixRequestBody;
|
|
102
|
-
}
|
|
103
|
-
return httpProxyMiddleware.createProxyMiddleware(filter, fullConfig);
|
|
104
|
-
}
|
|
105
|
-
function readProxyConfig(config, logger) {
|
|
106
|
-
var _a, _b;
|
|
107
|
-
const endpoints = (_a = config.getOptionalConfig("proxy.endpoints")) == null ? void 0 : _a.get();
|
|
108
|
-
if (endpoints) {
|
|
109
|
-
return endpoints;
|
|
110
|
-
}
|
|
111
|
-
const root = (_b = config.getOptionalConfig("proxy")) == null ? void 0 : _b.get();
|
|
112
|
-
if (!root) {
|
|
113
|
-
return {};
|
|
114
|
-
}
|
|
115
|
-
const rootEndpoints = Object.fromEntries(
|
|
116
|
-
Object.entries(root).filter(([key]) => key.startsWith("/"))
|
|
117
|
-
);
|
|
118
|
-
if (Object.keys(rootEndpoints).length === 0) {
|
|
119
|
-
return {};
|
|
120
|
-
}
|
|
121
|
-
logger.warn(
|
|
122
|
-
"Configuring proxy endpoints in the root 'proxy' configuration is deprecated. Move this configuration to 'proxy.endpoints' instead."
|
|
123
|
-
);
|
|
124
|
-
return rootEndpoints;
|
|
125
|
-
}
|
|
126
|
-
async function createRouter(options) {
|
|
127
|
-
var _a, _b, _c, _d;
|
|
128
|
-
const router = Router__default["default"]();
|
|
129
|
-
let currentRouter = Router__default["default"]();
|
|
130
|
-
const skipInvalidProxies = (_b = (_a = options.skipInvalidProxies) != null ? _a : options.config.getOptionalBoolean("proxy.skipInvalidProxies")) != null ? _b : false;
|
|
131
|
-
const reviveConsumedRequestBodies = (_d = (_c = options.reviveConsumedRequestBodies) != null ? _c : options.config.getOptionalBoolean("proxy.reviveConsumedRequestBodies")) != null ? _d : false;
|
|
132
|
-
const proxyOptions = {
|
|
133
|
-
skipInvalidProxies,
|
|
134
|
-
reviveConsumedRequestBodies,
|
|
135
|
-
logger: options.logger
|
|
136
|
-
};
|
|
137
|
-
const externalUrl = await options.discovery.getExternalBaseUrl("proxy");
|
|
138
|
-
const { pathname: pathPrefix } = new URL(externalUrl);
|
|
139
|
-
const proxyConfig = readProxyConfig(options.config, options.logger);
|
|
140
|
-
configureMiddlewares(proxyOptions, currentRouter, pathPrefix, proxyConfig);
|
|
141
|
-
router.use((...args) => currentRouter(...args));
|
|
142
|
-
if (options.config.subscribe) {
|
|
143
|
-
let currentKey = JSON.stringify(proxyConfig);
|
|
144
|
-
options.config.subscribe(() => {
|
|
145
|
-
const newProxyConfig = readProxyConfig(options.config, options.logger);
|
|
146
|
-
const newKey = JSON.stringify(newProxyConfig);
|
|
147
|
-
if (currentKey !== newKey) {
|
|
148
|
-
currentKey = newKey;
|
|
149
|
-
currentRouter = Router__default["default"]();
|
|
150
|
-
configureMiddlewares(
|
|
151
|
-
proxyOptions,
|
|
152
|
-
currentRouter,
|
|
153
|
-
pathPrefix,
|
|
154
|
-
newProxyConfig
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
return router;
|
|
160
|
-
}
|
|
161
|
-
function configureMiddlewares(options, router, pathPrefix, proxyConfig) {
|
|
162
|
-
Object.entries(proxyConfig).forEach(([route, proxyRouteConfig]) => {
|
|
163
|
-
try {
|
|
164
|
-
router.use(
|
|
165
|
-
route,
|
|
166
|
-
buildMiddleware(
|
|
167
|
-
pathPrefix,
|
|
168
|
-
options.logger,
|
|
169
|
-
route,
|
|
170
|
-
proxyRouteConfig,
|
|
171
|
-
options.reviveConsumedRequestBodies
|
|
172
|
-
)
|
|
173
|
-
);
|
|
174
|
-
} catch (e) {
|
|
175
|
-
if (options.skipInvalidProxies) {
|
|
176
|
-
options.logger.warn(`skipped configuring ${route} due to ${e.message}`);
|
|
177
|
-
} else {
|
|
178
|
-
throw e;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
const proxyPlugin = backendPluginApi.createBackendPlugin({
|
|
185
|
-
pluginId: "proxy",
|
|
186
|
-
register(env) {
|
|
187
|
-
env.registerInit({
|
|
188
|
-
deps: {
|
|
189
|
-
config: backendPluginApi.coreServices.rootConfig,
|
|
190
|
-
discovery: backendPluginApi.coreServices.discovery,
|
|
191
|
-
logger: backendPluginApi.coreServices.logger,
|
|
192
|
-
httpRouter: backendPluginApi.coreServices.httpRouter
|
|
193
|
-
},
|
|
194
|
-
async init({ config, discovery, logger, httpRouter }) {
|
|
195
|
-
httpRouter.use(
|
|
196
|
-
await createRouter({
|
|
197
|
-
config,
|
|
198
|
-
discovery,
|
|
199
|
-
logger: backendCommon.loggerToWinstonLogger(logger)
|
|
200
|
-
})
|
|
201
|
-
);
|
|
202
|
-
}
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
});
|
|
206
|
-
|
|
207
|
-
exports.createRouter = createRouter;
|
|
208
|
-
exports["default"] = proxyPlugin;
|
|
11
|
+
exports.createRouter = router.createRouter;
|
|
209
12
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/service/router.ts","../src/plugin.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport {\n createProxyMiddleware,\n fixRequestBody,\n Options,\n RequestHandler,\n} from 'http-proxy-middleware';\nimport { Logger } from 'winston';\nimport http from 'http';\nimport { PluginEndpointDiscovery } from '@backstage/backend-common';\n\n// A list of headers that are always forwarded to the proxy targets.\nconst safeForwardHeaders = [\n // https://fetch.spec.whatwg.org/#cors-safelisted-request-header\n 'cache-control',\n 'content-language',\n 'content-length',\n 'content-type',\n 'expires',\n 'last-modified',\n 'pragma',\n\n // host is overridden by default. if changeOrigin is configured to false,\n // we assume this is a intentional and should also be forwarded.\n 'host',\n\n // other headers that we assume to be ok\n 'accept',\n 'accept-language',\n 'user-agent',\n];\n\n/** @public */\nexport interface RouterOptions {\n logger: Logger;\n config: Config;\n discovery: PluginEndpointDiscovery;\n skipInvalidProxies?: boolean;\n reviveConsumedRequestBodies?: boolean;\n}\n\nexport interface ProxyConfig extends Options {\n allowedMethods?: string[];\n allowedHeaders?: string[];\n reviveRequestBody?: boolean;\n}\n\n// Creates a proxy middleware, possibly with defaults added on top of the\n// given config.\nexport function buildMiddleware(\n pathPrefix: string,\n logger: Logger,\n route: string,\n config: string | ProxyConfig,\n reviveConsumedRequestBodies?: boolean,\n): RequestHandler {\n const fullConfig =\n typeof config === 'string' ? { target: config } : { ...config };\n\n // Validate that target is a valid URL.\n const targetType = typeof fullConfig.target;\n if (targetType !== 'string') {\n throw new Error(\n `Proxy target for route \"${route}\" must be a string, but is of type ${targetType}`,\n );\n }\n try {\n // eslint-disable-next-line no-new\n new URL(fullConfig.target! as string);\n } catch {\n throw new Error(\n `Proxy target is not a valid URL: ${fullConfig.target ?? ''}`,\n );\n }\n\n // Default is to do a path rewrite that strips out the proxy's path prefix\n // and the rest of the route.\n if (fullConfig.pathRewrite === undefined) {\n let routeWithSlash = route.endsWith('/') ? route : `${route}/`;\n\n if (!pathPrefix.endsWith('/') && !routeWithSlash.startsWith('/')) {\n // Need to insert a / between pathPrefix and routeWithSlash\n routeWithSlash = `/${routeWithSlash}`;\n } else if (pathPrefix.endsWith('/') && routeWithSlash.startsWith('/')) {\n // Never expect this to happen at this point in time as\n // pathPrefix is set using `getExternalBaseUrl` which \"Returns the\n // external HTTP base backend URL for a given plugin,\n // **without a trailing slash.**\". But in case this changes in future, we\n // need to drop a / on either pathPrefix or routeWithSlash\n routeWithSlash = routeWithSlash.substring(1);\n }\n\n // The ? makes the slash optional for the rewrite, so that a base path without an ending slash\n // will also be matched (e.g. '/sample' and then requesting just '/api/proxy/sample' without an\n // ending slash). Otherwise the target gets called with the full '/api/proxy/sample' path\n // appended.\n fullConfig.pathRewrite = {\n [`^${pathPrefix}${routeWithSlash}?`]: '/',\n };\n }\n\n // Default is to update the Host header to the target\n if (fullConfig.changeOrigin === undefined) {\n fullConfig.changeOrigin = true;\n }\n\n // Attach the logger to the proxy config\n fullConfig.logProvider = () => logger;\n // http-proxy-middleware uses this log level to check if it should log the\n // requests that it proxies. Setting this to the most verbose log level\n // ensures that it always logs these requests. Our logger ends up deciding\n // if the logs are displayed or not.\n fullConfig.logLevel = 'debug';\n\n // Only return the allowed HTTP headers to not forward unwanted secret headers\n const requestHeaderAllowList = new Set<string>(\n [\n // allow all safe headers\n ...safeForwardHeaders,\n\n // allow all headers that are set by the proxy\n ...((fullConfig.headers && Object.keys(fullConfig.headers)) || []),\n\n // allow all configured headers\n ...(fullConfig.allowedHeaders || []),\n ].map(h => h.toLocaleLowerCase()),\n );\n\n // Use the custom middleware filter to do two things:\n // 1. Remove any headers not in the allow list to stop them being forwarded\n // 2. Only permit the allowed HTTP methods if configured\n //\n // We are filtering the proxy request headers here rather than in\n // `onProxyReq` because when global-agent is enabled then `onProxyReq`\n // fires _after_ the agent has already sent the headers to the proxy\n // target, causing a ERR_HTTP_HEADERS_SENT crash\n const filter = (_pathname: string, req: http.IncomingMessage): boolean => {\n const headerNames = Object.keys(req.headers);\n headerNames.forEach(h => {\n if (!requestHeaderAllowList.has(h.toLocaleLowerCase())) {\n delete req.headers[h];\n }\n });\n\n return fullConfig?.allowedMethods?.includes(req.method!) ?? true;\n };\n // Makes http-proxy-middleware logs look nicer and include the mount path\n filter.toString = () => route;\n\n // Only forward the allowed HTTP headers to not forward unwanted secret headers\n const responseHeaderAllowList = new Set<string>(\n [\n // allow all safe headers\n ...safeForwardHeaders,\n\n // allow all configured headers\n ...(fullConfig.allowedHeaders || []),\n ].map(h => h.toLocaleLowerCase()),\n );\n\n // only forward the allowed headers in backend->client\n fullConfig.onProxyRes = (proxyRes: http.IncomingMessage) => {\n const headerNames = Object.keys(proxyRes.headers);\n\n headerNames.forEach(h => {\n if (!responseHeaderAllowList.has(h.toLocaleLowerCase())) {\n delete proxyRes.headers[h];\n }\n });\n };\n\n if (reviveConsumedRequestBodies) {\n fullConfig.onProxyReq = fixRequestBody;\n }\n\n return createProxyMiddleware(filter, fullConfig);\n}\n\nfunction readProxyConfig(config: Config, logger: Logger): unknown {\n const endpoints = config.getOptionalConfig('proxy.endpoints')?.get();\n if (endpoints) {\n return endpoints;\n }\n\n const root = config.getOptionalConfig('proxy')?.get();\n if (!root) {\n return {};\n }\n\n const rootEndpoints = Object.fromEntries(\n Object.entries(root).filter(([key]) => key.startsWith('/')),\n );\n if (Object.keys(rootEndpoints).length === 0) {\n return {};\n }\n\n logger.warn(\n \"Configuring proxy endpoints in the root 'proxy' configuration is deprecated. Move this configuration to 'proxy.endpoints' instead.\",\n );\n\n return rootEndpoints;\n}\n\n/**\n * Creates a new {@link https://expressjs.com/en/api.html#router | \"express router\"} that proxy each target configured under the `proxy` key of the config\n * @example\n * ```ts\n * let router = await createRouter({logger, config, discovery});\n * ```\n * @config\n * ```yaml\n * proxy:\n * simple-example: http://simple.example.com:8080 # Opt 1 Simple URL String\n * '/larger-example/v1': # Opt 2 `http-proxy-middleware` compatible object\n * target: http://larger.example.com:8080/svc.v1\n * headers:\n * Authorization: Bearer ${EXAMPLE_AUTH_TOKEN}\n *```\n * @see https://backstage.io/docs/plugins/proxying\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const router = Router();\n let currentRouter = Router();\n\n const skipInvalidProxies =\n options.skipInvalidProxies ??\n options.config.getOptionalBoolean('proxy.skipInvalidProxies') ??\n false;\n const reviveConsumedRequestBodies =\n options.reviveConsumedRequestBodies ??\n options.config.getOptionalBoolean('proxy.reviveConsumedRequestBodies') ??\n false;\n const proxyOptions = {\n skipInvalidProxies,\n reviveConsumedRequestBodies,\n logger: options.logger,\n };\n\n const externalUrl = await options.discovery.getExternalBaseUrl('proxy');\n const { pathname: pathPrefix } = new URL(externalUrl);\n\n const proxyConfig = readProxyConfig(options.config, options.logger);\n configureMiddlewares(proxyOptions, currentRouter, pathPrefix, proxyConfig);\n router.use((...args) => currentRouter(...args));\n\n if (options.config.subscribe) {\n let currentKey = JSON.stringify(proxyConfig);\n\n options.config.subscribe(() => {\n const newProxyConfig = readProxyConfig(options.config, options.logger);\n const newKey = JSON.stringify(newProxyConfig);\n\n if (currentKey !== newKey) {\n currentKey = newKey;\n currentRouter = Router();\n configureMiddlewares(\n proxyOptions,\n currentRouter,\n pathPrefix,\n newProxyConfig,\n );\n }\n });\n }\n\n return router;\n}\n\nfunction configureMiddlewares(\n options: {\n reviveConsumedRequestBodies: boolean;\n skipInvalidProxies: boolean;\n logger: Logger;\n },\n router: express.Router,\n pathPrefix: string,\n proxyConfig: any,\n) {\n Object.entries<any>(proxyConfig).forEach(([route, proxyRouteConfig]) => {\n try {\n router.use(\n route,\n buildMiddleware(\n pathPrefix,\n options.logger,\n route,\n proxyRouteConfig,\n options.reviveConsumedRequestBodies,\n ),\n );\n } catch (e) {\n if (options.skipInvalidProxies) {\n options.logger.warn(`skipped configuring ${route} due to ${e.message}`);\n } else {\n throw e;\n }\n }\n });\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport {\n createBackendPlugin,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { createRouter } from './service/router';\n\n/**\n * The proxy backend plugin.\n *\n * @alpha\n */\nexport const proxyPlugin = createBackendPlugin({\n pluginId: 'proxy',\n register(env) {\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n discovery: coreServices.discovery,\n logger: coreServices.logger,\n httpRouter: coreServices.httpRouter,\n },\n async init({ config, discovery, logger, httpRouter }) {\n httpRouter.use(\n await createRouter({\n config,\n discovery,\n logger: loggerToWinstonLogger(logger),\n }),\n );\n },\n });\n },\n});\n"],"names":["_a","fixRequestBody","createProxyMiddleware","Router","createBackendPlugin","coreServices","loggerToWinstonLogger"],"mappings":";;;;;;;;;;;;;AA8BA,MAAM,kBAAqB,GAAA;AAAA;AAAA,EAEzB,eAAA;AAAA,EACA,kBAAA;AAAA,EACA,gBAAA;AAAA,EACA,cAAA;AAAA,EACA,SAAA;AAAA,EACA,eAAA;AAAA,EACA,QAAA;AAAA;AAAA;AAAA,EAIA,MAAA;AAAA;AAAA,EAGA,QAAA;AAAA,EACA,iBAAA;AAAA,EACA,YAAA;AACF,CAAA,CAAA;AAmBO,SAAS,eACd,CAAA,UAAA,EACA,MACA,EAAA,KAAA,EACA,QACA,2BACgB,EAAA;AAzElB,EAAA,IAAA,EAAA,CAAA;AA0EE,EAAM,MAAA,UAAA,GACJ,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mappings":";;;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A Backstage backend plugin that helps you set up proxy endpoints in the backend
|
|
3
|
-
*
|
|
4
|
-
* @packageDocumentation
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { BackendFeature } from '@backstage/backend-plugin-api';
|
|
8
1
|
import { Config } from '@backstage/config';
|
|
9
2
|
import express from 'express';
|
|
10
3
|
import { Logger } from 'winston';
|
|
11
4
|
import { PluginEndpointDiscovery } from '@backstage/backend-common';
|
|
12
5
|
|
|
6
|
+
/** @public */
|
|
7
|
+
interface RouterOptions {
|
|
8
|
+
logger: Logger;
|
|
9
|
+
config: Config;
|
|
10
|
+
discovery: PluginEndpointDiscovery;
|
|
11
|
+
skipInvalidProxies?: boolean;
|
|
12
|
+
reviveConsumedRequestBodies?: boolean;
|
|
13
|
+
}
|
|
13
14
|
/**
|
|
14
15
|
* Creates a new {@link https://expressjs.com/en/api.html#router | "express router"} that proxy each target configured under the `proxy` key of the config
|
|
15
16
|
* @example
|
|
@@ -28,17 +29,6 @@ import { PluginEndpointDiscovery } from '@backstage/backend-common';
|
|
|
28
29
|
* @see https://backstage.io/docs/plugins/proxying
|
|
29
30
|
* @public
|
|
30
31
|
*/
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
/* Excluded from this release type: proxyPlugin */
|
|
34
|
-
|
|
35
|
-
/** @public */
|
|
36
|
-
export declare interface RouterOptions {
|
|
37
|
-
logger: Logger;
|
|
38
|
-
config: Config;
|
|
39
|
-
discovery: PluginEndpointDiscovery;
|
|
40
|
-
skipInvalidProxies?: boolean;
|
|
41
|
-
reviveConsumedRequestBodies?: boolean;
|
|
42
|
-
}
|
|
32
|
+
declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
43
33
|
|
|
44
|
-
export { }
|
|
34
|
+
export { RouterOptions, createRouter };
|
package/package.json
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-proxy-backend",
|
|
3
3
|
"description": "A Backstage backend plugin that helps you set up proxy endpoints in the backend",
|
|
4
|
-
"version": "0.4.
|
|
5
|
-
"main": "dist/index.cjs.js",
|
|
6
|
-
"types": "dist/index.d.ts",
|
|
4
|
+
"version": "0.4.4",
|
|
5
|
+
"main": "./dist/index.cjs.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"publishConfig": {
|
|
9
|
-
"access": "public"
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
"
|
|
9
|
+
"access": "public"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"require": "./dist/index.cjs.js",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.cjs.js"
|
|
16
|
+
},
|
|
17
|
+
"./alpha": {
|
|
18
|
+
"require": "./dist/alpha.cjs.js",
|
|
19
|
+
"types": "./dist/alpha.d.ts",
|
|
20
|
+
"default": "./dist/alpha.cjs.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
13
23
|
},
|
|
14
24
|
"backstage": {
|
|
15
25
|
"role": "backend-plugin"
|
|
@@ -25,7 +35,7 @@
|
|
|
25
35
|
],
|
|
26
36
|
"scripts": {
|
|
27
37
|
"start": "backstage-cli package start",
|
|
28
|
-
"build": "backstage-cli package build
|
|
38
|
+
"build": "backstage-cli package build",
|
|
29
39
|
"lint": "backstage-cli package lint",
|
|
30
40
|
"test": "backstage-cli package test",
|
|
31
41
|
"prepack": "backstage-cli package prepack",
|
package/dist/index.alpha.d.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A Backstage backend plugin that helps you set up proxy endpoints in the backend
|
|
3
|
-
*
|
|
4
|
-
* @packageDocumentation
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { BackendFeature } from '@backstage/backend-plugin-api';
|
|
8
|
-
import { Config } from '@backstage/config';
|
|
9
|
-
import express from 'express';
|
|
10
|
-
import { Logger } from 'winston';
|
|
11
|
-
import { PluginEndpointDiscovery } from '@backstage/backend-common';
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Creates a new {@link https://expressjs.com/en/api.html#router | "express router"} that proxy each target configured under the `proxy` key of the config
|
|
15
|
-
* @example
|
|
16
|
-
* ```ts
|
|
17
|
-
* let router = await createRouter({logger, config, discovery});
|
|
18
|
-
* ```
|
|
19
|
-
* @config
|
|
20
|
-
* ```yaml
|
|
21
|
-
* proxy:
|
|
22
|
-
* simple-example: http://simple.example.com:8080 # Opt 1 Simple URL String
|
|
23
|
-
* '/larger-example/v1': # Opt 2 `http-proxy-middleware` compatible object
|
|
24
|
-
* target: http://larger.example.com:8080/svc.v1
|
|
25
|
-
* headers:
|
|
26
|
-
* Authorization: Bearer ${EXAMPLE_AUTH_TOKEN}
|
|
27
|
-
*```
|
|
28
|
-
* @see https://backstage.io/docs/plugins/proxying
|
|
29
|
-
* @public
|
|
30
|
-
*/
|
|
31
|
-
export declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* The proxy backend plugin.
|
|
35
|
-
*
|
|
36
|
-
* @alpha
|
|
37
|
-
*/
|
|
38
|
-
declare const proxyPlugin: () => BackendFeature;
|
|
39
|
-
export default proxyPlugin;
|
|
40
|
-
|
|
41
|
-
/** @public */
|
|
42
|
-
export declare interface RouterOptions {
|
|
43
|
-
logger: Logger;
|
|
44
|
-
config: Config;
|
|
45
|
-
discovery: PluginEndpointDiscovery;
|
|
46
|
-
skipInvalidProxies?: boolean;
|
|
47
|
-
reviveConsumedRequestBodies?: boolean;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export { }
|
package/dist/index.beta.d.ts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A Backstage backend plugin that helps you set up proxy endpoints in the backend
|
|
3
|
-
*
|
|
4
|
-
* @packageDocumentation
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { BackendFeature } from '@backstage/backend-plugin-api';
|
|
8
|
-
import { Config } from '@backstage/config';
|
|
9
|
-
import express from 'express';
|
|
10
|
-
import { Logger } from 'winston';
|
|
11
|
-
import { PluginEndpointDiscovery } from '@backstage/backend-common';
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Creates a new {@link https://expressjs.com/en/api.html#router | "express router"} that proxy each target configured under the `proxy` key of the config
|
|
15
|
-
* @example
|
|
16
|
-
* ```ts
|
|
17
|
-
* let router = await createRouter({logger, config, discovery});
|
|
18
|
-
* ```
|
|
19
|
-
* @config
|
|
20
|
-
* ```yaml
|
|
21
|
-
* proxy:
|
|
22
|
-
* simple-example: http://simple.example.com:8080 # Opt 1 Simple URL String
|
|
23
|
-
* '/larger-example/v1': # Opt 2 `http-proxy-middleware` compatible object
|
|
24
|
-
* target: http://larger.example.com:8080/svc.v1
|
|
25
|
-
* headers:
|
|
26
|
-
* Authorization: Bearer ${EXAMPLE_AUTH_TOKEN}
|
|
27
|
-
*```
|
|
28
|
-
* @see https://backstage.io/docs/plugins/proxying
|
|
29
|
-
* @public
|
|
30
|
-
*/
|
|
31
|
-
export declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
32
|
-
|
|
33
|
-
/* Excluded from this release type: proxyPlugin */
|
|
34
|
-
|
|
35
|
-
/** @public */
|
|
36
|
-
export declare interface RouterOptions {
|
|
37
|
-
logger: Logger;
|
|
38
|
-
config: Config;
|
|
39
|
-
discovery: PluginEndpointDiscovery;
|
|
40
|
-
skipInvalidProxies?: boolean;
|
|
41
|
-
reviveConsumedRequestBodies?: boolean;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export { }
|