-
Notifications
You must be signed in to change notification settings - Fork 101
/
proxy.ts
418 lines (363 loc) · 12.6 KB
/
proxy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/* eslint-disable no-console */
// Webpack proxy and express config for `useProxy: true` or `standalone: true`
import { execSync } from 'child_process';
import fetch from 'node-fetch';
import express from 'express';
import path from 'path';
import type { Configuration } from 'webpack-dev-server';
import { HttpsProxyAgent } from 'https-proxy-agent';
import cookieTransform from './cookieTransform';
import router from './standalone/helpers/router';
import { getConfig, getExposedPort, isGitUrl, resolvePath } from './standalone/helpers/index';
import { checkoutRepo } from './standalone/helpers/checkout';
import { startService, stopService } from './standalone/startService';
import { NET } from './standalone/helpers';
import defaultServices from './standalone/services/default';
import { registerChrome } from './standalone/services/default/chrome';
const defaultReposDir = path.join(__dirname, 'repos');
const checkLocalAppHost = (appName: string, hostUrl: string, port: number | string) => {
const check = execSync(`curl --max-time 5 --silent --head ${hostUrl} | awk '/^HTTP/{print $2}'`).toString().trim();
if (check !== '200') {
console.error('\n' + appName[0].toUpperCase() + appName.substring(1) + ' is not running or available via ' + hostUrl);
console.log(
'\nMake sure to run `npm run start -- --port=' +
port +
'` in the ' +
appName +
" application directory to start it's webpack dev server and the bundle is built.\n"
);
return false;
} else {
return true;
}
};
type ProxyConfigItem = import('webpack-dev-server').ProxyConfigArrayItem;
const buildRoutes = (
routes: {
[route: string]: ProxyConfigItem & { host?: string };
},
target: string
) =>
Object.entries(routes || {}).map(([route, redirect]) => {
const currTarget = typeof redirect === 'object' ? redirect.host : redirect;
if (typeof redirect === 'object') {
delete redirect.host;
}
const result: ProxyConfigItem = {
context: (path: string) => path.includes(route),
target: currTarget === 'PORTAL_BACKEND_MARKER' ? target : currTarget || undefined,
secure: false,
changeOrigin: true,
autoRewrite: true,
ws: true,
onProxyReq: cookieTransform as ProxyConfigItem['onProxyReq'],
...(currTarget === 'PORTAL_BACKEND_MARKER' && { router: router(target, false) }),
...(typeof redirect === 'object' ? redirect : {}),
};
return result;
});
const buildLocalAppRoutes = (localApps: string | string[], defaultLocalAppHost: string, target: string) =>
buildRoutes(
(!Array.isArray(localApps) ? localApps.split(',') : localApps).reduce((acc, curr) => {
const [appName, appConfig] = (curr || '').split(':');
const [appPort = 8003, protocol = 'http'] = appConfig.split('~');
const appUrl = `${protocol}://${defaultLocalAppHost}:${appPort}`;
if (checkLocalAppHost(appName, appUrl, appPort)) {
console.log('Creating app proxy routes for: ' + appName + ' to ' + appUrl);
return {
...acc,
[`/apps/${appName}`]: {
host: appUrl,
},
[`/preview/apps/${appName}`]: {
host: appUrl,
},
};
} else {
process.exit();
}
}, {}),
target
);
export type ProxyOptions = {
env?: 'prod-stable' | 'prod-beta' | 'stage-stable' | 'stage-beta' | string;
customProxy?: ProxyConfigItem[];
routes?: { routes?: { [route: string]: ProxyConfigItem } } & { [route: string]: ProxyConfigItem };
routesPath?: string;
useProxy?: boolean;
proxyURL?: string;
standalone?: boolean;
port?: number;
reposDir?: string;
localChrome?: string;
appUrl?: (string | RegExp)[];
publicPath: string;
proxyVerbose?: boolean;
useCloud?: boolean;
target?: string;
keycloakUri?: string;
registry?: ((...args: any[]) => void)[];
isChrome?: boolean;
onBeforeSetupMiddleware?: (opts: { chromePath?: string }) => void;
bounceProd?: boolean;
useAgent?: boolean;
useDevBuild?: boolean;
localApps?: string;
};
const proxy = ({
env = 'ci-beta',
customProxy = [],
routes,
routesPath,
useProxy,
proxyURL = 'http://squid.corp.redhat.com:3128',
standalone,
port,
reposDir = defaultReposDir,
localChrome,
appUrl = [],
publicPath,
proxyVerbose,
useCloud = false,
target = '',
keycloakUri = '',
registry = [],
isChrome = false,
onBeforeSetupMiddleware = () => undefined,
bounceProd = false,
useAgent = true,
useDevBuild = true,
localApps = process.env.LOCAL_APPS,
}: ProxyOptions) => {
const proxy: ProxyConfigItem[] = [];
const majorEnv = env.split('-')[0];
const defaultLocalAppHost = process.env.LOCAL_APP_HOST || majorEnv + '.foo.redhat.com';
if (target === '') {
target += 'https://';
if (!['prod', 'stage'].includes(majorEnv)) {
target += majorEnv + '.';
}
target += useCloud ? 'cloud' : 'console';
if (majorEnv === 'stage') {
target += '.stage';
}
target += '.redhat.com/';
}
let agent;
const isProd = env.startsWith('prod');
const isStage = env.startsWith('stage');
const shouldBounceProdRequests = isProd && bounceProd && !useAgent;
if (isStage || (isProd && useAgent)) {
// stage is deployed with Akamai which requires a corporate proxy
agent = new HttpsProxyAgent(proxyURL);
}
if (isStage) {
// stage-stable / stage-beta branches don't exist in build repos
// Currently stage pulls from QA
env = env.replace('stage', 'qa');
}
if (!Array.isArray(appUrl)) {
appUrl = [appUrl];
}
appUrl.push(publicPath);
if (routesPath) {
routes = require(routesPath);
}
if (routes) {
routes = routes.routes || routes;
proxy.push(...buildRoutes(routes, target));
}
if (localApps && localApps.length > 0) {
proxy.push(...buildLocalAppRoutes(localApps, defaultLocalAppHost, target));
}
if (customProxy) {
proxy.push(...customProxy);
}
let standaloneConfig: ReturnType<typeof getConfig>;
if (standalone) {
standaloneConfig = getConfig(standalone, localChrome, env, port);
// Create network for services.
execSync(`docker network inspect ${NET} >/dev/null 2>&1 || docker network create ${NET}`);
// Clone repos and resolve functions
// If we manage the repos it's okay to overwrite the contents
const overwrite = reposDir === defaultReposDir;
// Resolve config functions for cross-service references
for (const [, proj] of Object.entries(standaloneConfig)) {
const { services, path, assets, register } = proj;
if (typeof register === 'function') {
registry.push(register);
}
if (isGitUrl(path)) {
// Add typical branch if not included
if (!path.includes('#')) {
proj.path = `${path}#${env}`;
}
proj.path = checkoutRepo({ repo: proj.path, reposDir, overwrite });
}
Object.keys(assets || []).forEach((key) => {
if (isGitUrl(assets[key])) {
assets[key] = checkoutRepo({ repo: assets[key], reposDir, overwrite });
}
});
// Resolve functions that depend on env, port, or assets
if (typeof services === 'function') {
proj.services = services({ env, port, assets });
}
}
// Start standalone services.
for (const [projName, proj] of Object.entries(standaloneConfig)) {
const { services, path, assets, onProxyReq, keycloakUri, register, target, ...rest } = proj;
const serviceNames: string[] = [];
for (const [subServiceName, subService] of Object.entries(proj.services || {})) {
const name = [projName, subServiceName].join('_');
// FIXME: Fix the typecasting
startService(standaloneConfig, name, subService as { args: string[]; dependsOn: string[] });
serviceNames.push(name);
const port = getExposedPort((subService as { args: string[]; dependsOn: string[] }).args);
console.log('Container', name, 'listening', port ? 'on' : '', port || '');
}
process.on('SIGINT', () => serviceNames.forEach(stopService));
if (target) {
proxy.push({
secure: false,
changeOrigin: true,
onProxyReq: cookieTransform,
target,
...rest,
});
}
}
process.on('SIGINT', () => process.exit());
}
if (useProxy) {
// Catch-all
proxy.push({
secure: false,
changeOrigin: true,
autoRewrite: true,
context: (url: string) => {
const shouldProxy = !appUrl.find((u) => (typeof u === 'string' ? url.startsWith(u) : u.test(url)));
if (shouldProxy) {
if (proxyVerbose) {
console.log('proxy', url);
}
return true;
}
return false;
},
target,
bypass: async (req, res) => {
/**
* Bypass any HTML requests if using chrome
* Serves as a historyApiFallback when refreshing on any other URL than '/'
*/
if (isChrome && !req.url.match(/\/api\//) && !req.url.match(/\./) && req.headers.accept?.includes('text/html')) {
return '/';
}
/**
* Use node-fetch to proxy all non-GET requests (this avoids all origin/host akamai policy)
* This enables using PROD proxy without VPN and agent
*/
if (shouldBounceProdRequests && req.method !== 'GET') {
const result = await fetch((target + req.url).replace(/\/\//g, '/'), {
method: req.method,
body: JSON.stringify(req.body),
headers: {
...(req.headers.cookie && {
cookie: req.headers.cookie,
}),
'Content-Type': 'application/json',
},
});
const text = await result.text();
try {
const data = JSON.parse(text);
res.status(result.status).json(data);
} catch (err) {
res.status(result.status).send(text);
}
}
return null;
},
router: router(target, useCloud),
...(agent && {
agent,
headers: {
// Staging Akamai CORS gives 403s for non-GET requests from non-origin hosts
Host: target.replace('https://', ''),
Origin: target,
},
}),
});
}
const config: Configuration = {
...(proxy.length > 0 && { proxy }),
onListening(server) {
if (useProxy || standaloneConfig) {
const host = useProxy ? `${majorEnv}.foo.redhat.com` : 'localhost';
const origin = `http${server.options.https ? 's' : ''}://${host}:${server.options.port}`;
console.log('App should run on:');
console.log('\u001b[34m'); // Use same webpack-dev-server blue
if (appUrl.length > 0) {
appUrl.slice(0, appUrl.length - 1).forEach((url) => console.log(` - ${origin}${url}`));
console.log('\x1b[0m');
console.log('Static assets are available at:');
console.log('\u001b[34m'); // Use same webpack-dev-server blue
console.log(` - ${origin}${appUrl[appUrl.length - 1]}`);
} else {
console.log(` - ${origin}`);
}
console.log('\u001b[0m');
}
},
onBeforeSetupMiddleware({ app, compiler, options }) {
app?.enable('strict routing'); // trailing slashes are mean
if (shouldBounceProdRequests) {
app?.use(express.json());
app?.use(express.urlencoded({ extended: true }));
}
/**
* Allow serving chrome assets
* This will allow running chrome as a host application
*/
if (!isChrome) {
let chromePath = localChrome;
if (standaloneConfig) {
if (standaloneConfig.chrome) {
chromePath = resolvePath(reposDir, standaloneConfig.chrome.path);
keycloakUri = standaloneConfig.chrome.keycloakUri;
}
} else if (!localChrome && useProxy) {
const chromeConfig = typeof defaultServices.chrome === 'function' ? defaultServices.chrome({}) : defaultServices.chrome;
const chromeEnv = useDevBuild ? (env.includes('-beta') ? 'dev-beta' : 'dev-stable') : env;
chromePath = checkoutRepo({
repo: `${chromeConfig.path}#${chromeEnv}`,
reposDir,
overwrite: true,
});
}
onBeforeSetupMiddleware({ chromePath });
if (app && chromePath) {
registerChrome({
app,
chromePath,
keycloakUri,
https: Boolean(options.https),
proxyVerbose,
});
}
}
registry.forEach((cb) =>
cb({
app,
options,
compiler,
config: standaloneConfig,
})
);
},
};
return config;
};
export default proxy;
module.exports = proxy;