@salesforce/pwa-kit-runtime 3.8.0-preview.0-basepath → 3.8.0-preview.2-basepath

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.
Files changed (52) hide show
  1. package/package.json +6 -5
  2. package/ssr/server/build-remote-server.js +1159 -0
  3. package/ssr/server/build-remote-server.test.js +41 -0
  4. package/ssr/server/constants.js +37 -0
  5. package/ssr/server/express.js +462 -0
  6. package/ssr/server/express.lambda.test.js +390 -0
  7. package/ssr/server/express.test.js +963 -0
  8. package/ssr/server/test_fixtures/favicon.ico +0 -0
  9. package/ssr/server/test_fixtures/loadable-stats.json +1 -0
  10. package/ssr/server/test_fixtures/localhost.pem +45 -0
  11. package/ssr/server/test_fixtures/main.js +7 -0
  12. package/ssr/server/test_fixtures/mobify.png +0 -0
  13. package/ssr/server/test_fixtures/server-renderer.js +12 -0
  14. package/ssr/server/test_fixtures/worker.js +7 -0
  15. package/ssr/server/test_fixtures/worker.js.map +1 -0
  16. package/utils/logger-factory.js +154 -0
  17. package/utils/logger-factory.test.js +71 -0
  18. package/utils/logger-instance.js +19 -0
  19. package/utils/middleware/index.js +16 -0
  20. package/utils/middleware/security.js +111 -0
  21. package/utils/middleware/security.test.js +110 -0
  22. package/utils/morgan-stream.js +28 -0
  23. package/utils/ssr-cache.js +177 -0
  24. package/utils/ssr-cache.test.js +64 -0
  25. package/utils/ssr-config.client.js +23 -0
  26. package/utils/ssr-config.client.test.js +25 -0
  27. package/utils/ssr-config.js +20 -0
  28. package/utils/ssr-config.server.js +98 -0
  29. package/utils/ssr-config.server.test.js +50 -0
  30. package/utils/ssr-namespace-paths.js +60 -0
  31. package/utils/ssr-namespace-paths.test.js +30 -0
  32. package/utils/ssr-paths.js +51 -0
  33. package/utils/ssr-paths.test.js +49 -0
  34. package/utils/ssr-proxying.js +859 -0
  35. package/utils/ssr-proxying.test.js +593 -0
  36. package/utils/ssr-request-processing.js +164 -0
  37. package/utils/ssr-request-processing.test.js +95 -0
  38. package/utils/ssr-server/cached-response.js +116 -0
  39. package/utils/ssr-server/configure-proxy.js +304 -0
  40. package/utils/ssr-server/metrics-sender.js +204 -0
  41. package/utils/ssr-server/outgoing-request-hook.js +139 -0
  42. package/utils/ssr-server/parse-end-parameters.js +38 -0
  43. package/utils/ssr-server/process-express-response.js +56 -0
  44. package/utils/ssr-server/process-lambda-response.js +43 -0
  45. package/utils/ssr-server/update-global-agent-options.js +41 -0
  46. package/utils/ssr-server/update-global-agent-options.test.js +28 -0
  47. package/utils/ssr-server/utils.js +124 -0
  48. package/utils/ssr-server/utils.test.js +69 -0
  49. package/utils/ssr-server/wrap-response-write.js +40 -0
  50. package/utils/ssr-server.js +115 -0
  51. package/utils/ssr-server.test.js +869 -0
  52. package/utils/ssr-shared.js +183 -0
