@commercetools-frontend/mc-dev-authentication 0.0.0-FEC-157-preview-releases-20241126230331

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) commercetools GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @commercetools-frontend/mc-dev-authentication
2
+
3
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/@commercetools-frontend/mc-dev-authentication"><img src="https://badgen.net/npm/v/@commercetools-frontend/mc-dev-authentication" alt="Latest release (latest dist-tag)" /></a> <a href="https://www.npmjs.com/package/@commercetools-frontend/mc-dev-authentication"><img src="https://badgen.net/npm/v/@commercetools-frontend/mc-dev-authentication/next" alt="Latest release (next dist-tag)" /></a> <a href="https://bundlephobia.com/result?p=@commercetools-frontend/mc-dev-authentication"><img src="https://badgen.net/bundlephobia/minzip/@commercetools-frontend/mc-dev-authentication" alt="Minified + GZipped size" /></a> <a href="https://github.com/commercetools/merchant-center-application-kit/blob/main/LICENSE"><img src="https://badgen.net/github/license/commercetools/merchant-center-application-kit" alt="GitHub license" /></a>
5
+ </p>
6
+
7
+ Authentication views when running webpack-dev-server in development mode.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ $ npm install --save @commercetools-frontend/mc-dev-authentication
13
+ ```
@@ -0,0 +1,2 @@
1
+ export * from "./declarations/src/index";
2
+ //# sourceMappingURL=commercetools-frontend-mc-dev-authentication.cjs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commercetools-frontend-mc-dev-authentication.cjs.d.ts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
6
+ var _concatInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/concat');
7
+ var fs = require('fs');
8
+ var path = require('path');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
+
12
+ var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
13
+ var _concatInstanceProperty__default = /*#__PURE__*/_interopDefault(_concatInstanceProperty);
14
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
15
+ var path__default = /*#__PURE__*/_interopDefault(path);
16
+
17
+ function logoutRoute(response) {
18
+ var _context;
19
+ let additionalCookieParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
20
+ // NOTE: removing the cookie only works if your are running the MC API
21
+ // locally, otherwise the cookie won't get removed as it's set to a
22
+ // proper domain (e.g. commercetools.com), which we can't unset from localhost.
23
+ response.setHeader('Set-Cookie', _concatInstanceProperty__default["default"](_context = [`mcAccessToken=''`,
24
+ // <-- unset the value
25
+ 'Path=/', `Expires=${new Date(0).toUTCString()}`,
26
+ // <-- put a date in the past
27
+ 'HttpOnly']).call(_context, additionalCookieParameters).join('; '));
28
+ }
29
+
30
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
31
+ const pages$1 = {
32
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
33
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
34
+ };
35
+ const trimTrailingSlash$1 = value => value.replace(/\/$/, '');
36
+ function createMcDevAuthenticationMiddleware(applicationConfig) {
37
+ const htmlLogin = pages$1.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash$1(applicationConfig.env.mcApiUrl));
38
+ const htmlLogout = pages$1.logoutPage;
39
+ const isDevAuthenticationMiddlewareDisabled = String(applicationConfig.env.disableAuthRoutesOfDevServer) === 'true' || applicationConfig.env.servedByProxy;
40
+ return (request, response, next) => {
41
+ if (request.originalUrl === '/api/graphql') {
42
+ response.statusCode = 404;
43
+ response.setHeader('Content-Type', 'application/json');
44
+ response.end(_JSON$stringify__default["default"]({
45
+ message: `This GraphQL endpoint is only available in production in the [Merchant Center Proxy Router](https://docs.commercetools.com/merchant-center-customizations/concepts/merchant-center-proxy-router). Please check that you are not calling this endpoint in development mode.`
46
+ }));
47
+ return;
48
+ }
49
+ if (applicationConfig.env.__DEVELOPMENT__?.oidc?.authorizeUrl) {
50
+ // Handle login page for OIDC workflow when developing against a local MC API.
51
+ if (applicationConfig.env.__DEVELOPMENT__?.oidc?.authorizeUrl.startsWith('http://localhost')) {
52
+ if (request.originalUrl?.startsWith('/login/authorize')) {
53
+ if (isDevAuthenticationMiddlewareDisabled) {
54
+ next();
55
+ } else {
56
+ response.end(htmlLogin);
57
+ }
58
+ return;
59
+ }
60
+ }
61
+ } else {
62
+ if (request.originalUrl === '/login') {
63
+ if (isDevAuthenticationMiddlewareDisabled) {
64
+ next();
65
+ } else {
66
+ response.end(htmlLogin);
67
+ }
68
+ return;
69
+ }
70
+ if (request.originalUrl === '/logout') {
71
+ logoutRoute(response);
72
+ if (isDevAuthenticationMiddlewareDisabled) {
73
+ next();
74
+ } else {
75
+ response.end(htmlLogout);
76
+ }
77
+ return;
78
+ }
79
+ }
80
+ next();
81
+ };
82
+ }
83
+
84
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
85
+ const pages = {
86
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
87
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
88
+ };
89
+ const trimTrailingSlash = value => value.replace(/\/$/, '');
90
+
91
+ // Make sure any symlinks in the project folder are resolved:
92
+ // https://github.com/facebook/create-react-app/issues/637
93
+ const appDirectory = fs__default["default"].realpathSync(process.cwd());
94
+ const resolveApp = relativePath => path__default["default"].resolve(appDirectory, relativePath);
95
+ const paths = {
96
+ appBuild: resolveApp('public')
97
+ };
98
+
99
+ // This transformer will generate a development `login` and `logout` HTML files
100
+ // and copy them to the application public folder.
101
+ // This is necessary to run the application locally in production mode.
102
+ const transformerLocal = compiledHtml => {
103
+ const htmlLogin = pages.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash(compiledHtml.env.mcApiUrl));
104
+ const htmlLogout = pages.logoutPage;
105
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'login.html'), htmlLogin, 'utf8');
106
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'logout.html'), htmlLogout, 'utf8');
107
+ };
108
+
109
+ exports.createMcDevAuthenticationMiddleware = createMcDevAuthenticationMiddleware;
110
+ exports.transformerLocal = transformerLocal;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./commercetools-frontend-mc-dev-authentication.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./commercetools-frontend-mc-dev-authentication.cjs.dev.js");
7
+ }
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
6
+ var _concatInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/concat');
7
+ var fs = require('fs');
8
+ var path = require('path');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
+
12
+ var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
13
+ var _concatInstanceProperty__default = /*#__PURE__*/_interopDefault(_concatInstanceProperty);
14
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
15
+ var path__default = /*#__PURE__*/_interopDefault(path);
16
+
17
+ function logoutRoute(response) {
18
+ var _context;
19
+ let additionalCookieParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
20
+ // NOTE: removing the cookie only works if your are running the MC API
21
+ // locally, otherwise the cookie won't get removed as it's set to a
22
+ // proper domain (e.g. commercetools.com), which we can't unset from localhost.
23
+ response.setHeader('Set-Cookie', _concatInstanceProperty__default["default"](_context = [`mcAccessToken=''`,
24
+ // <-- unset the value
25
+ 'Path=/', `Expires=${new Date(0).toUTCString()}`,
26
+ // <-- put a date in the past
27
+ 'HttpOnly']).call(_context, additionalCookieParameters).join('; '));
28
+ }
29
+
30
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
31
+ const pages$1 = {
32
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
33
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
34
+ };
35
+ const trimTrailingSlash$1 = value => value.replace(/\/$/, '');
36
+ function createMcDevAuthenticationMiddleware(applicationConfig) {
37
+ const htmlLogin = pages$1.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash$1(applicationConfig.env.mcApiUrl));
38
+ const htmlLogout = pages$1.logoutPage;
39
+ const isDevAuthenticationMiddlewareDisabled = String(applicationConfig.env.disableAuthRoutesOfDevServer) === 'true' || applicationConfig.env.servedByProxy;
40
+ return (request, response, next) => {
41
+ if (request.originalUrl === '/api/graphql') {
42
+ response.statusCode = 404;
43
+ response.setHeader('Content-Type', 'application/json');
44
+ response.end(_JSON$stringify__default["default"]({
45
+ message: `This GraphQL endpoint is only available in production in the [Merchant Center Proxy Router](https://docs.commercetools.com/merchant-center-customizations/concepts/merchant-center-proxy-router). Please check that you are not calling this endpoint in development mode.`
46
+ }));
47
+ return;
48
+ }
49
+ if (applicationConfig.env.__DEVELOPMENT__?.oidc?.authorizeUrl) {
50
+ // Handle login page for OIDC workflow when developing against a local MC API.
51
+ if (applicationConfig.env.__DEVELOPMENT__?.oidc?.authorizeUrl.startsWith('http://localhost')) {
52
+ if (request.originalUrl?.startsWith('/login/authorize')) {
53
+ if (isDevAuthenticationMiddlewareDisabled) {
54
+ next();
55
+ } else {
56
+ response.end(htmlLogin);
57
+ }
58
+ return;
59
+ }
60
+ }
61
+ } else {
62
+ if (request.originalUrl === '/login') {
63
+ if (isDevAuthenticationMiddlewareDisabled) {
64
+ next();
65
+ } else {
66
+ response.end(htmlLogin);
67
+ }
68
+ return;
69
+ }
70
+ if (request.originalUrl === '/logout') {
71
+ logoutRoute(response);
72
+ if (isDevAuthenticationMiddlewareDisabled) {
73
+ next();
74
+ } else {
75
+ response.end(htmlLogout);
76
+ }
77
+ return;
78
+ }
79
+ }
80
+ next();
81
+ };
82
+ }
83
+
84
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
85
+ const pages = {
86
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
87
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
88
+ };
89
+ const trimTrailingSlash = value => value.replace(/\/$/, '');
90
+
91
+ // Make sure any symlinks in the project folder are resolved:
92
+ // https://github.com/facebook/create-react-app/issues/637
93
+ const appDirectory = fs__default["default"].realpathSync(process.cwd());
94
+ const resolveApp = relativePath => path__default["default"].resolve(appDirectory, relativePath);
95
+ const paths = {
96
+ appBuild: resolveApp('public')
97
+ };
98
+
99
+ // This transformer will generate a development `login` and `logout` HTML files
100
+ // and copy them to the application public folder.
101
+ // This is necessary to run the application locally in production mode.
102
+ const transformerLocal = compiledHtml => {
103
+ const htmlLogin = pages.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash(compiledHtml.env.mcApiUrl));
104
+ const htmlLogout = pages.logoutPage;
105
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'login.html'), htmlLogin, 'utf8');
106
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'logout.html'), htmlLogout, 'utf8');
107
+ };
108
+
109
+ exports.createMcDevAuthenticationMiddleware = createMcDevAuthenticationMiddleware;
110
+ exports.transformerLocal = transformerLocal;
@@ -0,0 +1,98 @@
1
+ import _JSON$stringify from '@babel/runtime-corejs3/core-js-stable/json/stringify';
2
+ import _concatInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/concat';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+
6
+ function logoutRoute(response) {
7
+ var _context;
8
+ let additionalCookieParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
9
+ // NOTE: removing the cookie only works if your are running the MC API
10
+ // locally, otherwise the cookie won't get removed as it's set to a
11
+ // proper domain (e.g. commercetools.com), which we can't unset from localhost.
12
+ response.setHeader('Set-Cookie', _concatInstanceProperty(_context = [`mcAccessToken=''`,
13
+ // <-- unset the value
14
+ 'Path=/', `Expires=${new Date(0).toUTCString()}`,
15
+ // <-- put a date in the past
16
+ 'HttpOnly']).call(_context, additionalCookieParameters).join('; '));
17
+ }
18
+
19
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
20
+ const pages$1 = {
21
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
22
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
23
+ };
24
+ const trimTrailingSlash$1 = value => value.replace(/\/$/, '');
25
+ function createMcDevAuthenticationMiddleware(applicationConfig) {
26
+ const htmlLogin = pages$1.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash$1(applicationConfig.env.mcApiUrl));
27
+ const htmlLogout = pages$1.logoutPage;
28
+ const isDevAuthenticationMiddlewareDisabled = String(applicationConfig.env.disableAuthRoutesOfDevServer) === 'true' || applicationConfig.env.servedByProxy;
29
+ return (request, response, next) => {
30
+ if (request.originalUrl === '/api/graphql') {
31
+ response.statusCode = 404;
32
+ response.setHeader('Content-Type', 'application/json');
33
+ response.end(_JSON$stringify({
34
+ message: `This GraphQL endpoint is only available in production in the [Merchant Center Proxy Router](https://docs.commercetools.com/merchant-center-customizations/concepts/merchant-center-proxy-router). Please check that you are not calling this endpoint in development mode.`
35
+ }));
36
+ return;
37
+ }
38
+ if (applicationConfig.env.__DEVELOPMENT__?.oidc?.authorizeUrl) {
39
+ // Handle login page for OIDC workflow when developing against a local MC API.
40
+ if (applicationConfig.env.__DEVELOPMENT__?.oidc?.authorizeUrl.startsWith('http://localhost')) {
41
+ if (request.originalUrl?.startsWith('/login/authorize')) {
42
+ if (isDevAuthenticationMiddlewareDisabled) {
43
+ next();
44
+ } else {
45
+ response.end(htmlLogin);
46
+ }
47
+ return;
48
+ }
49
+ }
50
+ } else {
51
+ if (request.originalUrl === '/login') {
52
+ if (isDevAuthenticationMiddlewareDisabled) {
53
+ next();
54
+ } else {
55
+ response.end(htmlLogin);
56
+ }
57
+ return;
58
+ }
59
+ if (request.originalUrl === '/logout') {
60
+ logoutRoute(response);
61
+ if (isDevAuthenticationMiddlewareDisabled) {
62
+ next();
63
+ } else {
64
+ response.end(htmlLogout);
65
+ }
66
+ return;
67
+ }
68
+ }
69
+ next();
70
+ };
71
+ }
72
+
73
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
74
+ const pages = {
75
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
76
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
77
+ };
78
+ const trimTrailingSlash = value => value.replace(/\/$/, '');
79
+
80
+ // Make sure any symlinks in the project folder are resolved:
81
+ // https://github.com/facebook/create-react-app/issues/637
82
+ const appDirectory = fs.realpathSync(process.cwd());
83
+ const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
84
+ const paths = {
85
+ appBuild: resolveApp('public')
86
+ };
87
+
88
+ // This transformer will generate a development `login` and `logout` HTML files
89
+ // and copy them to the application public folder.
90
+ // This is necessary to run the application locally in production mode.
91
+ const transformerLocal = compiledHtml => {
92
+ const htmlLogin = pages.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash(compiledHtml.env.mcApiUrl));
93
+ const htmlLogout = pages.logoutPage;
94
+ fs.writeFileSync(path.join(paths.appBuild, 'login.html'), htmlLogin, 'utf8');
95
+ fs.writeFileSync(path.join(paths.appBuild, 'logout.html'), htmlLogout, 'utf8');
96
+ };
97
+
98
+ export { createMcDevAuthenticationMiddleware, transformerLocal };
@@ -0,0 +1,5 @@
1
+ import type { ServerResponse } from 'node:http';
2
+ import type { IncomingMessage, NextFunction } from 'connect';
3
+ import type { TCustomApplicationRuntimeConfig } from './types';
4
+ declare function createMcDevAuthenticationMiddleware(applicationConfig: TCustomApplicationRuntimeConfig): (request: IncomingMessage, response: ServerResponse, next: NextFunction) => void;
5
+ export default createMcDevAuthenticationMiddleware;
@@ -0,0 +1,2 @@
1
+ export { default as createMcDevAuthenticationMiddleware } from './create-mc-dev-authentication-middleware';
2
+ export { default as transformerLocal } from './transformer-local';
@@ -0,0 +1,3 @@
1
+ declare type Pages = { loginPage: string; logoutPage: string };
2
+ declare const pages: Pages;
3
+ export default pages;
@@ -0,0 +1 @@
1
+ export { default as logout } from './logout';
@@ -0,0 +1,4 @@
1
+ /// <reference types="node" />
2
+ import type { ServerResponse } from 'node:http';
3
+ declare function logoutRoute(response: ServerResponse, additionalCookieParameters?: string[]): void;
4
+ export default logoutRoute;
@@ -0,0 +1,3 @@
1
+ import type { TCompiledHtml } from './types';
2
+ declare const transformerLocal: (compiledHtml: TCompiledHtml) => void;
3
+ export default transformerLocal;
@@ -0,0 +1,9 @@
1
+ import type { ApplicationRuntimeConfig } from '@commercetools-frontend/application-config';
2
+ export type TCustomApplicationRuntimeConfig = ApplicationRuntimeConfig<{
3
+ disableAuthRoutesOfDevServer?: boolean;
4
+ }>;
5
+ export type TCompiledHtml = {
6
+ env: TCustomApplicationRuntimeConfig['env'];
7
+ headers: Record<string, string>;
8
+ indexHtmlContent: string;
9
+ };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@commercetools-frontend/mc-dev-authentication",
3
+ "version": "0.0.0-FEC-157-preview-releases-20241126230331",
4
+ "description": "Authentication views when running webpack-dev-server in development mode",
5
+ "bugs": "https://github.com/commercetools/merchant-center-application-kit/issues",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/commercetools/merchant-center-application-kit.git",
9
+ "directory": "packages/mc-dev-authentication"
10
+ },
11
+ "homepage": "https://docs.commercetools.com/merchant-center-customizations",
12
+ "keywords": [
13
+ "javascript",
14
+ "frontend",
15
+ "react",
16
+ "toolkit"
17
+ ],
18
+ "license": "MIT",
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "main": "dist/commercetools-frontend-mc-dev-authentication.cjs.js",
23
+ "module": "dist/commercetools-frontend-mc-dev-authentication.esm.js",
24
+ "files": [
25
+ "dist",
26
+ "transformer-local.js",
27
+ "package.json",
28
+ "LICENSE",
29
+ "README.md"
30
+ ],
31
+ "dependencies": {
32
+ "@babel/runtime": "^7.22.15",
33
+ "@babel/runtime-corejs3": "^7.22.15"
34
+ },
35
+ "devDependencies": {
36
+ "@tsconfig/node16": "^16.1.1",
37
+ "@types/connect": "^3.4.36",
38
+ "connect": "^3.7.0",
39
+ "@commercetools-frontend/application-config": "0.0.0-FEC-157-preview-releases-20241126230331"
40
+ },
41
+ "engines": {
42
+ "node": "16.x || >=18.0.0"
43
+ }
44
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * This file is expected to be included in the package as it's referenced for the `--transformer` option
3
+ * in the `compile-html` command.
4
+ *
5
+ * @example
6
+ * ```
7
+ * mc-scripts compile-html --transformer @commercetools-frontend/mc-dev-authentication/transformer-local.js
8
+ * ```
9
+ */
10
+
11
+ const { transformerLocal } = require('.');
12
+ module.exports = transformerLocal;