@@ -0,0 +1,859 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.rfc1123 = exports.rewriteSetCookies = exports.rewriteProxyResponseHeaders = exports.rewriteProxyRequestHeaders = exports.rewriteDomain = exports.parseHost = exports.cookieAsString = exports.X_PROXY_REQUEST_URL = exports.X_MOBIFY_REQUEST_CLASS = exports.X_HEADERS_TO_REMOVE_PROXY = exports.X_HEADERS_TO_REMOVE_ORIGIN = exports.X_HEADERS_TO_ADD = exports.MAX_URL_LENGTH_BYTES = exports.Headers = exports.ALLOWED_CACHING_PROXY_REQUEST_HEADERS = void 0;
7
+ var _setCookieParser = require("set-cookie-parser");
8
+ var _headerCase = _interopRequireDefault(require("header-case"));
9
+ var _url = require("url");
10
+ var _loggerInstance = _interopRequireDefault(require("./logger-instance"));
11
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
12
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
13
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
14
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
15
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
16
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /*
17
+ * Copyright (c) 2021, salesforce.com, inc.
18
+ * All rights reserved.
19
+ * SPDX-License-Identifier: BSD-3-Clause
20
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
21
+ */ /**
22
+ * @module progressive-web-sdk/utils/ssr-proxying
23
+ */ /*
24
+ There are some special requirements for this module, which is used in the
25
+ SDK and also in Lambda@Edge functions run by CloudFront. Specifically:
26
+ - Don't add any functionality in here that is not required by the
27
+ proxying code.
28
+ - Avoid importing any other modules not explicitly used by this code
29
+ */
30
+ const AC_ALLOW_ORIGIN = 'access-control-allow-origin';
31
+ const HOST = 'host';
32
+ const LOCATION = 'location';
33
+ const ORIGIN = 'origin';
34
+ const SET_COOKIE = 'set-cookie';
35
+ const USER_AGENT = 'user-agent';
36
+ const HEADER_FORMATS = ['http', 'aws'];
37
+ const X_PROXY_REQUEST_URL = exports.X_PROXY_REQUEST_URL = 'x-proxy-request-url';
38
+ const X_MOBIFY_REQUEST_CLASS = exports.X_MOBIFY_REQUEST_CLASS = 'x-mobify-request-class';
39
+ const MAX_URL_LENGTH_BYTES = exports.MAX_URL_LENGTH_BYTES = 8192;
40
+
41
+ /**
42
+ * This class provides a representation of HTTP request or response
43
+ * headers, that operates in the same way in multiple contexts
44
+ * (i.e. within the Express app as well as the request-processor).
45
+ *
46
+ * Within a Headers instance, headers are referenced using lower-case
47
+ * names. Use getHeader to access the value for a header. If there
48
+ * are multiple values, this will return the first value. This class
49
+ * internally supports round-trip preservation of multi-value headers,
50
+ * but does not yet provide a way to access them.
51
+ */
52
+ class Headers {
53
+ /*
54
+ A Lambda@Edge event contains headers in this form:
55
+ "headers": {
56
+ "host": [
57
+ {
58
+ "key": "Host",
59
+ "value": "d111111abcdef8.cloudfront.net"
60
+ }
61
+ ],
62
+ "user-agent": [
63
+ {
64
+ "key": "User-Agent",
65
+ "value": "curl/7.18.1"
66
+ }
67
+ ]
68
+ }
69
+ The http.IncomingMessage format is a simple object:
70
+ {
71
+ 'user-agent': 'curl/7.22.0',
72
+ host: '127.0.0.1:8000'
73
+ }
74
+ However, for IncomingMessage:
75
+ Duplicates of age, authorization, content-length, content-type, etag,
76
+ expires, from, host, if-modified-since, if-unmodified-since,
77
+ last-modified, location, max-forwards, proxy-authorization, referer,
78
+ retry-after, or user-agent are discarded.
79
+ The value for set-cookie is always an array. Duplicates are added to the array.
80
+ For all other headers, the values are joined together with ','
81
+ */
82
+
83
+ /**
84
+ * Construct a Headers object from either an AWS Lambda Event headers
85
+ * object, or an http.IncomingMessage headers object.
86
+ *
87
+ * Project code should never need to call this constructor.
88
+ *
89
+ * @private
90
+ * @param headers {Object} the input headers
91
+ * @param format {String} either 'http' or 'aws'
92
+ */
93
+ constructor(headers, format) {
94
+ if (!HEADER_FORMATS.includes(format)) {
95
+ throw new Error(`Headers format must be one of ${HEADER_FORMATS.join(', ')}`);
96
+ }
97
+ this.httpFormat = format === 'http';
98
+
99
+ // Within this class, headers are represented by an object that maps
100
+ // header names (lower-case) to arrays of values.
101
+ this.headers = {};
102
+ for (const [key, values] of Object.entries(headers)) {
103
+ // For http format, the value will be a comma-separated
104
+ // list of values (https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2)
105
+ // For AWS format, the value is an array of key/value objects.
106
+ if (this.httpFormat) {
107
+ // The Set-Cookie header is always passed to us as an array,
108
+ // so we do not split.
109
+ if (key === SET_COOKIE) {
110
+ this.headers[key] = values.slice();
111
+ } else {
112
+ this.headers[key] = values.split(/,\s*/).map(value => value.trim());
113
+ }
114
+ } else {
115
+ this.headers[key] = values.map(value => value.value.trim());
116
+ }
117
+ }
118
+ this._modified = false;
119
+ }
120
+
121
+ /**
122
+ * Return true if and only if any set or delete methods were called on
123
+ * this instance after construction. This does not actually test if
124
+ * the headers values have been changed, just whether any mutating
125
+ * methods have been called.
126
+ * @returns {Boolean}
127
+ */
128
+ get modified() {
129
+ return this._modified;
130
+ }
131
+
132
+ /**
133
+ * Return an array of the header keys (all lower-case)
134
+ */
135
+ keys() {
136
+ return Object.keys(this.headers);
137
+ }
138
+
139
+ /**
140
+ * Get the value of the set-cookie header(s), returning an array
141
+ * of strings. Always returns an array, even if it's empty.
142
+ */
143
+ getSetCookie() {
144
+ return this.headers[SET_COOKIE] || [];
145
+ }
146
+
147
+ /**
148
+ * Set the value of the set-cookie header(s)
149
+ * @param values {string[]}
150
+ */
151
+ setSetCookie(values) {
152
+ this._modified = true;
153
+ if (!(values && values.length)) {
154
+ delete this.headers[SET_COOKIE];
155
+ return;
156
+ }
157
+
158
+ // Clone the array
159
+ this.headers[SET_COOKIE] = values.slice();
160
+ }
161
+
162
+ /**
163
+ * Return the FIRST value of the header with the given key.
164
+ * This is for single-value headers only: Location, Access-Control-*, etc
165
+ * If the header is not present, returns undefined.
166
+ * @param key {String} header name
167
+ */
168
+ getHeader(key) {
169
+ const keyLC = key.toLowerCase();
170
+ const values = this.headers[keyLC];
171
+ if (!values) {
172
+ return undefined;
173
+ }
174
+ return values[0];
175
+ }
176
+
177
+ /**
178
+ * Set the value of the header with the given key. This is for single-
179
+ * value headers only (see getHeader). Setting the value removes ALL other
180
+ * values for the given key.
181
+ * @param key {String} header name
182
+ * @param value {String} header value
183
+ */
184
+ setHeader(key, value) {
185
+ this._modified = true;
186
+ const keyLC = key.toLowerCase();
187
+ this.headers[keyLC] = [value];
188
+ }
189
+
190
+ /**
191
+ * Remove any header with the given key
192
+ * @param key
193
+ */
194
+ deleteHeader(key) {
195
+ this._modified = true;
196
+ const keyLC = key.toLowerCase();
197
+ delete this.headers[keyLC];
198
+ }
199
+
200
+ /**
201
+ * Return the headers in AWS (Lambda event) format.
202
+ *
203
+ * Project code should never need to use this method.
204
+ */
205
+ toAWSFormat() {
206
+ const result = {};
207
+ for (const [key, values] of Object.entries(this.headers)) {
208
+ // Some customer servers return headers with unusual keys; for
209
+ // example, 'cached_response'. Underscores are technically legal
210
+ // in header keys, but are unexpected. The problem is that the
211
+ // header-case package maps underscore to '-' to get "legal"
212
+ // names, which breaks Lambda validation. So if the key
213
+ // contains an underscore, we use it as-is.
214
+ const finalKey = key.includes('_') ? key : (0, _headerCase.default)(key);
215
+ result[key] = values.map(value => ({
216
+ key: finalKey,
217
+ value
218
+ }));
219
+ }
220
+ return result;
221
+ }
222
+
223
+ /**
224
+ * Return the headers in Express (http.IncomingMessage) format.
225
+ *
226
+ * RFC2616 allows some flexibility in how multiple values are
227
+ * combined into a single header value. We separate with ', '
228
+ * rather than just ',' to maintain previous behaviour.
229
+ *
230
+ * Project code should never need to use this method.
231
+ */
232
+ toHTTPFormat() {
233
+ const result = {};
234
+ for (const [key, values] of Object.entries(this.headers)) {
235
+ // The Set-Cookie header is always returned as an array
236
+ if (key === SET_COOKIE) {
237
+ result[key] = values.slice();
238
+ } else {
239
+ result[key] = values.join(', ');
240
+ }
241
+ }
242
+ return result;
243
+ }
244
+
245
+ /**
246
+ * Return the headers in the same format (aws or http) that was
247
+ * used to construct them.
248
+ *
249
+ * Project code should never need to use this method.
250
+ */
251
+ toObject() {
252
+ return this.httpFormat ? this.toHTTPFormat() : this.toAWSFormat();
253
+ }
254
+ }
255
+ exports.Headers = Headers;
256
+ const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
257
+ const monthAbbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
258
+
259
+ // Return the given number as a 2-digit string with a leading zero
260
+ const leadingZero = n => {
261
+ const s = Number(n).toString();
262
+ return s.length > 1 ? s : '0' + s;
263
+ };
264
+
265
+ /**
266
+ * Return the given date as an RFC1123-format string, suitable for
267
+ * use in a Set-Cookie or Date header. The result is always in UTC.
268
+ * @function
269
+ * @param date {Date}
270
+ * @returns {String}
271
+ */
272
+ const rfc1123 = date => {
273
+ const time = [leadingZero(date.getUTCHours()), leadingZero(date.getUTCMinutes()), leadingZero(date.getUTCSeconds())].join(':');
274
+ return [`${dayNames[date.getUTCDay()]},`, leadingZero(date.getUTCDate()), monthAbbr[date.getUTCMonth()], date.getUTCFullYear(), time, 'GMT'].join(' ');
275
+ };
276
+
277
+ /**
278
+ * Given a cookie object parsed by set-cookie-parser,
279
+ * return a set-cookie header value for it.
280
+ * @private
281
+ */
282
+ exports.rfc1123 = rfc1123;
283
+ const cookieAsString = cookie => {
284
+ const elements = [`${cookie.name}=${cookie.value}`];
285
+ if (cookie.path) {
286
+ elements.push(`Path=${cookie.path}`);
287
+ }
288
+ if (cookie.expires) {
289
+ // This is a Date object and must be represented as
290
+ // an HTTP-date timestamp (RFC1123 format). For example,
291
+ // Wed, 24-Oct-2018 00:13:20 GMT
292
+ elements.push(`Expires=${rfc1123(cookie.expires)}`);
293
+ }
294
+ if (cookie.domain) {
295
+ elements.push(`Domain=${cookie.domain}`);
296
+ }
297
+ if (cookie.maxAge) {
298
+ elements.push(`Max-Age=${cookie.maxAge}`);
299
+ }
300
+ if (cookie.secure) {
301
+ elements.push('Secure');
302
+ }
303
+ if (cookie.httpOnly) {
304
+ elements.push('HttpOnly');
305
+ }
306
+ if (cookie.sameSite) {
307
+ elements.push(`SameSite=${cookie.sameSite}`);
308
+ }
309
+ return elements.join('; ');
310
+ };
311
+ exports.cookieAsString = cookieAsString;
312
+ const IPV6 = 'IPV6';
313
+ const IPV4 = 'IPV4';
314
+ const LOCALHOST = 'localhost';
315
+
316
+ /**
317
+ * An array of {type, regexp, isIPOrLocalhost} objects, where the type is used
318
+ * to determine how to get a port, regexp will spot an IPv4, IPv6 or hostname,
319
+ * and the isIPOrLocalhost flag is true for IP addresses or locahost, false for
320
+ * hostnames. The main reason for detecting IP address/localhost is to determine
321
+ * whether it can have subdomains.
322
+ * @private
323
+ */
324
+ const HOST_AND_PORT_TESTS = [
325
+ // IPV6 address plus port
326
+ {
327
+ type: IPV6,
328
+ regexp: /^\[([a-fA-F0-9:]+)\]:(\d+)$/,
329
+ isIPOrLocalhost: true,
330
+ hasPort: true
331
+ },
332
+ // IPV6 address without port
333
+ {
334
+ type: IPV6,
335
+ regexp: /^([a-fA-F0-9:]+)$/,
336
+ isIPOrLocalhost: true,
337
+ hasPort: false
338
+ },
339
+ // IPV4 address plus port
340
+ {
341
+ type: IPV4,
342
+ regexp: /^(\d+\.\d+\.\d+\.\d+):(\d+)$/,
343
+ isIPOrLocalhost: true,
344
+ hasPort: true
345
+ },
346
+ // IPV4 address plus without port
347
+ {
348
+ type: IPV4,
349
+ regexp: /^(\d+\.\d+\.\d+\.\d+)$/,
350
+ isIPOrLocalhost: true,
351
+ hasPort: false
352
+ },
353
+ // localhost plus port
354
+ {
355
+ type: LOCALHOST,
356
+ regexp: /^(localhost):(\d+)$/,
357
+ isIPOrLocalhost: true,
358
+ hasPort: true
359
+ },
360
+ // localhost without port
361
+ {
362
+ type: LOCALHOST,
363
+ regexp: /^(localhost)$/,
364
+ isIPOrLocalhost: true,
365
+ hasPort: false
366
+ },
367
+ // hostname plus port
368
+ {
369
+ type: null,
370
+ regexp: /(.+):\d+/,
371
+ isIPOrLocalhost: false,
372
+ // False means the hostname may have a subdomain
373
+ hasPort: true
374
+ }];
375
+
376
+ /**
377
+ * @typedef {Object} ParsedHost
378
+ * @property host {String} The host (10.10.10.10:port), which includes the port (if any)
379
+ * @property hostname {String} The hostname (10.10.10.10), which excludes the port
380
+ * @property port {String} The host's port
381
+ * @property isIPOrLocalhost {Boolean} Whether the hostname is an IP or localhost
382
+ */
383
+ /**
384
+ * Given a hostname that may be a hostname or ip address optionally
385
+ * followed by a port, return an object with 'host' being the ip address,
386
+ * the hostname, a port (if there is one), and 'isIPOrLocalhost' true for an ip
387
+ * address or localhost, false for a hostname
388
+ * @private
389
+ * @param host {String} Can be localhost, an IP or domain name
390
+ * @return {ParsedHost}
391
+ */
392
+ const parseHost = host => {
393
+ for (const test of HOST_AND_PORT_TESTS) {
394
+ const match = test.regexp.exec(host);
395
+ if (!match) {
396
+ continue;
397
+ }
398
+ const result = {
399
+ host,
400
+ hostname: match[1],
401
+ isIPOrLocalhost: test.isIPOrLocalhost
402
+ };
403
+
404
+ // Split apart and get the hostname and port from the host
405
+ if (test.hasPort) {
406
+ let parts;
407
+ switch (test.type) {
408
+ case IPV6:
409
+ // Filter out empty nodes fromt he array. We only care about
410
+ // the ones that have values
411
+ parts = result.host.split(test.regexp).filter(part => part.length > 0);
412
+ break;
413
+ case IPV4:
414
+ case LOCALHOST:
415
+ default:
416
+ parts = result.host.split(':');
417
+ break;
418
+ }
419
+ ;
420
+ [result.hostname, result.port] = parts;
421
+ }
422
+ return result;
423
+ }
424
+ return {
425
+ host,
426
+ hostname: host,
427
+ isIPOrLocalhost: false
428
+ };
429
+ };
430
+
431
+ // Cookie domain rewrite logic for rewriteSetCookies below
432
+ exports.parseHost = parseHost;
433
+ const rewriteDomain = (domain, appHostname, targetHost) => {
434
+ // Strip any leading dots off the domain and split into elements
435
+ const domainElements = domain.split('.').filter(x => x);
436
+ const domainString = domainElements.join('.');
437
+
438
+ // Does the appHostname include a port number? We need a version
439
+ // of it without the port (hostname) because set-cookie domains cannot
440
+ // include ports. We can't just test for ':' because the host might be an
441
+ // ipv6 address. An ipv6 address containing a port contains the
442
+ // actual IP surrounded by [] (e.g. [2001:db8::1]:8080)
443
+ // RFC3986
444
+ const parsedHost = parseHost(appHostname);
445
+
446
+ // If the target host equals or ends with the domainString
447
+ // value, then we change the domain to be the appHostname
448
+ // (though for localhost, we strip off the port number)
449
+ if (targetHost === domainString) {
450
+ // Straight replacement
451
+ return parsedHost.hostname;
452
+ }
453
+ if (!targetHost.endsWith(domainString)) {
454
+ // Third-party cookie... leave unchanged
455
+ return domain;
456
+ }
457
+
458
+ // Cookie is set for a subdomain.
459
+ if (parsedHost.isIPOrLocalhost) {
460
+ // No subdomains for IP addresses or localhost, so return just that domain
461
+ return parsedHost.hostname;
462
+ }
463
+
464
+ // This is tricky... there's no standard way to get the domain for
465
+ // a hostname. We use a shortcut - we build up a subdomain based on the
466
+ // appHost that has the same number of elements as the cookie domain.
467
+ const targetHostElements = targetHost.split('.');
468
+ // Work out how many elements have been removed to form the subdomain
469
+ const strippedOff = targetHostElements.length - domainElements.length;
470
+ // Strip the same number of elements off the appHost
471
+ const appHostnameElements = parsedHost.hostname.split('.');
472
+ return appHostnameElements.slice(strippedOff).join('.');
473
+ };
474
+
475
+ /**
476
+ * Given a headers object, rewrite any set-cookie headers in it
477
+ * so that they apply to the app hostname rather than the target
478
+ * hostname.
479
+ *
480
+ * @private
481
+ * @param appHostname {String} the hostname (host+port) under which the
482
+ * Express app is running (e.g. localhost:3443 for a local dev server)
483
+ * @param targetHost {String} the target hostname (host+port)
484
+ * @param logging {Boolean} true to log operations
485
+ * @param setCookies {string[]} Array of set-cookie header values
486
+ * @returns string[] of rewritten set-cookie header values
487
+ */
488
+ exports.rewriteDomain = rewriteDomain;
489
+ const rewriteSetCookies = ({
490
+ appHostname,
491
+ setCookies,
492
+ targetHost,
493
+ logging
494
+ }) => {
495
+ if (!(setCookies && setCookies.length)) {
496
+ return [];
497
+ }
498
+
499
+ // Parse the set-cookie headers into a set of objects
500
+ const oldCookies = (0, _setCookieParser.parse)(setCookies, {
501
+ decodeValues: false
502
+ });
503
+
504
+ // Map the oldCookies array into an array of updated objects
505
+ const newCookies = oldCookies.map(cookie => {
506
+ if (cookie.domain) {
507
+ const newDomain = rewriteDomain(cookie.domain, appHostname, targetHost);
508
+
509
+ /* istanbul ignore next */
510
+ if (logging) {
511
+ _loggerInstance.default.info(`Rewriting proxy response set-cookie header domain from "${cookie.domain}" to "${newDomain}"`, {
512
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders.rewriteSetCookies'
513
+ });
514
+ }
515
+ cookie.domain = newDomain;
516
+ }
517
+ return cookie;
518
+ });
519
+
520
+ // Convert the cookies back to string values
521
+ return newCookies.map(cookieAsString);
522
+ };
523
+
524
+ /**
525
+ * Rewrite headers for a proxied response.
526
+ *
527
+ * 1. If the original domain appears in the
528
+ * Access-Control-Allow-Origin header, it's replaced with the
529
+ * appOrigin.
530
+ * 2. If the response is a 30x redirection and contains a Location
531
+ * header on the target host, that header is rewritten to use the
532
+ * app host and proxy path.
533
+ *
534
+ * For a caching proxy, we also remove any Set-Cookie headers - caching
535
+ * proxies don't pass Cookie headers for requests and don't allow Set-Cookie
536
+ * in responses, so that they may be cached independently of any cookie
537
+ * values.
538
+ *
539
+ * @private
540
+ * @param appHostname {String} the hostname (host+port) under which the
541
+ * Express app is running (e.g. localhost:3443 for a local dev server)
542
+ * @param caching {Boolean} true for a caching proxy, false for a standard proxy
543
+ * @param proxyPath {String} the path being proxied (e.g. /mobify/proxy/base/)
544
+ * @param targetProtocol {String} the protocol to use to make requests to
545
+ * the target ('http' or 'https')
546
+ * @param requestUrl {String} the URL from the request that prompted the
547
+ * response. If present, used to set the X-Proxy-Request-Url header. This should
548
+ * be the request URL sent to the target host, not containing any
549
+ * /mobify/proxy/... part.
550
+ * @param targetHost {String} the target hostname (host+port)
551
+ * @param appProtocol {String} the protocol to use to make requests to
552
+ * the origin ('http' or 'https', defaults to 'https'), use of unencrypted
553
+ * protocol is only allowed in local development
554
+ * @param logging {Boolean} true to log operations
555
+ * @param headers {Object} the headers to be rewritten
556
+ * @param headerFormat {String} 'aws' or 'http' - the format of the 'headers'
557
+ * parameter
558
+ * @param statusCode {Number} the response status code
559
+ * @returns {Object} - the modified response headers
560
+ */
561
+ exports.rewriteSetCookies = rewriteSetCookies;
562
+ const rewriteProxyResponseHeaders = ({
563
+ appHostname,
564
+ caching,
565
+ headers,
566
+ headerFormat = 'http',
567
+ proxyPath,
568
+ requestUrl,
569
+ statusCode = 200,
570
+ targetProtocol,
571
+ targetHost,
572
+ appProtocol = 'https',
573
+ logging = false
574
+ }) => {
575
+ const workingHeaders = new Headers(headers ? _objectSpread({}, headers) : {}, headerFormat);
576
+ const appOrigin = `${appProtocol}://${appHostname}`;
577
+ const targetOrigin = `${targetProtocol}://${targetHost}`;
578
+
579
+ // Set the X-Proxy-Request-Url header, if we have the request URL
580
+ if (requestUrl) {
581
+ // If the requestUrl is just a path, prepend the targetOrigin.
582
+ // Including the full URL as a header value risks exceeding limits
583
+ // on header value sizes. CloudFront limits URLs to 8192 bytes.
584
+ // Even though API Gateway has a header value limit of
585
+ // 10240 bytes, we choose to limit the length of the header
586
+ // value to 8192 bytes.
587
+ const fullRequestUrl = (requestUrl.startsWith('/') ? `${targetOrigin}${requestUrl}` : requestUrl).slice(0, MAX_URL_LENGTH_BYTES);
588
+ logging && _loggerInstance.default.info(`Setting proxy response ${X_PROXY_REQUEST_URL} header to "${fullRequestUrl}"`, {
589
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
590
+ additionalProperties: {
591
+ fullRequestUrl
592
+ }
593
+ });
594
+ workingHeaders.setHeader(X_PROXY_REQUEST_URL, fullRequestUrl);
595
+ }
596
+
597
+ // Get a version of the proxyPath that does not end in a slash
598
+ /* istanbul ignore next */
599
+ const proxyPathBase = proxyPath.endsWith('/') ? proxyPath.slice(0, -1) : proxyPath;
600
+ const allowOrigin = workingHeaders.getHeader(AC_ALLOW_ORIGIN);
601
+ logging && allowOrigin && _loggerInstance.default.info(`Header ${AC_ALLOW_ORIGIN} has value "${allowOrigin}"`, {
602
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
603
+ additionalProperties: {
604
+ allowOrigin,
605
+ AC_ALLOW_ORIGIN
606
+ }
607
+ });
608
+ if (allowOrigin === targetOrigin) {
609
+ /* istanbul ignore next */
610
+ if (logging) {
611
+ _loggerInstance.default.info(`Rewriting proxy response ${AC_ALLOW_ORIGIN} header to "${appOrigin}"`, {
612
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
613
+ additionalProperties: {
614
+ appOrigin,
615
+ AC_ALLOW_ORIGIN
616
+ }
617
+ });
618
+ }
619
+ workingHeaders.setHeader(AC_ALLOW_ORIGIN, appOrigin);
620
+ }
621
+ if (caching) {
622
+ // For a caching proxy, remove any Set-Cookie headers
623
+ workingHeaders.deleteHeader(SET_COOKIE);
624
+ } else {
625
+ // For a standard proxy, rewrite domains in any set-cookie headers.
626
+ const updatedCookies = rewriteSetCookies({
627
+ appHostname,
628
+ setCookies: workingHeaders.getSetCookie(),
629
+ targetHost,
630
+ logging
631
+ });
632
+ workingHeaders.setSetCookie(updatedCookies);
633
+ }
634
+
635
+ // Handle any redirect
636
+ if (statusCode >= 301 && statusCode <= 308) {
637
+ logging && _loggerInstance.default.info(`Status code is ${statusCode}, checking Location header`, {
638
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
639
+ additionalProperties: {
640
+ statusCode
641
+ }
642
+ });
643
+ const location = workingHeaders.getHeader(LOCATION);
644
+ logging && _loggerInstance.default.info(`Location header has value "${location}"`, {
645
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
646
+ additionalProperties: {
647
+ location
648
+ }
649
+ });
650
+
651
+ /* istanbul ignore else */
652
+ if (location) {
653
+ // The Location header is defined as a URL, meaning that it
654
+ // can be both protocol- and host-relative, so we expand it
655
+ // relative to the targetOrigin.
656
+ const locUrl = new _url.URL(location, targetOrigin);
657
+
658
+ // If the location header URL is on the targetOrigin, we rewrite it.
659
+ if (locUrl.protocol === `${targetProtocol}:` && locUrl.host === targetHost) {
660
+ // Rewrite the Location value to map to the proxy path
661
+ // on the app host.
662
+ locUrl.protocol = appProtocol;
663
+ locUrl.host = appHostname;
664
+ // Since the proxyPath ends with a slash and locUrl.pathname
665
+ // will start with a slash, we need to
666
+ locUrl.pathname = proxyPathBase + locUrl.pathname;
667
+ const newLocation = locUrl.toString();
668
+ workingHeaders.setHeader(LOCATION, newLocation);
669
+ /* istanbul ignore else */
670
+ if (logging) {
671
+ _loggerInstance.default.info(`Rewriting proxy response Location header from "${location}" to "${newLocation}"`, {
672
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
673
+ additionalProperties: {
674
+ location,
675
+ newLocation
676
+ }
677
+ });
678
+ }
679
+ }
680
+ }
681
+ }
682
+ return workingHeaders.toObject();
683
+ };
684
+
685
+ /**
686
+ * List of x- headers that are removed from proxied requests.
687
+ * @private
688
+ * @type {string[]}
689
+ */
690
+ exports.rewriteProxyResponseHeaders = rewriteProxyResponseHeaders;
691
+ const X_HEADERS_TO_REMOVE_PROXY = exports.X_HEADERS_TO_REMOVE_PROXY = ['x-mobify-access-key', 'x-sfdc-access-control'];
692
+
693
+ /**
694
+ * List of x- headers that are removed from origin requests.
695
+ * @private
696
+ * @type {string[]}
697
+ */
698
+ const X_HEADERS_TO_REMOVE_ORIGIN = exports.X_HEADERS_TO_REMOVE_ORIGIN = ['x-api-key', 'x-apigateway-event', 'x-apigateway-context', 'x-mobify-access-key', 'x-sfdc-access-control'];
699
+
700
+ /**
701
+ * X-header key and values to add to proxied requests
702
+ * @private
703
+ * @type {Object}
704
+ */
705
+ const X_HEADERS_TO_ADD = exports.X_HEADERS_TO_ADD = {
706
+ 'x-mobify': 'true'
707
+ };
708
+
709
+ /**
710
+ * List of headers that are allowed for a caching proxy request.
711
+ * This must match the allowlist that CloudFront uses for a
712
+ * CacheBehavior that does not pass cookies and is not configured
713
+ * to cache based on headers.
714
+ *
715
+ * This is a map from lower-case header name to 'true' - we use an object
716
+ * to make lookups fast, since this mapping might be used for many requests.
717
+ *
718
+ * Also see what is configured in the SSR Manager (ssr-infrastructure repo),
719
+ * in the CloudFront configuration. This list is a superset of that list,
720
+ * since the proxying code must also allow headers that it adds, such as
721
+ * Host, Origin, etc.
722
+ *
723
+ * See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html
724
+ * See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html
725
+ *
726
+ * @private
727
+ */
728
+ const ALLOWED_CACHING_PROXY_REQUEST_HEADERS = exports.ALLOWED_CACHING_PROXY_REQUEST_HEADERS = {
729
+ // This is the set of headers allowed for CloudFront
730
+ accept: true,
731
+ 'accept-charset': true,
732
+ 'accept-encoding': true,
733
+ 'accept-language': true,
734
+ authorization: true,
735
+ range: true,
736
+ // These headers must be preserved in the request so that
737
+ // header processing works correctly.
738
+ host: true,
739
+ origin: true,
740
+ // Where CloudFront does the proxying, these headers are
741
+ // generated by CloudFront itself. Where the Express app
742
+ // does it, we forward them.
743
+ 'if-match': true,
744
+ 'if-modified-since': true,
745
+ 'if-none-match': true,
746
+ 'if-range': true,
747
+ 'if-unmodified-since': true
748
+ };
749
+
750
+ /**
751
+ * Rewrite headers for a request that is being proxied.
752
+ *
753
+ * 1. If the request contains a Host header, rewrite it so that the
754
+ * value is the target host.
755
+ * 2. If the request contains an Origin header, rewrite it so that the
756
+ * value is the target host.
757
+ * 3. ALL other header values are left unchanged. If they are multi-value
758
+ * headers whose values are stored as arrays, the values are left as arrays.
759
+ *
760
+ * @private
761
+ * @param caching {Boolean} true for a caching proxy, false for a standard proxy
762
+ * @param headers {Object} the headers to be rewritten
763
+ * @param headerFormat {String} 'aws' or 'http' - the format of the 'headers'
764
+ * parameter
765
+ * @param targetProtocol {String} the protocol to use to make requests to
766
+ * the target ('http' or 'https')
767
+ * @param targetHost {String} the target hostname (host+port)
768
+ * @param logging {Boolean} true to log operations
769
+ * @returns {Object} - the modified request headers
770
+ */
771
+ const rewriteProxyRequestHeaders = ({
772
+ caching = false,
773
+ headers,
774
+ headerFormat = 'http',
775
+ targetProtocol,
776
+ targetHost,
777
+ logging = false
778
+ }) => {
779
+ if (!headers) {
780
+ return {};
781
+ }
782
+ const workingHeaders = new Headers(_objectSpread({}, headers), headerFormat);
783
+
784
+ // Strip out some specific X-headers
785
+ X_HEADERS_TO_REMOVE_PROXY.forEach(key => workingHeaders.deleteHeader(key));
786
+
787
+ // For a caching proxy, apply special header processing
788
+ if (caching) {
789
+ // Remove any headers that are not on the allowlist
790
+ workingHeaders.keys().forEach(key => {
791
+ if (!ALLOWED_CACHING_PROXY_REQUEST_HEADERS[key]) {
792
+ workingHeaders.deleteHeader(key);
793
+ }
794
+ });
795
+
796
+ // Override user-agent - mimic the behaviour of CloudFront
797
+ workingHeaders.setHeader(USER_AGENT, 'Amazon CloudFront');
798
+ }
799
+
800
+ // Fix up any Host header. We ignore any current value and
801
+ // always replace it with the target host.
802
+ // Host: <host>:<port>
803
+ const hostHeader = workingHeaders.getHeader(HOST);
804
+ if (hostHeader !== targetHost) {
805
+ /* istanbul ignore else */
806
+ if (logging) {
807
+ _loggerInstance.default.info(`Rewriting proxy request Host header from "${hostHeader}" to "${targetHost}"`, {
808
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
809
+ additionalProperties: {
810
+ hostHeader,
811
+ targetHost
812
+ }
813
+ });
814
+ }
815
+ workingHeaders.setHeader(HOST, targetHost);
816
+ }
817
+
818
+ // Fix up any Origin header. We ignore any current value and
819
+ // always replace it with the targetOrigin
820
+ // Origin: <scheme> "://" <hostname> [ ":" <port> ]
821
+ const originHeader = workingHeaders.getHeader(ORIGIN);
822
+ const targetOrigin = `${targetProtocol}://${targetHost}`;
823
+ if (originHeader && originHeader !== targetOrigin) {
824
+ /* istanbul ignore else */
825
+ if (logging) {
826
+ _loggerInstance.default.info(`Rewriting proxy request Origin header from "${originHeader}" to "${targetOrigin}"`, {
827
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
828
+ additionalProperties: {
829
+ originHeader,
830
+ targetOrigin
831
+ }
832
+ });
833
+ }
834
+ workingHeaders.setHeader(ORIGIN, targetOrigin);
835
+ }
836
+
837
+ // Replace some headers with hardwired values
838
+ if (workingHeaders.getHeader(USER_AGENT)) {
839
+ // Mimic the behaviour of CloudFront
840
+ workingHeaders.setHeader(USER_AGENT, 'Amazon CloudFront');
841
+ }
842
+
843
+ // Add some specific X-headers
844
+ Object.entries(X_HEADERS_TO_ADD).forEach(([key, value]) => {
845
+ /* istanbul ignore else */
846
+ if (logging) {
847
+ _loggerInstance.default.info(`Adding a proxy request ${key} header with value "${value}"`), {
848
+ namespace: 'ssr-proxying.rewriteProxyResponseHeaders',
849
+ additionalProperties: {
850
+ key,
851
+ value
852
+ }
853
+ };
854
+ }
855
+ workingHeaders.setHeader(key, value);
856
+ });
857
+ return workingHeaders.toObject();
858
+ };
859
+ exports.rewriteProxyRequestHeaders = rewriteProxyRequestHeaders;