@frontegg/nextjs 7.0.16 → 7.0.17-alpha.5712339467

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # Change Log
2
+
3
+ ## [7.0.17](https://github.com/frontegg/frontegg-nextjs/compare/v7.0.16...v7.0.17) (2023-7-31)
4
+
5
+ - FR-12701 - revert change settings list
6
+ - FR-12696 - Entitlements load on demand fix
7
+ - FR-12701 - implememt sessions inner page
8
+
9
+
10
+ ### NextJS Wrapper 7.0.17:
11
+ - FR-12634 - support-custom-login-sub-domain-out-of-the-box
12
+ - Update Frontegg AdminPortal to 6.126.0
1
13
  # Change Log
2
14
 
3
15
  ## [7.0.16](https://github.com/frontegg/frontegg-nextjs/compare/v7.0.15...v7.0.16) (2023-7-19)
package/api/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ILoginResponse, GetCurrentUserTenantsResponse } from '@frontegg/rest-api';
1
+ import { ILoginResponse, GetCurrentUserTenantsResponse, IPublicSettingsResponse } from '@frontegg/rest-api';
2
2
  /**
3
3
  *
4
4
  * @param headers
@@ -9,11 +9,13 @@ export declare const getUsers: (headers: Record<string, string>) => Promise<ILog
9
9
  * @param headers
10
10
  */
11
11
  export declare const getTenants: (headers: Record<string, string>) => Promise<GetCurrentUserTenantsResponse | undefined>;
12
+ export declare const getPublicSettings: (headers: Record<string, string>) => Promise<IPublicSettingsResponse | undefined>;
12
13
  declare const _default: {
13
14
  loadPublicKey: () => Promise<any>;
14
15
  refreshTokenEmbedded: (headers: Record<string, string>) => Promise<Response>;
15
16
  refreshTokenHostedLogin: (headers: Record<string, string>, refresh_token: string) => Promise<Response>;
16
17
  getUsers: (headers: Record<string, string>) => Promise<ILoginResponse | undefined>;
17
18
  getTenants: (headers: Record<string, string>) => Promise<GetCurrentUserTenantsResponse | undefined>;
19
+ getPublicSettings: (headers: Record<string, string>) => Promise<IPublicSettingsResponse | undefined>;
18
20
  };
19
21
  export default _default;
package/api/index.js CHANGED
@@ -4,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.getUsers = exports.getTenants = exports.default = void 0;
7
+ exports.getUsers = exports.getTenants = exports.getPublicSettings = exports.default = void 0;
8
8
  var _config = _interopRequireDefault(require("../config"));
9
9
  var _urls = require("./urls");
10
10
  var _utils = require("./utils");
@@ -74,12 +74,22 @@ const getTenants = async headers => {
74
74
  return (0, _utils.parseHttpResponse)(res);
75
75
  };
76
76
  exports.getTenants = getTenants;
77
+ const getPublicSettings = async headers => {
78
+ const res = await (0, _utils.Get)({
79
+ //TODO: export the route url from rest-api and import from there
80
+ url: `${_config.default.baseUrl}/frontegg/tenants/resources/account-settings/v1/public`,
81
+ headers: (0, _utils.buildRequestHeaders)(headers)
82
+ });
83
+ return (0, _utils.parseHttpResponse)(res);
84
+ };
85
+ exports.getPublicSettings = getPublicSettings;
77
86
  var _default = {
78
87
  loadPublicKey,
79
88
  refreshTokenEmbedded,
80
89
  refreshTokenHostedLogin,
81
90
  getUsers,
82
- getTenants
91
+ getTenants,
92
+ getPublicSettings
83
93
  };
84
94
  exports.default = _default;
85
95
  //# sourceMappingURL=index.js.map
package/api/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_config","_interopRequireDefault","require","_urls","_utils","_restApi","loadPublicKey","response","fetch","config","baseUrl","ApiUrls","WellKnown","jwks","cache","data","json","keys","refreshTokenEmbedded","headers","Post","url","refreshToken","embedded","body","credentials","buildRequestHeaders","refreshTokenHostedLogin","refresh_token","hosted","JSON","stringify","grant_type","getUsers","headersToSend","res","Get","fronteggUsersUrl","parseHttpResponse","exports","getTenants","fronteggTenantsV3Url","_default","default"],"sources":["../../../../packages/nextjs/src/api/index.ts"],"sourcesContent":["import config from '../config';\nimport { ApiUrls } from './urls';\nimport { buildRequestHeaders, Get, parseHttpResponse, Post } from './utils';\nimport {\n fronteggTenantsV3Url,\n fronteggUsersUrl,\n ILoginResponse,\n GetCurrentUserTenantsResponse,\n} from '@frontegg/rest-api';\n\n/**\n * Send HTTP GET to frontegg domain public route to download the JWT public key\n */\nconst loadPublicKey = async () => {\n const response = await fetch(`${config.baseUrl}${ApiUrls.WellKnown.jwks}`, {\n cache: 'force-cache',\n });\n const data = await response.json();\n return data.keys[0];\n};\n\n/**\n * Send HTTP post request for Frontegg services to refresh token\n * by providing client's fe_ cookies\n */\nconst refreshTokenEmbedded = async (headers: Record<string, string>) => {\n return Post({\n url: `${config.baseUrl}${ApiUrls.refreshToken.embedded}`,\n body: '{}',\n credentials: 'include',\n headers: buildRequestHeaders(headers),\n });\n};\n\n/**\n * Send HTTP post request for Frontegg services to refresh `hosted login` token\n * by providing client's fe_ as body with grant_type.\n */\nconst refreshTokenHostedLogin = async (headers: Record<string, string>, refresh_token: string) => {\n return Post({\n url: `${config.baseUrl}${ApiUrls.refreshToken.hosted}`,\n body: JSON.stringify({\n grant_type: 'refresh_token',\n refresh_token,\n }),\n headers: buildRequestHeaders(headers),\n });\n};\n\n/**\n *\n * @param headers\n */\nexport const getUsers = async (headers: Record<string, string>): Promise<ILoginResponse | undefined> => {\n const headersToSend = buildRequestHeaders(headers);\n const res = await Get({\n url: `${config.baseUrl}/frontegg${fronteggUsersUrl}`,\n headers: headersToSend,\n });\n return parseHttpResponse(res);\n};\n\n/**\n *\n * @param headers\n */\nexport const getTenants = async (\n headers: Record<string, string>\n): Promise<GetCurrentUserTenantsResponse | undefined> => {\n const res = await Get({\n url: `${config.baseUrl}/frontegg${fronteggTenantsV3Url}`,\n headers: buildRequestHeaders(headers),\n });\n return parseHttpResponse(res);\n};\n\nexport default {\n loadPublicKey,\n refreshTokenEmbedded,\n refreshTokenHostedLogin,\n getUsers,\n getTenants,\n};\n"],"mappings":";;;;;;;AAAA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,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,OAAO,CAAC;EAClD,MAAMgB,GAAG,GAAG,MAAM,IAAAC,UAAG,EAAC;IACpBf,GAAG,EAAG,GAAEZ,eAAM,CAACC,OAAQ,YAAW2B,yBAAiB,EAAC;IACpDlB,OAAO,EAAEe;EACX,CAAC,CAAC;EACF,OAAO,IAAAI,wBAAiB,EAACH,GAAG,CAAC;AAC/B,CAAC;;AAED;AACA;AACA;AACA;AAHAI,OAAA,CAAAN,QAAA,GAAAA,QAAA;AAIO,MAAMO,UAAU,GAAG,MACxBrB,OAA+B,IACwB;EACvD,MAAMgB,GAAG,GAAG,MAAM,IAAAC,UAAG,EAAC;IACpBf,GAAG,EAAG,GAAEZ,eAAM,CAACC,OAAQ,YAAW+B,6BAAqB,EAAC;IACxDtB,OAAO,EAAE,IAAAO,0BAAmB,EAACP,OAAO;EACtC,CAAC,CAAC;EACF,OAAO,IAAAmB,wBAAiB,EAACH,GAAG,CAAC;AAC/B,CAAC;AAACI,OAAA,CAAAC,UAAA,GAAAA,UAAA;AAAA,IAAAE,QAAA,GAEa;EACbpC,aAAa;EACbY,oBAAoB;EACpBS,uBAAuB;EACvBM,QAAQ;EACRO;AACF,CAAC;AAAAD,OAAA,CAAAI,OAAA,GAAAD,QAAA"}
1
+ {"version":3,"file":"index.js","names":["_config","_interopRequireDefault","require","_urls","_utils","_restApi","loadPublicKey","response","fetch","config","baseUrl","ApiUrls","WellKnown","jwks","cache","data","json","keys","refreshTokenEmbedded","headers","Post","url","refreshToken","embedded","body","credentials","buildRequestHeaders","refreshTokenHostedLogin","refresh_token","hosted","JSON","stringify","grant_type","getUsers","headersToSend","res","Get","fronteggUsersUrl","parseHttpResponse","exports","getTenants","fronteggTenantsV3Url","getPublicSettings","_default","default"],"sources":["../../../../packages/nextjs/src/api/index.ts"],"sourcesContent":["import config from '../config';\nimport { ApiUrls } from './urls';\nimport { buildRequestHeaders, Get, parseHttpResponse, Post } from './utils';\nimport {\n fronteggTenantsV3Url,\n fronteggUsersUrl,\n ILoginResponse,\n GetCurrentUserTenantsResponse,\n IPublicSettingsResponse,\n} from '@frontegg/rest-api';\n\n/**\n * Send HTTP GET to frontegg domain public route to download the JWT public key\n */\nconst loadPublicKey = async () => {\n const response = await fetch(`${config.baseUrl}${ApiUrls.WellKnown.jwks}`, {\n cache: 'force-cache',\n });\n const data = await response.json();\n return data.keys[0];\n};\n\n/**\n * Send HTTP post request for Frontegg services to refresh token\n * by providing client's fe_ cookies\n */\nconst refreshTokenEmbedded = async (headers: Record<string, string>) => {\n return Post({\n url: `${config.baseUrl}${ApiUrls.refreshToken.embedded}`,\n body: '{}',\n credentials: 'include',\n headers: buildRequestHeaders(headers),\n });\n};\n\n/**\n * Send HTTP post request for Frontegg services to refresh `hosted login` token\n * by providing client's fe_ as body with grant_type.\n */\nconst refreshTokenHostedLogin = async (headers: Record<string, string>, refresh_token: string) => {\n return Post({\n url: `${config.baseUrl}${ApiUrls.refreshToken.hosted}`,\n body: JSON.stringify({\n grant_type: 'refresh_token',\n refresh_token,\n }),\n headers: buildRequestHeaders(headers),\n });\n};\n\n/**\n *\n * @param headers\n */\nexport const getUsers = async (headers: Record<string, string>): Promise<ILoginResponse | undefined> => {\n const headersToSend = buildRequestHeaders(headers);\n const res = await Get({\n url: `${config.baseUrl}/frontegg${fronteggUsersUrl}`,\n headers: headersToSend,\n });\n return parseHttpResponse(res);\n};\n\n/**\n *\n * @param headers\n */\nexport const getTenants = async (\n headers: Record<string, string>\n): Promise<GetCurrentUserTenantsResponse | undefined> => {\n const res = await Get({\n url: `${config.baseUrl}/frontegg${fronteggTenantsV3Url}`,\n headers: buildRequestHeaders(headers),\n });\n return parseHttpResponse(res);\n};\n\nexport const getPublicSettings = async (\n headers: Record<string, string>\n): Promise<IPublicSettingsResponse | undefined> => {\n const res = await Get({\n //TODO: export the route url from rest-api and import from there\n url: `${config.baseUrl}/frontegg/tenants/resources/account-settings/v1/public`,\n headers: buildRequestHeaders(headers),\n });\n return parseHttpResponse(res);\n};\n\nexport default {\n loadPubl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GAAAD,QAAA"}
package/api/utils.d.ts CHANGED
@@ -18,6 +18,10 @@ export declare const Post: ({ url, credentials, headers, body }: PostRequestOpti
18
18
  export declare function removeInvalidHeaders(headers: Record<string, string>): {
19
19
  [x: string]: string;
20
20
  };
21
+ /**
22
+ * These header is used to identify the tenant for login per tenant feature
23
+ */
24
+ export declare const CUSTOM_LOGIN_HEADER = "frontegg-login-alias";
21
25
  /**
22
26
  * Build fetch request headers, remove invalid http headers
23
27
  * @param headers - Incoming request headers
package/api/utils.js CHANGED
@@ -4,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.Post = exports.Get = void 0;
7
+ exports.Post = exports.Get = exports.CUSTOM_LOGIN_HEADER = void 0;
8
8
  exports.buildRequestHeaders = buildRequestHeaders;
9
9
  exports.isMiddlewarePath = isMiddlewarePath;
10
10
  exports.parseHttpResponse = void 0;
@@ -62,10 +62,15 @@ function removeInvalidHeaders(headers) {
62
62
  return newHeaders;
63
63
  }
64
64
 
65
+ /**
66
+ * These header is used to identify the tenant for login per tenant feature
67
+ */
68
+ const CUSTOM_LOGIN_HEADER = 'frontegg-login-alias';
65
69
  /**
66
70
  * Build fetch request headers, remove invalid http headers
67
71
  * @param headers - Incoming request headers
68
72
  */
73
+ exports.CUSTOM_LOGIN_HEADER = CUSTOM_LOGIN_HEADER;
69
74
  function buildRequestHeaders(headers) {
70
75
  let cookie = headers['cookie'];
71
76
  if (cookie != null && typeof cookie === 'string') {
@@ -87,6 +92,9 @@ function buildRequestHeaders(headers) {
87
92
  'x-frontegg-framework': `next@${_package.default.version}`,
88
93
  'x-frontegg-sdk': `@frontegg/nextjs@${_sdkVersion.default.version}`
89
94
  };
95
+ if (headers[CUSTOM_LOGIN_HEADER]) {
96
+ preparedHeaders[CUSTOM_LOGIN_HEADER] = headers[CUSTOM_LOGIN_HEADER];
97
+ }
90
98
  return removeInvalidHeaders((0, _extends2.default)({}, preparedHeaders));
91
99
  }
92
100
 
package/api/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["_config","_interopRequireDefault","require","_sdkVersion","_package","_restApi","_constants","Get","url","credentials","headers","fetch","method","exports","Post","body","removeInvalidHeaders","newHeaders","_extends2","default","Object","keys","forEach","key","val","Array","isArray","headerCharRegex","exec","undefined","length","buildRequestHeaders","cookie","replace","entries","map","value","join","preparedHeaders","authorization","accept","origin","config","baseUrl","nextjsPkg","version","sdkVersion","parseHttpResponse","res","ok","json","isMiddlewarePath","path","isAuthPath","fronteggAuthApiRoutesRegex","find","pathRegex","RegExp","test","isSocialLoginPath","endsWith"],"sources":["../../../../packages/nextjs/src/api/utils.ts"],"sourcesContent":["import config from '../config';\nimport sdkVersion from '../sdkVersion';\nimport nextjsPkg from 'next/package.json';\nimport { fronteggAuthApiRoutesRegex } from '@frontegg/rest-api';\nimport { headerCharRegex } from '../utils/common/constants';\n\ninterface GetRequestOptions {\n url: string;\n credentials?: RequestCredentials;\n headers?: HeadersInit;\n}\n\nexport const Get = ({ url, credentials = 'include', headers }: GetRequestOptions) =>\n fetch(url, { method: 'GET', credentials, headers });\n\ninterface PostRequestOptions extends GetRequestOptions {\n body: string;\n}\n\nexport const Post = ({ url, credentials = 'include', headers, body }: PostRequestOptions) =>\n fetch(url, { method: 'POST', credentials, headers, body });\n\n/**\n * NodeJS 18 start using undici as http request handler,\n * undici http request does not accept invalid headers\n * for more details see:\n * https://github.com/nodejs/undici/blob/2b260c997ad4efe4ed2064b264b4b546a59e7a67/lib/core/request.js#L282\n * @param headers\n */\nexport function removeInvalidHeaders(headers: Record<string, string>) {\n const newHeaders = { ...headers };\n Object.keys(newHeaders).forEach((key: string) => {\n const val: any = headers[key];\n if (val && typeof val === 'object' && !Array.isArray(val)) {\n delete newHeaders[key];\n } else if (headerCharRegex.exec(val) !== null) {\n delete newHeaders[key];\n } else if (val === undefined || val === null) {\n delete newHeaders[key];\n } else if (key.length === 10 && key === 'connection') {\n delete newHeaders[key];\n }\n });\n return newHeaders;\n}\n\n/**\n * Build fetch request headers, remove invalid http headers\n * @param headers - Incoming request headers\n */\nexport function buildRequestHeaders(headers: Record<string, any>): Record<string, string> {\n let cookie = headers['cookie'];\n if (cookie != null && typeof cookie === 'string') {\n cookie = cookie.replace(/fe_session-[^=]*=[^;]*$/, '').replace(/fe_session-[^=]*=[^;]*;/, '');\n }\n if (cookie != null && typeof cookie === 'object') {\n cookie = Object.entries(cookie)\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n }\n\n const preparedHeaders: Record<string, string> = {\n authorization: headers['authorization'],\n 'accept-encoding': headers['accept-encoding'],\n 'accept-language': headers['accept-language'],\n accept: headers['accept'],\n 'content-type': 'application/json',\n origin: config.baseUrl,\n cookie,\n 'user-agent': headers['user-agent'],\n 'cache-control': headers['cache-control'],\n 'x-frontegg-framework': `next@${nextjsPkg.version}`,\n 'x-frontegg-sdk': `@frontegg/nextjs@${sdkVersion.version}`,\n };\n\n return removeInvalidHeaders({ ...preparedHeaders });\n}\n\n/**\n * Return parsed json response if http status code = 200\n * @param res\n */\nexport const parseHttpResponse = async <T>(res: Response): Promise<T | undefined> => {\n if (!res.ok) {\n return undefined;\n }\n return await res.json();\n};\n\n/**\n * Checks if the given path should be forwarded to the Next.js server middleware.\n *\n *\n * @param {string} path - The path to check for authentication API routes.\n * @returns {boolean} Returns true if the path is a frontegg authentication API route or ends with '/postlogin' or '/prelogin'; otherwise, returns false.\n */\nexport function isMiddlewarePath(path: string): boolean {\n let isAuthPath =\n fronteggAuthApiRoutesRegex.find((pathRegex) => {\n if (typeof pathRegex === 'string') {\n return pathRegex === path;\n } else {\n return new RegExp(pathRegex).test(path);\n }\n }) != null;\n\n // if(!isAuthPath){\n // isAuthPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/user\\/sso\\/[^\\/]*\\/postlogin$/g.test(path)\n // }\n // if(!isAuthPath){\n // isAuthPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/passwordless\\/[^\\/]*\\/prelogin$/g.test(path)\n // }\n // if(!isAuthPath){\n // isAuthPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/[^\\/]*\\/prelogin$/g.test(path)\n // }\n\n if (!isAuthPath) {\n const isSocialLoginPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/user\\/sso\\/default\\/[^\\/]*\\/prelogin$/.test(path);\n isAuthPath = (path.endsWith('/postlogin') || path.endsWith('/prelogin')) && !isSocialLoginPath;\n }\n\n return isAuthPath;\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,WAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,QAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AACA,IAAAI,UAAA,GAAAJ,OAAA;AAQO,MAAMK,GAAG,GAAGA,CAAC;EAAEC,GAAG;EAAEC,WAAW,GAAG,SAAS;EAAEC;AAA2B,CAAC,KAC9EC,KAAK,CAACH,GAAG,EAAE;EAAEI,MAAM,EAAE,KAAK;EAAEH,WAAW;EAAEC;AAAQ,CAAC,CAAC;AAACG,OAAA,CAAAN,GAAA,GAAAA,GAAA;AAM/C,MAAMO,IAAI,GAAGA,CAAC;EAAEN,GAAG;EAAEC,WAAW,GAAG,SAAS;EAAEC,OAAO;EAAEK;AAAyB,CAAC,KACtFJ,KAAK,CAACH,GAAG,EAAE;EAAEI,MAAM,EAAE,MAAM;EAAEH,WAAW;EAAEC,OAAO;EAAEK;AAAK,CAAC,CAAC;;AAE5D;AACA;AACA;AACA;AACA;AACA;AACA;AANAF,OAAA,CAAAC,IAAA,GAAAA,IAAA;AAOO,SAASE,oBAAoBA,CAACN,OAA+B,EAAE;EACpE,MAAMO,UAAU,OAAAC,SAAA,CAAAC,OAAA,MAAQT,OAAO,CAAE;EACjCU,MAAM,CAACC,IAAI,C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ACf,MAAMM,iBAAiB,GAAG,8EAA8E,CAACD,IAAI,CAACN,IAAI,CAAC;IACnHC,UAAU,GAAG,CAACD,IAAI,CAACQ,QAAQ,CAAC,YAAY,CAAC,IAAIR,IAAI,CAACQ,QAAQ,CAAC,WAAW,CAAC,KAAK,CAACD,iBAAiB;EAChG;EAEA,OAAON,UAAU;AACnB"}
1
+ {"version":3,"file":"utils.js","names":["_config","_interopRequireDefault","require","_sdkVersion","_package","_restApi","_constants","Get","url","credentials","headers","fetch","method","exports","Post","body","removeInvalidHeaders","newHeaders","_extends2","default","Object","keys","forEach","key","val","Array","isArray","headerCharRegex","exec","undefined","length","CUSTOM_LOGIN_HEADER","buildRequestHeaders","cookie","replace","entries","map","value","join","preparedHeaders","authorization","accept","origin","config","baseUrl","nextjsPkg","version","sdkVersion","parseHttpResponse","res","ok","json","isMiddlewarePath","path","isAuthPath","fronteggAuthApiRoutesRegex","find","pathRegex","RegExp","test","isSocialLoginPath","endsWith"],"sources":["../../../../packages/nextjs/src/api/utils.ts"],"sourcesContent":["import config from '../config';\nimport sdkVersion from '../sdkVersion';\nimport nextjsPkg from 'next/package.json';\nimport { fronteggAuthApiRoutesRegex } from '@frontegg/rest-api';\nimport { headerCharRegex } from '../utils/common/constants';\n\ninterface GetRequestOptions {\n url: string;\n credentials?: RequestCredentials;\n headers?: HeadersInit;\n}\n\nexport const Get = ({ url, credentials = 'include', headers }: GetRequestOptions) =>\n fetch(url, { method: 'GET', credentials, headers });\n\ninterface PostRequestOptions extends GetRequestOptions {\n body: string;\n}\n\nexport const Post = ({ url, credentials = 'include', headers, body }: PostRequestOptions) =>\n fetch(url, { method: 'POST', credentials, headers, body });\n\n/**\n * NodeJS 18 start using undici as http request handler,\n * undici http request does not accept invalid headers\n * for more details see:\n * https://github.com/nodejs/undici/blob/2b260c997ad4efe4ed2064b264b4b546a59e7a67/lib/core/request.js#L282\n * @param headers\n */\nexport function removeInvalidHeaders(headers: Record<string, string>) {\n const newHeaders = { ...headers };\n Object.keys(newHeaders).forEach((key: string) => {\n const val: any = headers[key];\n if (val && typeof val === 'object' && !Array.isArray(val)) {\n delete newHeaders[key];\n } else if (headerCharRegex.exec(val) !== null) {\n delete newHeaders[key];\n } else if (val === undefined || val === null) {\n delete newHeaders[key];\n } else if (key.length === 10 && key === 'connection') {\n delete newHeaders[key];\n }\n });\n return newHeaders;\n}\n\n/**\n * These header is used to identify the tenant for login per tenant feature\n */\nexport const CUSTOM_LOGIN_HEADER = 'frontegg-login-alias';\n/**\n * Build fetch request headers, remove invalid http headers\n * @param headers - Incoming request headers\n */\nexport function buildRequestHeaders(headers: Record<string, any>): Record<string, string> {\n let cookie = headers['cookie'];\n if (cookie != null && typeof cookie === 'string') {\n cookie = cookie.replace(/fe_session-[^=]*=[^;]*$/, '').replace(/fe_session-[^=]*=[^;]*;/, '');\n }\n if (cookie != null && typeof cookie === 'object') {\n cookie = Object.entries(cookie)\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n }\n\n const preparedHeaders: Record<string, string> = {\n authorization: headers['authorization'],\n 'accept-encoding': headers['accept-encoding'],\n 'accept-language': headers['accept-language'],\n accept: headers['accept'],\n 'content-type': 'application/json',\n origin: config.baseUrl,\n cookie,\n 'user-agent': headers['user-agent'],\n 'cache-control': headers['cache-control'],\n 'x-frontegg-framework': `next@${nextjsPkg.version}`,\n 'x-frontegg-sdk': `@frontegg/nextjs@${sdkVersion.version}`,\n };\n\n if (headers[CUSTOM_LOGIN_HEADER]) {\n preparedHeaders[CUSTOM_LOGIN_HEADER] = headers[CUSTOM_LOGIN_HEADER];\n }\n return removeInvalidHeaders({ ...preparedHeaders });\n}\n\n/**\n * Return parsed json response if http status code = 200\n * @param res\n */\nexport const parseHttpResponse = async <T>(res: Response): Promise<T | undefined> => {\n if (!res.ok) {\n return undefined;\n }\n return await res.json();\n};\n\n/**\n * Checks if the given path should be forwarded to the Next.js server middleware.\n *\n *\n * @param {string} path - The path to check for authentication API routes.\n * @returns {boolean} Returns true if the path is a frontegg authentication API route or ends with '/postlogin' or '/prelogin'; otherwise, returns false.\n */\nexport function isMiddlewarePath(path: string): boolean {\n let isAuthPath =\n fronteggAuthApiRoutesRegex.find((pathRegex) => {\n if (typeof pathRegex === 'string') {\n return pathRegex === path;\n } else {\n return new RegExp(pathRegex).test(path);\n }\n }) != null;\n\n // if(!isAuthPath){\n // isAuthPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/user\\/sso\\/[^\\/]*\\/postlogin$/g.test(path)\n // }\n // if(!isAuthPath){\n // isAuthPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/passwordless\\/[^\\/]*\\/prelogin$/g.test(path)\n // }\n // if(!isAuthPath){\n // isAuthPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/[^\\/]*\\/prelogin$/g.test(path)\n // }\n\n if (!isAuthPath) {\n const isSocialLoginPath = /^\\/identity\\/resources\\/auth\\/v[0-9]*\\/user\\/sso\\/default\\/[^\\/]*\\/prelogin$/.test(path);\n isAuthPath = (path.endsWith('/postlogin') || path.endsWith('/prelogin')) && !isSocialLoginPath;\n }\n\n return isAuthPath;\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,WAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,QAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AACA,IAAAI,UAAA,GAAAJ,OAAA;AAQO,MAAMK,GAAG,GAAGA,CAAC;EAAEC,GAAG;EAAEC,WAAW,GAAG,SAAS;EAAEC;AAA2B,CAAC,KAC9EC,KAAK,CAACH,GAAG,EAAE;EAAEI,MAAM,EAAE,KAAK;EAAEH,WAAW;EAAEC;AAAQ,CAAC,CAAC;AAACG,OAAA,CAAAN,GAAA,GAAAA,GAAA;AAM/C,MAAMO,IAAI,GAAGA,CAAC;EAAEN,GAAG;EAAEC,WAAW,GAAG,SAAS;EAAE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ACC,EAAE,EAAE;IACX,OAAOrB,SAAS;EAClB;EACA,OAAO,MAAMoB,GAAG,CAACE,IAAI,EAAE;AACzB,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AANAtC,OAAA,CAAAmC,iBAAA,GAAAA,iBAAA;AAOO,SAASI,gBAAgBA,CAACC,IAAY,EAAW;EACtD,IAAIC,UAAU,GACZC,mCAA0B,CAACC,IAAI,CAAEC,SAAS,IAAK;IAC7C,IAAI,OAAOA,SAAS,KAAK,QAAQ,EAAE;MACjC,OAAOA,SAAS,KAAKJ,IAAI;IAC3B,CAAC,MAAM;MACL,OAAO,IAAIK,MAAM,CAACD,SAAS,CAAC,CAACE,IAAI,CAACN,IAAI,CAAC;IACzC;EACF,CAAC,CAAC,IAAI,IAAI;;EAEZ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA,IAAI,CAACC,UAAU,EAAE;IACf,MAAMM,iBAAiB,GAAG,8EAA8E,CAACD,IAAI,CAACN,IAAI,CAAC;IACnHC,UAAU,GAAG,CAACD,IAAI,CAACQ,QAAQ,CAAC,YAAY,CAAC,IAAIR,IAAI,CAACQ,QAAQ,CAAC,WAAW,CAAC,KAAK,CAACD,iBAAiB;EAChG;EAEA,OAAON,UAAU;AACnB"}
@@ -6,19 +6,30 @@ Object.defineProperty(exports, "__esModule", {
6
6
  });
7
7
  exports.FronteggAppProvider = void 0;
8
8
  var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
9
+ var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
9
10
  var _react = _interopRequireDefault(require("react"));
10
11
  var _ClientFronteggProvider = require("./ClientFronteggProvider");
11
12
  var _helpers = require("./helpers");
12
13
  var _config = _interopRequireDefault(require("../config"));
13
14
  var _fetchUserData = _interopRequireDefault(require("../utils/fetchUserData"));
15
+ var _getAppUrlForCustomLoginWithSubdomain = require("./getAppUrlForCustomLoginWithSubdomain");
14
16
  var _jsxRuntime = require("react/jsx-runtime");
17
+ const _excluded = ["envAppUrl"];
15
18
  const FronteggAppProvider = async options => {
16
- const appEnvConfig = _config.default.appEnvConfig;
19
+ var _options$customLoginO;
20
+ const _config$appEnvConfig = _config.default.appEnvConfig,
21
+ {
22
+ envAppUrl
23
+ } = _config$appEnvConfig,
24
+ appEnvConfig = (0, _objectWithoutPropertiesLoose2.default)(_config$appEnvConfig, _excluded);
17
25
  const userData = await (0, _fetchUserData.default)({
18
26
  getSession: _helpers.getAppSession,
19
- getHeaders: _helpers.getAppHeaders
27
+ getHeaders: _helpers.getAppHeadersPromise
28
+ });
29
+ const subDomainAppUrl = await (0, _getAppUrlForCustomLoginWithSubdomain.getAppUrlForCustomLoginWithSubdomain)((_options$customLoginO = options.customLoginOptions) == null ? void 0 : _options$customLoginO.subDomainIndex);
30
+ const providerProps = (0, _extends2.default)({}, appEnvConfig, userData, options, {
31
+ envAppUrl: subDomainAppUrl != null ? subDomainAppUrl : envAppUrl
20
32
  });
21
- const providerProps = (0, _extends2.default)({}, appEnvConfig, userData, options);
22
33
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ClientFronteggProvider.ClientFronteggProvider, (0, _extends2.default)({}, providerProps));
23
34
  };
24
35
  exports.FronteggAppProvider = FronteggAppProvider;
@@ -1 +1 @@
1
- {"version":3,"file":"FronteggAppProvider.js","names":["_react","_interopRequireDefault","require","_ClientFronteggProvider","_helpers","_config","_fetchUserData","_jsxRuntime","FronteggAppProvider","options","appEnvConfig","config","userData","fetchUserData","getSession","getAppSession","getHeaders","getAppHeaders","providerProps","_extends2","default","jsx","ClientFronteggProvider","exports"],"sources":["../../../../packages/nextjs/src/app/FronteggAppProvider.tsx"],"sourcesContent":["import React, { PropsWithChildren } from 'react';\nimport { ClientFronteggProvider } from './ClientFronteggProvider';\nimport { getAppHeaders, getAppSession } from './helpers';\nimport config from '../config';\nimport fetchUserData from '../utils/fetchUserData';\nimport { ClientFronteggProviderProps } from '../types';\n\nexport type FronteggAppProviderProps = PropsWithChildren<Omit<ClientFronteggProviderProps, 'contextOptions'>>;\n\nexport const FronteggAppProvider = async (options: FronteggAppProviderProps) => {\n const appEnvConfig = config.appEnvConfig;\n const userData = await fetchUserData({ getSession: getAppSession, getHeaders: getAppHeaders });\n\n const providerProps = {\n ...appEnvConfig,\n ...userData,\n ...options,\n };\n\n return <ClientFronteggProvider {...providerProps} />;\n};\n"],"mappings":";;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,uBAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,cAAA,GAAAL,sBAAA,CAAAC,OAAA;AAAmD,IAAAK,WAAA,GAAAL,OAAA;AAK5C,MAAMM,mBAAmB,GAAG,MAAOC,OAAiC,IAAK;EAC9E,MAAMC,YAAY,GAAGC,eAAM,CAACD,YAAY;EACxC,MAAME,QAAQ,GAAG,MAAM,IAAAC,sBAAa,EAAC;IAAEC,UAAU,EAAEC,sBAAa;IAAEC,UAAU,EAAEC;EAAc,CAAC,CAAC;EAE9F,MAAMC,aAAa,OAAAC,SAAA,CAAAC,OAAA,MACdV,YAAY,EACZE,QAAQ,EACRH,OAAO,CACX;EAED,oBAAO,IAAAF,WAAA,CAAAc,GAAA,EAAClB,uBAAA,CAAAmB,sBAAsB,MAAAH,SAAA,CAAAC,OAAA,MAAKF,aAAa,EAAI;AACtD,CAAC;AAACK,OAAA,CAAAf,mBAAA,GAAAA,mBAAA"}
1
+ {"version":3,"file":"FronteggAppProvider.js","names":["_react","_interopRequireDefault","require","_ClientFronteggProvider","_helpers","_config","_fetchUserData","_getAppUrlForCustomLoginWithSubdomain","_jsxRuntime","_excluded","FronteggAppProvider","options","_options$customLoginO","_config$appEnvConfig","config","appEnvConfig","envAppUrl","_objectWithoutPropertiesLoose2","default","userData","fetchUserData","getSession","getAppSession","getHeaders","getAppHeadersPromise","subDomainAppUrl","getAppUrlForCustomLoginWithSubdomain","customLoginOptions","subDomainIndex","providerProps","_extends2","jsx","ClientFronteggProvider","exports"],"sources":["../../../../packages/nextjs/src/app/FronteggAppProvider.tsx"],"sourcesContent":["import React, { PropsWithChildren } from 'react';\nimport { ClientFronteggProvider } from './ClientFronteggProvider';\nimport { getAppHeadersPromise, getAppSession } from './helpers';\nimport config from '../config';\nimport fetchUserData from '../utils/fetchUserData';\nimport { ClientFronteggProviderProps } from '../types';\nimport { getAppUrlForCustomLoginWithSubdomain } from './getAppUrlForCustomLoginWithSubdomain';\n\nexport type FronteggAppProviderProps = PropsWithChildren<Omit<ClientFronteggProviderProps, 'contextOptions'>>;\n\nexport const FronteggAppProvider = async (options: FronteggAppProviderProps) => {\n const { envAppUrl, ...appEnvConfig } = config.appEnvConfig;\n const userData = await fetchUserData({ getSession: getAppSession, getHeaders: getAppHeadersPromise });\n const subDomainAppUrl = await getAppUrlForCustomLoginWithSubdomain(options.customLoginOptions?.subDomainIndex);\n\n const providerProps = {\n ...appEnvConfig,\n ...userData,\n ...options,\n envAppUrl: subDomainAppUrl ?? envAppUrl,\n };\n\n return <ClientFronteggProvider {...providerProps} />;\n};\n"],"mappings":";;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,uBAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,cAAA,GAAAL,sBAAA,CAAAC,OAAA;AAEA,IAAAK,qCAAA,GAAAL,OAAA;AAA8F,IAAAM,WAAA,GAAAN,OAAA;AAAA,MAAAO,SAAA;AAIvF,MAAMC,mBAAmB,GAAG,MAAOC,OAAiC,IAAK;EAAA,IAAAC,qBAAA;EAC9E,MAAAC,oBAAA,GAAuCC,eAAM,CAACC,YAAY;IAApD;MAAEC;IAA2B,CAAC,GAAAH,oBAAA;IAAdE,YAAY,OAAAE,8BAAA,CAAAC,OAAA,EAAAL,oBAAA,EAAAJ,SAAA;EAClC,MAAMU,QAAQ,GAAG,MAAM,IAAAC,sBAAa,EAAC;IAAEC,UAAU,EAAEC,sBAAa;IAAEC,UAAU,EAAEC;EAAqB,CAAC,CAAC;EACrG,MAAMC,eAAe,GAAG,MAAM,IAAAC,0EAAoC,GAAAd,qBAAA,GAACD,OAAO,CAACgB,kBAAkB,qBAA1Bf,qBAAA,CAA4BgB,cAAc,CAAC;EAE9G,MAAMC,aAAa,OAAAC,SAAA,CAAAZ,OAAA,MACdH,YAAY,EACZI,QAAQ,EACRR,OAAO;IACVK,SAAS,EAAES,eAAe,WAAfA,eAAe,GAAIT;EAAS,EACxC;EAED,oBAAO,IAAAR,WAAA,CAAAuB,GAAA,EAAC5B,uBAAA,CAAA6B,sBAAsB,MAAAF,SAAA,CAAAZ,OAAA,MAAKW,aAAa,EAAI;AACtD,CAAC;AAACI,OAAA,CAAAvB,mBAAA,GAAAA,mBAAA"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * get the tenant alias from the request headers with the host and subdomain index
3
+ * @param headers - the request headers
4
+ * @param subDomainIndex - the subdomain index to specify the tenant sub-domain
5
+ * @returns the alias for custom login with subdomain or undefined if not exist
6
+ */
7
+ export declare const getTenantAliasFromHeaders: (headers: Record<string, string>, subDomainIndex: number) => string;
8
+ /**
9
+ * set the global.customLoginAppUrl to undefined in order to allow switching from tenant to vendor app
10
+ */
11
+ export declare const resetGlobalCustomLoginAppUrl: () => void;
12
+ /**
13
+ * get the app url for custom login with subdomain and set it to the global customLoginAppUrl
14
+ * @param subDomainIndex - the index of the subdomain in the host
15
+ * @returns Promise of string or undefined, the app url for custom login with subdomain or undefined if the sub-domain index/app url/alias is not exist
16
+ * @sideEffect - set the global.customLoginAppUrl to the app url for custom login with subdomain */
17
+ export declare const getAppUrlForCustomLoginWithSubdomain: (subDomainIndex?: number) => Promise<string | undefined>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.resetGlobalCustomLoginAppUrl = exports.getTenantAliasFromHeaders = exports.getAppUrlForCustomLoginWithSubdomain = void 0;
8
+ var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
9
+ var _api = require("../api");
10
+ var _utils = require("../api/utils");
11
+ var _helpers = require("./helpers");
12
+ /**
13
+ * get the tenant alias from the request headers with the host and subdomain index
14
+ * @param headers - the request headers
15
+ * @param subDomainIndex - the subdomain index to specify the tenant sub-domain
16
+ * @returns the alias for custom login with subdomain or undefined if not exist
17
+ */
18
+ const getTenantAliasFromHeaders = (headers, subDomainIndex) => {
19
+ var _headers$host, _headers$host$split, _headers$host$split$s;
20
+ return headers == null ? void 0 : (_headers$host = headers.host) == null ? void 0 : (_headers$host$split = _headers$host.split('.')) == null ? void 0 : (_headers$host$split$s = _headers$host$split.slice(0, -2)) == null ? void 0 : _headers$host$split$s[subDomainIndex];
21
+ };
22
+
23
+ /**
24
+ * set the global.customLoginAppUrl to undefined in order to allow switching from tenant to vendor app
25
+ */
26
+ exports.getTenantAliasFromHeaders = getTenantAliasFromHeaders;
27
+ const resetGlobalCustomLoginAppUrl = () => {
28
+ global.customLoginAppUrl = undefined;
29
+ };
30
+
31
+ /**
32
+ * get the app url for custom login with subdomain and set it to the global customLoginAppUrl
33
+ * @param subDomainIndex - the index of the subdomain in the host
34
+ * @returns Promise of string or undefined, the app url for custom login with subdomain or undefined if the sub-domain index/app url/alias is not exist
35
+ * @sideEffect - set the global.customLoginAppUrl to the app url for custom login with subdomain */
36
+ exports.resetGlobalCustomLoginAppUrl = resetGlobalCustomLoginAppUrl;
37
+ const getAppUrlForCustomLoginWithSubdomain = async subDomainIndex => {
38
+ if (subDomainIndex === undefined) {
39
+ return undefined;
40
+ }
41
+ const headers = (0, _helpers.getAppHeaders)();
42
+ const alias = getTenantAliasFromHeaders(headers, subDomainIndex);
43
+ if (!alias) {
44
+ resetGlobalCustomLoginAppUrl();
45
+ return undefined;
46
+ }
47
+ const requestHeaders = (0, _extends2.default)({}, headers, {
48
+ [_utils.CUSTOM_LOGIN_HEADER]: alias
49
+ });
50
+ const res = await (0, _api.getPublicSettings)(requestHeaders).catch(() => undefined);
51
+ const subDomainAppUrl = res == null ? void 0 : res.applicationUrl;
52
+ if (!subDomainAppUrl) {
53
+ resetGlobalCustomLoginAppUrl();
54
+ return undefined;
55
+ }
56
+ global.customLoginAppUrl = subDomainAppUrl;
57
+ return subDomainAppUrl;
58
+ };
59
+ exports.getAppUrlForCustomLoginWithSubdomain = getAppUrlForCustomLoginWithSubdomain;
60
+ //# sourceMappingURL=getAppUrlForCustomLoginWithSubdomain.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getAppUrlForCustomLoginWithSubdomain.js","names":["_api","require","_utils","_helpers","getTenantAliasFromHeaders","headers","subDomainIndex","_headers$host","_headers$host$split","_headers$host$split$s","host","split","slice","exports","resetGlobalCustomLoginAppUrl","global","customLoginAppUrl","undefined","getAppUrlForCustomLoginWithSubdomain","getAppHeaders","alias","requestHeaders","_extends2","default","CUSTOM_LOGIN_HEADER","res","getPublicSettings","catch","subDomainAppUrl","applicationUrl"],"sources":["../../../../packages/nextjs/src/app/getAppUrlForCustomLoginWithSubdomain.ts"],"sourcesContent":["import { getPublicSettings } from '../api';\nimport { CUSTOM_LOGIN_HEADER } from '../api/utils';\nimport { getAppHeaders } from './helpers';\n\n/**\n * get the tenant alias from the request headers with the host and subdomain index\n * @param headers - the request headers\n * @param subDomainIndex - the subdomain index to specify the tenant sub-domain\n * @returns the alias for custom login with subdomain or undefined if not exist\n */\nexport const getTenantAliasFromHeaders = (headers: Record<string, string>, subDomainIndex: number) => {\n return headers?.host?.split('.')?.slice(0, -2)?.[subDomainIndex];\n};\n\n/**\n * set the global.customLoginAppUrl to undefined in order to allow switching from tenant to vendor app\n */\nexport const resetGlobalCustomLoginAppUrl = () => {\n global.customLoginAppUrl = undefined;\n};\n\n/**\n * get the app url for custom login with subdomain and set it to the global customLoginAppUrl\n * @param subDomainIndex - the index of the subdomain in the host\n * @returns Promise of string or undefined, the app url for custom login with subdomain or undefined if the sub-domain index/app url/alias is not exist\n * @sideEffect - set the global.customLoginAppUrl to the app url for custom login with subdomain */\n\nexport const getAppUrlForCustomLoginWithSubdomain = async (subDomainIndex?: number): Promise<string | undefined> => {\n if (subDomainIndex === undefined) {\n return undefined;\n }\n\n const headers = getAppHeaders();\n const alias = getTenantAliasFromHeaders(headers, subDomainIndex);\n if (!alias) {\n resetGlobalCustomLoginAppUrl();\n return undefined;\n }\n const requestHeaders = { ...headers, [CUSTOM_LOGIN_HEADER]: alias };\n const res = await getPublicSettings(requestHeaders).catch(() => undefined);\n const subDomainAppUrl = res?.applicationUrl;\n if (!subDomainAppUrl) {\n resetGlobalCustomLoginAppUrl();\n return undefined;\n }\n global.customLoginAppUrl = subDomainAppUrl;\n return subDomainAppUrl;\n};\n"],"mappings":";;;;;;;;AAAA,IAAAA,IAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMG,yBAAyB,GAAGA,CAACC,OAA+B,EAAEC,cAAsB,KAAK;EAAA,IAAAC,aAAA,EAAAC,mBAAA,EAAAC,qBAAA;EACpG,OAAOJ,OAAO,qBAAAE,aAAA,GAAPF,OAAO,CAAEK,IAAI,sBAAAF,mBAAA,GAAbD,aAAA,CAAeI,KAAK,CAAC,GAAG,CAAC,sBAAAF,qBAAA,GAAzBD,mBAAA,CAA2BI,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,qBAAvCH,qBAAA,CAA0CH,cAAc,CAAC;AAClE,CAAC;;AAED;AACA;AACA;AAFAO,OAAA,CAAAT,yBAAA,GAAAA,yBAAA;AAGO,MAAMU,4BAA4B,GAAGA,CAAA,KAAM;EAChDC,MAAM,CAACC,iBAAiB,GAAGC,SAAS;AACtC,CAAC;;AAED;AACA;AACA;AACA;AACA;AAJAJ,OAAA,CAAAC,4BAAA,GAAAA,4BAAA;AAMO,MAAMI,oCAAoC,GAAG,MAAOZ,cAAuB,IAAkC;EAClH,IAAIA,cAAc,KAAKW,SAAS,EAAE;IAChC,OAAOA,SAAS;EAClB;EAEA,MAAMZ,OAAO,GAAG,IAAAc,sBAAa,GAAE;EAC/B,MAAMC,KAAK,GAAGhB,yBAAyB,CAACC,OAAO,EAAEC,cAAc,CAAC;EAChE,IAAI,CAACc,KAAK,EAAE;IACVN,4BAA4B,EAAE;IAC9B,OAAOG,SAAS;EAClB;EACA,MAAMI,cAAc,OAAAC,SAAA,CAAAC,OAAA,MAAQlB,OAAO;IAAE,CAACmB,0BAAmB,GAAGJ;EAAK,EAAE;EACnE,MAAMK,GAAG,GAAG,MAAM,IAAAC,sBAAiB,EAACL,cAAc,CAAC,CAACM,KAAK,CAAC,MAAMV,SAAS,CAAC;EAC1E,MAAMW,eAAe,GAAGH,GAAG,oBAAHA,GAAG,CAAEI,cAAc;EAC3C,IAAI,CAACD,eAAe,EAAE;IACpBd,4BAA4B,EAAE;IAC9B,OAAOG,SAAS;EAClB;EACAF,MAAM,CAACC,iBAAiB,GAAGY,eAAe;EAC1C,OAAOA,eAAe;AACxB,CAAC;AAACf,OAAA,CAAAK,oCAAA,GAAAA,oCAAA"}
package/app/helpers.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { FronteggUserSession, FronteggUserTokens } from '../types';
2
2
  export declare const getAppSession: () => Promise<import("../types").FronteggNextJSSession | undefined>;
3
- export declare const getAppHeaders: () => Promise<Record<string, string>>;
3
+ export declare const getAppHeaders: () => Record<string, string>;
4
+ export declare const getAppHeadersPromise: () => Promise<Record<string, string>>;
4
5
  export declare function getAppUserSession(): Promise<FronteggUserSession | undefined>;
5
6
  export declare function getAppUserTokens(): Promise<FronteggUserTokens | undefined>;
package/app/helpers.js CHANGED
@@ -4,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.getAppSession = exports.getAppHeaders = void 0;
7
+ exports.getAppSession = exports.getAppHeadersPromise = exports.getAppHeaders = void 0;
8
8
  exports.getAppUserSession = getAppUserSession;
9
9
  exports.getAppUserTokens = getAppUserTokens;
10
10
  var _headers = require("next/headers");
@@ -20,12 +20,16 @@ const getAppSession = () => {
20
20
  return (0, _createSession.default)(cookies, _encryption.default);
21
21
  };
22
22
  exports.getAppSession = getAppSession;
23
- const getAppHeaders = async () => {
23
+ const getAppHeaders = () => {
24
24
  const reqHeaders = {};
25
25
  (0, _headers.headers)().forEach((value, key) => reqHeaders[key] = value);
26
26
  return reqHeaders;
27
27
  };
28
28
  exports.getAppHeaders = getAppHeaders;
29
+ const getAppHeadersPromise = async () => {
30
+ return getAppHeaders();
31
+ };
32
+ exports.getAppHeadersPromise = getAppHeadersPromise;
29
33
  async function getAppUserSession() {
30
34
  const session = await getAppSession();
31
35
  return session == null ? void 0 : session.user;
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","names":["_headers","require","_cookies","_interopRequireDefault","_createSession","_encryption","getCookie","allCookies","cookies","getAll","CookieManager","parseCookieFromArray","getAppSession","createSession","encryption","exports","getAppHeaders","reqHeaders","headers","forEach","value","key","getAppUserSession","session","user","getAppUserTokens","undefined","accessToken","refreshToken"],"sources":["../../../../packages/nextjs/src/app/helpers.ts"],"sourcesContent":["import { cookies, headers } from 'next/headers';\nimport CookieManager from '../utils/cookies';\nimport createSession from '../utils/createSession';\nimport encryption from '../utils/encryption';\nimport { FronteggUserSession, FronteggUserTokens } from '../types';\n\nconst getCookie = () => {\n const allCookies = cookies().getAll();\n return CookieManager.parseCookieFromArray(allCookies);\n};\n\nexport const getAppSession = () => {\n const cookies = getCookie();\n return createSession(cookies, encryption);\n};\n\nexport const getAppHeaders = async (): Promise<Record<string, string>> => {\n const reqHeaders: Record<string, string> = {};\n headers().forEach((value, key) => (reqHeaders[key] = value));\n return reqHeaders;\n};\n\nexport async function getAppUserSession(): Promise<FronteggUserSession | undefined> {\n const session = await getAppSession();\n return session?.user;\n}\n\nexport async function getAppUserTokens(): Promise<FronteggUserTokens | undefined> {\n const session = await getAppSession();\n if (!session) {\n return undefined;\n }\n return {\n accessToken: session.accessToken,\n refreshToken: session.refreshToken,\n };\n}\n"],"mappings":";;;;;;;;;AAAA,IAAAA,QAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,cAAA,GAAAD,sBAAA,CAAAF,OAAA;AACA,IAAAI,WAAA,GAAAF,sBAAA,CAAAF,OAAA;AAGA,MAAMK,SAAS,GAAGA,CAAA,KAAM;EACtB,MAAMC,UAAU,GAAG,IAAAC,gBAAO,GAAE,CAACC,MAAM,EAAE;EACrC,OAAOC,gBAAa,CAACC,oBAAoB,CAACJ,UAAU,CAAC;AACvD,CAAC;AAEM,MAAMK,aAAa,GAAGA,CAAA,KAAM;EACjC,MAAMJ,OAAO,GAAGF,SAAS,EAAE;EAC3B,OAAO,IAAAO,sBAAa,EAACL,OAAO,EAAEM,mBAAU,CAAC;AAC3C,CAAC;AAACC,OAAA,CAAAH,aAAA,GAAAA,aAAA;AAEK,MAAMI,aAAa,GAAG,MAAAA,CAAA,KAA6C;EACxE,MAAMC,UAAkC,GAAG,CAAC,CAAC;EAC7C,IAAAC,gBAAO,GAAE,CAACC,OAAO,CAAC,CAACC,KAAK,EAAEC,GAAG,KAAMJ,UAAU,CAACI,GAAG,CAAC,GAAGD,KAAM,CAAC;EAC5D,OAAOH,UAAU;AACnB,CAAC;AAACF,OAAA,CAAAC,aAAA,GAAAA,aAAA;AAEK,eAAeM,iBAAiBA,CAAA,EAA6C;EAClF,MAAMC,OAAO,GAAG,MAAMX,aAAa,EAAE;EACrC,OAAOW,OAAO,oBAAPA,OAAO,CAAEC,IAAI;AACtB;AAEO,eAAeC,gBAAgBA,CAAA,EAA4C;EAChF,MAAMF,OAAO,GAAG,MAAMX,aAAa,EAAE;EACrC,IAAI,CAACW,OAAO,EAAE;IACZ,OAAOG,SAAS;EAClB;EACA,OAAO;IACLC,WAAW,EAAEJ,OAAO,CAACI,WAAW;IAChCC,YAAY,EAAEL,OAAO,CAACK;EACxB,CAAC;AACH"}
1
+ {"version":3,"file":"helpers.js","names":["_headers","require","_cookies","_interopRequireDefault","_createSession","_encryption","getCookie","allCookies","cookies","getAll","CookieManager","parseCookieFromArray","getAppSession","createSession","encryption","exports","getAppHeaders","reqHeaders","headers","forEach","value","key","getAppHeadersPromise","getAppUserSession","session","user","getAppUserTokens","undefined","accessToken","refreshToken"],"sources":["../../../../packages/nextjs/src/app/helpers.ts"],"sourcesContent":["import { cookies, headers } from 'next/headers';\nimport CookieManager from '../utils/cookies';\nimport createSession from '../utils/createSession';\nimport encryption from '../utils/encryption';\nimport { FronteggUserSession, FronteggUserTokens } from '../types';\n\nconst getCookie = () => {\n const allCookies = cookies().getAll();\n return CookieManager.parseCookieFromArray(allCookies);\n};\n\nexport const getAppSession = () => {\n const cookies = getCookie();\n return createSession(cookies, encryption);\n};\n\nexport const getAppHeaders = (): Record<string, string> => {\n const reqHeaders: Record<string, string> = {};\n headers().forEach((value, key) => (reqHeaders[key] = value));\n return reqHeaders;\n};\n\nexport const getAppHeadersPromise = async (): Promise<Record<string, string>> => {\n return getAppHeaders();\n};\n\nexport async function getAppUserSession(): Promise<FronteggUserSession | undefined> {\n const session = await getAppSession();\n return session?.user;\n}\n\nexport async function getAppUserTokens(): Promise<FronteggUserTokens | undefined> {\n const session = await getAppSession();\n if (!session) {\n return undefined;\n }\n return {\n accessToken: session.accessToken,\n refreshToken: session.refreshToken,\n };\n}\n"],"mappings":";;;;;;;;;AAAA,IAAAA,QAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAA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 -81,6 +81,9 @@ function generateAppUrl() {
81
81
  throw new _errors.FronteggEnvNotFound(_constants.EnvVariables.FRONTEGG_APP_URL);
82
82
  }
83
83
  }
84
+ if (global.customLoginAppUrl) {
85
+ appUrl = global.customLoginAppUrl;
86
+ }
84
87
 
85
88
  /**
86
89
  * In some cases the {@link EnvVariables.VERCEL_URL} value does not
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","names":["_errors","require","_constants","getEnv","name","value","process","env","FronteggEnvNotFound","exports","getEnvOrDefault","defaultValue","e","generateCookieDomain","appUrl","url","URL","hostname","replace","InvalidFronteggEnv","EnvVariables","FRONTEGG_APP_URL","normalizeStringPasswordToMap","password","generateAppUrl","appUrlEnv","undefined","isVercel","VERCEL","vercelUrl","VERCEL_URL","startsWith","protocol"],"sources":["../../../../packages/nextjs/src/config/helpers.ts"],"sourcesContent":["import { InvalidFronteggEnv, FronteggEnvNotFound } from '../utils/errors';\nimport { PasswordsMap } from './types';\nimport { EnvVariables } from './constants';\n\n/**\n * Return environment variable's value.\n * @throws {@link FronteggEnvNotFound} if not exists\n * @param name\n */\nexport const getEnv = (name: string): string => {\n const value = process.env[name];\n if (!value) {\n throw new FronteggEnvNotFound(name);\n }\n return value;\n};\n\n/**\n * Return environment variable's value with default if not exists\n * @param {string} name - the name from environment variable {@link EnvVariables}\n * @param {optional string} defaultValue - default value if not exists\n */\nexport const getEnvOrDefault = <T>(name: string, defaultValue: T): string | T => {\n try {\n return getEnv(name);\n } catch (e) {\n return defaultValue;\n }\n};\n\n/**\n * extract hostname from appUrl for session cookie creation\n * @param {string} appUrl - The generated appUrl\n */\nexport const generateCookieDomain = (appUrl: string): string => {\n try {\n const url = new URL(appUrl);\n return url.hostname.replace(/:(\\d)+$/, '');\n } catch (e) {\n throw new InvalidFronteggEnv(EnvVariables.FRONTEGG_APP_URL, 'Valid URL');\n }\n};\n\n/**\n * Create passwordMap if from {@link EnvVariables.FRONTEGG_ENCRYPTION_PASSWORD}\n * @param {string} password - encryption password\n */\nexport function normalizeStringPasswordToMap(password: string | PasswordsMap): PasswordsMap {\n return typeof password === 'string' ? { 1: password } : password;\n}\n\n/**\n * Check if the Next.js application running on Vercel Deployment Service\n * and calculate the appUrl based on Vercel Environment variables.\n */\nexport function generateAppUrl() {\n const appUrlEnv = getEnvOrDefault(EnvVariables.FRONTEGG_APP_URL, undefined);\n const isVercel = getEnvOrDefault(EnvVariables.VERCEL, undefined) != undefined;\n const vercelUrl = getEnvOrDefault(EnvVariables.VERCEL_URL, undefined);\n\n let appUrl: string | undefined;\n if (appUrlEnv) {\n appUrl = appUrlEnv;\n } else if (isVercel && vercelUrl) {\n appUrl = vercelUrl;\n }\n\n if (!appUrl) {\n if (isVercel) {\n throw new FronteggEnvNotFound(EnvVariables.VERCEL, EnvVariables.VERCEL_URL);\n } else {\n throw new FronteggEnvNotFound(EnvVariables.FRONTEGG_APP_URL);\n }\n }\n\n /**\n * In some cases the {@link EnvVariables.VERCEL_URL} value does not\n * include the URL protocol, bellow code to verify that the appUrl\n * must have a valid http protocol\n */\n if (!appUrl.startsWith('http')) {\n // noinspection HttpUrlsUsage\n const protocol = appUrl.startsWith('localhost') ? 'http://' : 'https://';\n appUrl = `${protocol}${appUrl}`;\n }\n\n return appUrl;\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,UAAA,GAAAD,OAAA;AAEA;AACA;AACA;AACA;AACA;AACO,MAAME,MAAM,GAAIC,IAAY,IAAa;EAC9C,MAAMC,KAAK,GAAGC,OAAO,CAACC,GAAG,CAACH,IAAI,CAAC;EAC/B,IAAI,CAACC,KAAK,EAAE;IACV,MAAM,IAAIG,2BAAmB,CAACJ,IAAI,CAAC;EACrC;EACA,OAAOC,KAAK;AACd,CAAC;;AAED;AACA;AACA;AACA;AACA;AAJAI,OAAA,CAAAN,MAAA,GAAAA,MAAA;AAKO,MAAMO,eAAe,GAAGA,CAAIN,IAAY,EAAEO,YAAe,KAAiB;EAC/E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B,2BAAmB,CAACY,uBAAY,CAACQ,MAAM,EAAER,uBAAY,CAACU,UAAU,CAAC;IAC7E,CAAC,MAAM;MACL,MAAM,IAAItB,2BAAmB,CAACY,uBAAY,CAACC,gBAAgB,CAAC;IAC9D;EACF;;EAEA;AACF;AACA;AACA;AACA;EACE,IAAI,CAACP,MAAM,CAACiB,UAAU,CAAC,MAAM,CAAC,EAAE;IAC9B;IACA,MAAMC,QAAQ,GAAGlB,MAAM,CAACiB,UAAU,CAAC,WAAW,CAAC,GAAG,SAAS,GAAG,UAAU;IACxEjB,MAAM,GAAI,GAAEkB,QAAS,GAAElB,MAAO,EAAC;EACjC;EAEA,OAAOA,MAAM;AACf"}
1
+ {"version":3,"file":"helpers.js","names":["_errors","require","_constants","getEnv","name","value","process","env","FronteggEnvNotFound","exports","getEnvOrDefault","defaultValue","e","generateCookieDomain","appUrl","url","URL","hostname","replace","InvalidFronteggEnv","EnvVariables","FRONTEGG_APP_URL","normalizeStringPasswordToMap","password","generateAppUrl","appUrlEnv","undefined","isVercel","VERCEL","vercelUrl","VERCEL_URL","global","customLoginAppUrl","startsWith","protocol"],"sources":["../../../../packages/nextjs/src/config/helpers.ts"],"sourcesContent":["import { InvalidFronteggEnv, FronteggEnvNotFound } from '../utils/errors';\nimport { PasswordsMap } from './types';\nimport { EnvVariables } from './constants';\n\n/**\n * Return environment variable's value.\n * @throws {@link FronteggEnvNotFound} if not exists\n * @param name\n */\nexport const getEnv = (name: string): string => {\n const value = process.env[name];\n if (!value) {\n throw new FronteggEnvNotFound(name);\n }\n return value;\n};\n\n/**\n * Return environment variable's value with default if not exists\n * @param {string} name - the name from environment variable {@link EnvVariables}\n * @param {optional string} defaultValue - default value if not exists\n */\nexport const getEnvOrDefault = <T>(name: string, defaultValue: T): string | T => {\n try {\n return getEnv(name);\n } catch (e) {\n return defaultValue;\n }\n};\n\n/**\n * extract hostname from appUrl for session cookie creation\n * @param {string} appUrl - The generated appUrl\n */\nexport const generateCookieDomain = (appUrl: string): string => {\n try {\n const url = new URL(appUrl);\n return url.hostname.replace(/:(\\d)+$/, '');\n } catch (e) {\n throw new InvalidFronteggEnv(EnvVariables.FRONTEGG_APP_URL, 'Valid URL');\n }\n};\n\n/**\n * Create passwordMap if from {@link EnvVariables.FRONTEGG_ENCRYPTION_PASSWORD}\n * @param {string} password - encryption password\n */\nexport function normalizeStringPasswordToMap(password: string | PasswordsMap): PasswordsMap {\n return typeof password === 'string' ? { 1: password } : password;\n}\n\n/**\n * Check if the Next.js application running on Vercel Deployment Service\n * and calculate the appUrl based on Vercel Environment variables.\n */\nexport function generateAppUrl() {\n const appUrlEnv = getEnvOrDefault(EnvVariables.FRONTEGG_APP_URL, undefined);\n const isVercel = getEnvOrDefault(EnvVariables.VERCEL, undefined) != undefined;\n const vercelUrl = getEnvOrDefault(EnvVariables.VERCEL_URL, undefined);\n\n let appUrl: string | undefined;\n if (appUrlEnv) {\n appUrl = appUrlEnv;\n } else if (isVercel && vercelUrl) {\n appUrl = vercelUrl;\n }\n\n if (!appUrl) {\n if (isVercel) {\n throw new FronteggEnvNotFound(EnvVariables.VERCEL, EnvVariables.VERCEL_URL);\n } else {\n throw new FronteggEnvNotFound(EnvVariables.FRONTEGG_APP_URL);\n }\n }\n\n if (global.customLoginAppUrl) {\n appUrl = global.customLoginAppUrl;\n }\n\n /**\n * In some cases the {@link EnvVariables.VERCEL_URL} value does not\n * include the URL protocol, bellow code to verify that the appUrl\n * must have a valid http protocol\n */\n if (!appUrl.startsWith('http')) {\n // noinspection HttpUrlsUsage\n const protocol = appUrl.startsWith('localhost') ? 'http://' : 'https://';\n appUrl = `${protocol}${appUrl}`;\n }\n\n return appUrl;\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,UAAA,GAAAD,OAAA;AAEA;AACA;AACA;AACA;AACA;AACO,MAAME,MAAM,GAAIC,IAAY,IAAa;EAC9C,MAAMC,KAAK,GAAGC,OAAO,CAACC,GAAG,CAAC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,UAAU,EAAEJ,SAAS,CAAC;EAErE,IAAIZ,MAA0B;EAC9B,IAAIW,SAAS,EAAE;IACbX,MAAM,GAAGW,SAAS;EACpB,CAAC,MAAM,IAAIE,QAAQ,IAAIE,SAAS,EAAE;IAChCf,MAAM,GAAGe,SAAS;EACpB;EAEA,IAAI,CAACf,MAAM,EAAE;IACX,IAAIa,QAAQ,EAAE;MACZ,MAAM,IAAInB,2BAAmB,CAACY,uBAAY,CAACQ,MAAM,EAAER,uBAAY,CAACU,UAAU,CAAC;IAC7E,CAAC,MAAM;MACL,MAAM,IAAItB,2BAAmB,CAACY,uBAAY,CAACC,gBAAgB,CAAC;IAC9D;EACF;EAEA,IAAIU,MAAM,CAACC,iBAAiB,EAAE;IAC5BlB,MAAM,GAAGiB,MAAM,CAACC,iBAAiB;EACnC;;EAEA;AACF;AACA;AACA;AACA;EACE,IAAI,CAAClB,MAAM,CAACmB,UAAU,CAAC,MAAM,CAAC,EAAE;IAC9B;IACA,MAAMC,QAAQ,GAAGpB,MAAM,CAACmB,UAAU,CAAC,WAAW,CAAC,GAAG,SAAS,GAAG,UAAU;IACxEnB,MAAM,GAAI,GAAEoB,QAAS,GAAEpB,MAAO,EAAC;EACjC;EAEA,OAAOA,MAAM;AACf"}
@@ -1 +1 @@
1
- {"version":3,"file":"shouldBypassMiddleware.js","names":["_initialState","require","_excluded","staticFilesRegex","RegExp","imageOptimizationRegex","headerRequestsRegex","fronteggMiddlewareRegex","shouldByPassMiddleware","pathname","options","_options","_extends2","default","bypassStaticFiles","bypassImageOptimization","bypassHeaderRequests","bypassFronteggMiddleware","bypassFronteggRoutes","bypassAuthSamlCallback","isStaticFiles","test","isImageOptimization","isHeaderRequests","isFronteggMiddleware","_authInitialState$rou","authInitialState","routes","authRoutes","_objectWithoutPropertiesLoose2","isFronteggRoutes","Object","values","find","path","startsWith","exports"],"sources":["../../../../packages/nextjs/src/edge/shouldBypassMiddleware.ts"],"sourcesContent":["import config from '../config';\nimport { initialState as authInitialState } from '@frontegg/redux-store/auth/initialState';\n\nconst staticFilesRegex = new RegExp('^/(_next/static).*');\nconst imageOptimizationRegex = new RegExp('^/(_next/image).*');\nconst headerRequestsRegex = new RegExp('^/(favicon.ico).*');\nconst fronteggMiddlewareRegex = new RegExp('^/(api/frontegg).*');\n\ninterface ByPassOptions {\n bypassStaticFiles?: boolean; // default: true\n bypassImageOptimization?: boolean; // default: true\n bypassHeaderRequests?: boolean; // default: true\n}\n\n/**\n * Use `shouldByPassMiddleware` in the middleware.ts file\n * to protect all application's routes.\n * You can override whitelist by passing options parameter\n * NOTE: this will slow down your application due to session check on each\n * static files and image request\n *\n * The default whitelist:\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - favicon.ico (favicon file)\n * - api/frontegg (API frontegg middleware)\n * - account/[login|logout|saml/callback|...] (frontegg authentication routes)\n */\nexport const shouldByPassMiddleware = (pathname: string, options?: ByPassOptions): boolean => {\n const _options = {\n bypassStaticFiles: true,\n bypassImageOptimization: true,\n bypassHeaderRequests: true,\n ...options,\n bypassFronteggMiddleware: true,\n bypassFronteggRoutes: true,\n bypassAuthSamlCallback: true,\n };\n\n const isStaticFiles = staticFilesRegex.test(pathname);\n const isImageOptimization = imageOptimizationRegex.test(pathname);\n const isHeaderRequests = headerRequestsRegex.test(pathname);\n const isFronteggMiddleware = fronteggMiddlewareRegex.test(pathname);\n\n const { authenticatedUrl, ...authRoutes } = authInitialState.routes;\n const isFronteggRoutes = Object.values(authRoutes).find((path) => pathname.startsWith(path)) != null;\n\n if (isStaticFiles) return _options.bypassStaticFiles;\n if (isImageOptimization) return _options.bypassImageOptimization;\n if (isHeaderRequests) return _options.bypassHeaderRequests;\n if (isFronteggMiddleware) return _options.bypassFronteggMiddleware;\n if (isFronteggRoutes) return _options.bypassFronteggRoutes;\n\n return false;\n};\n"],"mappings":";;;;;;;;;AACA,IAAAA,aAAA,GAAAC,OAAA;AAA2F,MAAAC,SAAA;AAE3F,MAAMC,gBAAgB,GAAG,IAAIC,M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,QAAQ,CAACI,uBAAuB;EAChE,IAAIQ,gBAAgB,EAAE,OAAOZ,QAAQ,CAACK,oBAAoB;EAC1D,IAAIQ,oBAAoB,EAAE,OAAOb,QAAQ,CAACM,wBAAwB;EAClE,IAAIa,gBAAgB,EAAE,OAAOnB,QAAQ,CAACO,oBAAoB;EAE1D,OAAO,KAAK;AACd,CAAC;AAACkB,OAAA,CAAA5B,sBAAA,GAAAA,sBAAA"}
1
+ {"version":3,"file":"shouldBypassMiddleware.js","names":["_initialState","require","_excluded","staticFilesRegex","RegExp","imageOptimizationRegex","headerRequestsRegex","fronteggMiddlewareRegex","shouldByPassMiddleware","pathname","options","_options","_extends2","default","bypassStaticFiles","bypassImageOptimization","bypassHeaderRequests","bypassFronteggMiddleware","bypassFronteggRoutes","bypassAuthSamlCallback","isStaticFiles","test","isImageOptimization","isHeaderRequests","isFronteggMiddleware","_authInitialState$rou","authInitialState","routes","authRoutes","_objectWithoutPropertiesLoose2","isFronteggRoutes","Object","values","find","path","startsWith","exports"],"sources":["../../../../packages/nextjs/src/edge/shouldBypassMiddleware.ts"],"sourcesContent":["import { initialState as authInitialState } from '@frontegg/redux-store/auth/initialState';\n\nconst staticFilesRegex = new RegExp('^/(_next/static).*');\nconst imageOptimizationRegex = new RegExp('^/(_next/image).*');\nconst headerRequestsRegex = new RegExp('^/(favicon.ico).*');\nconst fronteggMiddlewareRegex = new RegExp('^/(api/frontegg).*');\n\ninterface ByPassOptions {\n bypassStaticFiles?: boolean; // default: true\n bypassImageOptimization?: boolean; // default: true\n bypassHeaderRequests?: boolean; // default: true\n}\n\n/**\n * Use `shouldByPassMiddleware` in the middleware.ts file\n * to protect all application's routes.\n * You can override whitelist by passing options parameter\n * NOTE: this will slow down your application due to session check on each\n * static files and image request\n *\n * The default whitelist:\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - favicon.ico (favicon file)\n * - api/frontegg (API frontegg middleware)\n * - account/[login|logout|saml/callback|...] (frontegg authentication routes)\n */\nexport const shouldByPassMiddleware = (pathname: string, options?: ByPassOptions): boolean => {\n const _options = {\n bypassStaticFiles: true,\n bypassImageOptimization: true,\n bypassHeaderRequests: true,\n ...options,\n bypassFronteggMiddleware: true,\n bypassFronteggRoutes: true,\n bypassAuthSamlCallback: true,\n };\n\n const isStaticFiles = staticFilesRegex.test(pathname);\n const isImageOptimization = imageOptimizationRegex.test(pathname);\n const isHeaderRequests = headerRequestsRegex.test(pathname);\n const isFronteggMiddleware = fronteggMiddlewareRegex.test(pathname);\n\n const { authenticatedUrl, ...authRoutes } = authInitialState.routes;\n const isFronteggRoutes = Object.values(authRoutes).find((path) => pathname.startsWith(path)) != null;\n\n if (isStaticFiles) return _options.bypassStaticFiles;\n if (isImageOptimization) return _options.bypassImageOptimization;\n if (isHeaderRequests) return _options.bypassHeaderRequests;\n if (isFronteggMiddleware) return _options.bypassFronteggMiddleware;\n if (isFronteggRoutes) return _options.bypassFronteggRoutes;\n\n return false;\n};\n"],"mappings":";;;;;;;;;AAAA,IAAAA,aAAA,GAAAC,OAAA;AAA2F,MAAAC,SAAA;AAE3F,MAAMC,gBAAgB,GAAG,IAAIC,MAAM,CAAC,oBAAoB,CAAC;AACzD,MAAMC,sBAAsB,GAAG,IAAID,MAAM,CAAC,mBAAmB,CAAC;AAC9D,MAAME,mBAAmB,GAAG,IAAIF,MAAM,CAAC,mBAAmB,CAAC;AAC3D,MAAMG,uBAAuB,GAAG,IAAIH,MAAM,CAAC,oBAAoB,CAAC;AAQhE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMI,sBAAsB,GAAGA,CAACC,QAAgB,EAAEC,OAAuB,KAAc;EAC5F,MAAMC,QAAQ,OAAAC,SAAA,CAAAC,OAAA;IACZC,iBAAiB,EAAE,IAAI;IACvBC,uBAAuB,EAAE,IAAI;IAC7BC,oBAAoB,EAAE;EAAI,GACvBN,OAAO;IACVO,wBAAwB,EAAE,IAAI;IAC9BC,oBAAoB,EAAE,IAAI;IAC1BC,sBAAsB,EAAE;EAAI,EAC7B;EAED,MAAMC,aAAa,GAAGjB,gBAAgB,CAACkB,IAAI,CAACZ,QAAQ,CAAC;EACrD,MAAMa,mBAAmB,GAAGjB,sBAAsB,CAACgB,IAAI,CAACZ,QAAQ,CAAC;EACjE,MAAMc,gBAAgB,GAAGjB,mBAAmB,CAACe,IAAI,CAACZ,QAAQ,CAAC;EAC3D,MAAMe,oBAAoB,GAAGjB,uBAAuB,CAACc,IAAI,CAACZ,QAAQ,CAAC;EAEnE,MAAAgB,qBAAA,GAA4CC,0BAAgB,CAACC,MAAM;IAAtCC,UAAU,OAAAC,8BAAA,CAAAhB,OAAA,EAAAY,qBAAA,EAAAvB,SAAA;EACvC,MAAM4B,gBAAgB,GAAGC,MAAM,CAACC,MAAM,CAACJ,UAAU,CAAC,CAACK,IAAI,CAAEC,IAAI,IAAKzB,QAAQ,CAAC0B,UAAU,CAACD,IAAI,CAAC,CAAC,IAAI,IAAI;EAEpG,IAAId,aAAa,EAAE,OAAOT,QAAQ,CAACG,iBAAiB;EACpD,IAAIQ,mBAAmB,EAAE,OAAOX,QAAQ,CAACI,uBAAuB;EAChE,IAAIQ,gBAAgB,EAAE,OAAOZ,QAAQ,CAACK,oBAAoB;EAC1D,IAAIQ,oBAAoB,EAAE,OAAOb,QAAQ,CAACM,wBAAwB;EAClE,IAAIa,gBAAgB,EAAE,OAAOnB,QAAQ,CAACO,oBAAoB;EAE1D,OAAO,KAAK;AACd,CAAC;AAACkB,OAAA,CAAA5B,sBAAA,GAAAA,sBAAA"}
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- /** @license Frontegg v7.0.16
1
+ /** @license Frontegg v7.0.17-alpha.5712339467
2
2
  *
3
3
  * This source code is licensed under the MIT license found in the
4
4
  * LICENSE file in the root directory of this source tree.
@@ -1 +1 @@
1
- {"version":3,"file":"ProxyResponseCallback.js","names":["_config","_interopRequireDefault","require","_cookies","_common","_helpers","_fronteggLogger","_helpers2","logger","fronteggLogger","child","tag","ProxyResponseCallback","proxyRes","req","res","buffer","Buffer","totalLength","isSecured","URL","config","appUrl","protocol","on","chunk","length","concat","_proxyRes$statusCode","url","statusCode","isSuccess","bodyStr","toString","isLogout","isFronteggLogoutUrl","CookieManager","removeCookies","cookieDomain","status","end","_CookieManager$modify","cookies","modifySetCookie","headers","body","JSON","parse","accessToken","access_token","session","decodedJwt","createSessionFromAccessToken","sessionCookie","create","value","expires","Date","exp","secure","push","e","isSSOPostRequest","error","Object","keys","filter","header","forEach","setHeader","_default","exports","default"],"sources":["../../../../packages/nextjs/src/middleware/ProxyResponseCallback.ts"],"sourcesContent":["import { ProxyResCallback } from 'http-proxy';\nimport { IncomingMessage } from 'http';\nimport { NextApiResponse, NextApiRequest } from 'next';\nimport config from '../config';\nimport CookieManager from '../utils/cookies';\nimport { createSessionFromAccessToken } from '../common';\nimport { isFronteggLogoutUrl } from './helpers';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport { isSSOPostRequest } from '../utils/refreshAccessToken/helpers';\n\nconst logger = fronteggLogger.child({ tag: 'FronteggApiMiddleware.ProxyResponseCallback' });\n/**\n * Proxy response callback fired on after each response from Frontegg services,\n * to transport frontegg modify cookies and generating encrypted JWT session cookie.\n *\n * @param {IncomingMessage} proxyRes - Proxy response from Frontegg services\n * @param {NextApiRequest} req - Next.js request sent from client-side\n * @param {NextApiResponse} res - Next.js response to send to client-side\n */\nconst ProxyResponseCallback: ProxyResCallback<IncomingMessage, NextApiResponse> = (proxyRes, req, res) => {\n let buffer = new Buffer('');\n let totalLength: number = 0;\n const isSecured = new URL(config.appUrl).protocol === 'https:';\n\n proxyRes.on('data', (chunk: Buffer) => {\n totalLength += chunk.length;\n buffer = Buffer.concat([buffer, chunk], totalLength);\n });\n proxyRes.on('end', async () => {\n try {\n const url = req.url!;\n const statusCode = proxyRes.statusCode ?? 500;\n const isSuccess = statusCode >= 200 && statusCode < 400;\n const bodyStr = buffer.toString('utf-8');\n const isLogout = isFronteggLogoutUrl(url);\n\n if (isLogout) {\n CookieManager.removeCookies({\n isSecured,\n cookieDomain: config.cookieDomain,\n res,\n req,\n });\n res.status(statusCode).end(bodyStr);\n return;\n }\n\n if (isSuccess) {\n const cookies = CookieManager.modifySetCookie(proxyRes.headers['set-cookie'], isSecured) ?? [];\n\n try {\n if (bodyStr && bodyStr.length > 0) {\n const body = JSON.parse(bodyStr);\n if (body.accessToken || body.access_token) {\n const [session, decodedJwt] = await createSessionFromAccessToken(body);\n if (session) {\n const sessionCookie = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n cookies.push(...sessionCookie);\n }\n }\n }\n } catch (e) {\n /** ignore api call if:\n * - Does not have accessToken / access_token\n * - Not json response\n */\n if (statusCode === 302 && isSSOPostRequest(url)) {\n /**\n * Ignore saml/oidc postLogin response with redirect\n */\n } else {\n logger.error('failed to create session', e, {\n url,\n statusCode,\n });\n }\n }\n Object.keys(proxyRes.headers)\n .filter((header) => header !== 'cookie')\n .forEach((header) => {\n res.setHeader(header, `${proxyRes.headers[header]}`);\n });\n res.setHeader('set-cookie', cookies);\n res.status(statusCode).end(bodyStr);\n } else {\n if (statusCode >= 400 && statusCode !== 404) {\n logger.error(`Middleware request failed statusCode: ${statusCode} for url: ${url}`);\n }\n Object.keys(proxyRes.headers)\n .filter((header) => header !== 'cookie')\n .forEach((header) => {\n res.setHeader(header, `${proxyRes.headers[header]}`);\n });\n res.status(statusCode).end(bodyStr);\n }\n } catch (e: any) {\n logger.error('proxy failed to send request', e);\n res.status(500).end('Internal Server Error');\n }\n });\n};\n\nexport default ProxyResponseCallback;\n"],"mappings":";;;;;;;AAGA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,QAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAL,sBAAA,CAAAC,OAA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,CACvCC,OAAO,CAAED,MAAM,IAAK;UACnBpD,GAAG,CAACsD,SAAS,CAACF,MAAM,EAAG,GAAEtD,QAAQ,CAAC+B,OAAO,CAACuB,MAAM,CAAE,EAAC,CAAC;QACtD,CAAC,CAAC;QACJpD,GAAG,CAACsD,SAAS,CAAC,YAAY,EAAE3B,OAAO,CAAC;QACpC3B,GAAG,CAACwB,MAAM,CAACT,UAAU,CAAC,CAACU,GAAG,CAACR,OAAO,CAAC;MACrC,CAAC,MAAM;QACL,IAAIF,UAAU,IAAI,GAAG,IAAIA,UAAU,KAAK,GAAG,EAAE;UAC3CtB,MAAM,CAACuD,KAAK,CAAE,yCAAwCjC,UAAW,aAAYD,GAAI,EAAC,CAAC;QACrF;QACAmC,MAAM,CAACC,IAAI,CAACpD,QAAQ,CAAC+B,OAAO,CAAC,CAC1BsB,MAAM,CAAEC,MAAM,IAAKA,MAAM,KAAK,QAAQ,CAAC,CACvCC,OAAO,CAAED,MAAM,IAAK;UACnBpD,GAAG,CAACsD,SAAS,CAACF,MAAM,EAAG,GAAEtD,QAAQ,CAAC+B,OAAO,CAACuB,MAAM,CAAE,EAAC,CAAC;QACtD,CAAC,CAAC;QACJpD,GAAG,CAACwB,MAAM,CAACT,UAAU,CAAC,CAACU,GAAG,CAACR,OAAO,CAAC;MACrC;IACF,CAAC,CAAC,OAAO6B,CAAM,EAAE;MACfrD,MAAM,CAACuD,KAAK,CAAC,8BAA8B,EAAEF,CAAC,CAAC;MAC/C9C,GAAG,CAACwB,MAAM,CAAC,GAAG,CAAC,CAACC,GAAG,CAAC,uBAAuB,CAAC;IAC9C;EACF,CAAC,CAAC;AACJ,CAAC;AAAC,IAAA8B,QAAA,GAEa1D,qBAAqB;AAAA2D,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
1
+ {"version":3,"file":"ProxyResponseCallback.js","names":["_config","_interopRequireDefault","require","_cookies","_common","_helpers","_fronteggLogger","_helpers2","logger","fronteggLogger","child","tag","ProxyResponseCallback","proxyRes","req","res","buffer","Buffer","totalLength","isSecured","URL","config","appUrl","protocol","on","chunk","length","concat","_proxyRes$statusCode","url","statusCode","isSuccess","bodyStr","toString","isLogout","isFronteggLogoutUrl","CookieManager","removeCookies","cookieDomain","status","end","_CookieManager$modify","cookies","modifySetCookie","headers","body","JSON","parse","accessToken","access_token","session","decodedJwt","createSessionFromAccessToken","sessionCookie","create","value","expires","Date","exp","secure","push","e","isSSOPostRequest","error","Object","keys","filter","header","forEach","setHeader","_default","exports","default"],"sources":["../../../../packages/nextjs/src/middleware/ProxyResponseCallback.ts"],"sourcesContent":["import { ProxyResCallback } from 'http-proxy';\nimport { IncomingMessage } from 'http';\nimport { NextApiResponse } from 'next';\nimport config from '../config';\nimport CookieManager from '../utils/cookies';\nimport { createSessionFromAccessToken } from '../common';\nimport { isFronteggLogoutUrl } from './helpers';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport { isSSOPostRequest } from '../utils/refreshAccessToken/helpers';\n\nconst logger = fronteggLogger.child({ tag: 'FronteggApiMiddleware.ProxyResponseCallback' });\n/**\n * Proxy response callback fired on after each response from Frontegg services,\n * to transport frontegg modify cookies and generating encrypted JWT session cookie.\n *\n * @param {IncomingMessage} proxyRes - Proxy response from Frontegg services\n * @param {NextApiRequest} req - Next.js request sent from client-side\n * @param {NextApiResponse} res - Next.js response to send to client-side\n */\nconst ProxyResponseCallback: ProxyResCallback<IncomingMessage, NextApiResponse> = (proxyRes, req, res) => {\n let buffer = new Buffer('');\n let totalLength: number = 0;\n const isSecured = new URL(config.appUrl).protocol === 'https:';\n\n proxyRes.on('data', (chunk: Buffer) => {\n totalLength += chunk.length;\n buffer = Buffer.concat([buffer, chunk], totalLength);\n });\n proxyRes.on('end', async () => {\n try {\n const url = req.url!;\n const statusCode = proxyRes.statusCode ?? 500;\n const isSuccess = statusCode >= 200 && statusCode < 400;\n const bodyStr = buffer.toString('utf-8');\n const isLogout = isFronteggLogoutUrl(url);\n\n if (isLogout) {\n CookieManager.removeCookies({\n isSecured,\n cookieDomain: config.cookieDomain,\n res,\n req,\n });\n res.status(statusCode).end(bodyStr);\n return;\n }\n\n if (isSuccess) {\n const cookies = CookieManager.modifySetCookie(proxyRes.headers['set-cookie'], isSecured) ?? [];\n\n try {\n if (bodyStr && bodyStr.length > 0) {\n const body = JSON.parse(bodyStr);\n if (body.accessToken || body.access_token) {\n const [session, decodedJwt] = await createSessionFromAccessToken(body);\n if (session) {\n const sessionCookie = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n cookies.push(...sessionCookie);\n }\n }\n }\n } catch (e) {\n /** ignore api call if:\n * - Does not have accessToken / access_token\n * - Not json response\n */\n if (statusCode === 302 && isSSOPostRequest(url)) {\n /**\n * Ignore saml/oidc postLogin response with redirect\n */\n } else {\n logger.error('failed to create session', e, {\n url,\n statusCode,\n });\n }\n }\n Object.keys(proxyRes.headers)\n .filter((header) => header !== 'cookie')\n .forEach((header) => {\n res.setHeader(header, `${proxyRes.headers[header]}`);\n });\n res.setHeader('set-cookie', cookies);\n res.status(statusCode).end(bodyStr);\n } else {\n if (statusCode >= 400 && statusCode !== 404) {\n logger.error(`Middleware request failed statusCode: ${statusCode} for url: ${url}`);\n }\n Object.keys(proxyRes.headers)\n .filter((header) => header !== 'cookie')\n .forEach((header) => {\n res.setHeader(header, `${proxyRes.headers[header]}`);\n });\n res.status(statusCode).end(bodyStr);\n }\n } catch (e: any) {\n logger.error('proxy failed to send request', e);\n res.status(500).end('Internal Server Error');\n }\n });\n};\n\nexport default ProxyResponseCallback;\n"],"mappings":";;;;;;;AAGA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,QAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAL,sBAAA,CAAAC,OAAA;AACA,IAAAK,SAAA,GAAAL,OAAA;AAEA,MAAMM,M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AACsD,SAAS,CAACF,MAAM,EAAG,GAAEtD,QAAQ,CAAC+B,OAAO,CAACuB,MAAM,CAAE,EAAC,CAAC;QACtD,CAAC,CAAC;QACJpD,GAAG,CAACsD,SAAS,CAAC,YAAY,EAAE3B,OAAO,CAAC;QACpC3B,GAAG,CAACwB,MAAM,CAACT,UAAU,CAAC,CAACU,GAAG,CAACR,OAAO,CAAC;MACrC,CAAC,MAAM;QACL,IAAIF,UAAU,IAAI,GAAG,IAAIA,UAAU,KAAK,GAAG,EAAE;UAC3CtB,MAAM,CAACuD,KAAK,CAAE,yCAAwCjC,UAAW,aAAYD,GAAI,EAAC,CAAC;QACrF;QACAmC,MAAM,CAACC,IAAI,CAACpD,QAAQ,CAAC+B,OAAO,CAAC,CAC1BsB,MAAM,CAAEC,MAAM,IAAKA,MAAM,KAAK,QAAQ,CAAC,CACvCC,OAAO,CAAED,MAAM,IAAK;UACnBpD,GAAG,CAACsD,SAAS,CAACF,MAAM,EAAG,GAAEtD,QAAQ,CAAC+B,OAAO,CAACuB,MAAM,CAAE,EAAC,CAAC;QACtD,CAAC,CAAC;QACJpD,GAAG,CAACwB,MAAM,CAACT,UAAU,CAAC,CAACU,GAAG,CAACR,OAAO,CAAC;MACrC;IACF,CAAC,CAAC,OAAO6B,CAAM,EAAE;MACfrD,MAAM,CAACuD,KAAK,CAAC,8BAA8B,EAAEF,CAAC,CAAC;MAC/C9C,GAAG,CAACwB,MAAM,CAAC,GAAG,CAAC,CAACC,GAAG,CAAC,uBAAuB,CAAC;IAC9C;EACF,CAAC,CAAC;AACJ,CAAC;AAAC,IAAA8B,QAAA,GAEa1D,qBAAqB;AAAA2D,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@frontegg/nextjs",
3
3
  "libName": "FronteggNextJs",
4
- "version": "7.0.16",
4
+ "version": "7.0.17-alpha.5712339467",
5
5
  "author": "Frontegg LTD",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -27,8 +27,8 @@
27
27
  "lint-json": "eslint -c .eslintrc.json -o ./lint-report.json --format json --no-color ./src/**/*.{ts,tsx}"
28
28
  },
29
29
  "dependencies": {
30
- "@frontegg/js": "6.124.0",
31
- "@frontegg/react-hooks": "6.124.0",
30
+ "@frontegg/js": "6.126.0",
31
+ "@frontegg/react-hooks": "6.126.0",
32
32
  "http-proxy": "^1.18.1",
33
33
  "iron-session": "^6.3.1",
34
34
  "jose": "^4.12.2"
package/sdkVersion.js CHANGED
@@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _default = {
8
- version: '7.0.16'
8
+ version: '7.0.17-alpha.5712339467'
9
9
  };
10
10
  exports.default = _default;
11
11
  //# sourceMappingURL=sdkVersion.js.map
package/sdkVersion.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdkVersion.js","names":["version","exports","default","_default"],"sources":["../../../packages/nextjs/src/sdkVersion.ts"],"sourcesContent":["export default { version: '7.0.16' };\n"],"mappings":";;;;;;eAAe;EAAEA,OAAO,EAAE;AAAS,CAAC;AAAAC,OAAA,CAAAC,OAAA,GAAAC,QAAA"}
1
+ {"version":3,"file":"sdkVersion.js","names":["version","exports","default","_default"],"sources":["../../../packages/nextjs/src/sdkVersion.ts"],"sourcesContent":["export default { version: '7.0.17-alpha.5712339467' };\n"],"mappings":";;;;;;eAAe;EAAEA,OAAO,EAAE;AAA0B,CAAC;AAAAC,OAAA,CAAAC,OAAA,GAAAC,QAAA"}
package/types/index.d.ts CHANGED
@@ -92,6 +92,7 @@ declare module 'iron-session' {
92
92
  }
93
93
  }
94
94
  declare global {
95
+ var customLoginAppUrl: string | undefined;
95
96
  interface ProcessEnv {
96
97
  FRONTEGG_BASE_URL: string;
97
98
  PORT?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../packages/nextjs/src/types/index.ts"],"sourcesContent":["import type { FronteggAppOptions } from '@frontegg/types';\nimport type { ILoginResponse, ITenantsResponse } from '@frontegg/rest-api';\nimport type { IncomingMessage } from 'http';\nimport type { ReactNode } from 'react';\nimport type { AppRouterInstance } from 'next/dist/shared/lib/app-router-context';\nimport type { NextRouter } from 'next/router';\n\nexport interface EncryptionUtils {\n unsealTokens(data: string): Promise<FronteggUserTokens | undefined>;\n\n sealTokens(tokens: FronteggUserTokens, ttl: number): Promise<string>;\n}\n\nexport interface FronteggUserTokens {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface FronteggNextJSSession extends FronteggUserTokens {\n user: FronteggUserSession;\n}\n\nexport type RequestType = IncomingMessage | Request;\n\nexport interface AccountEnvironment {\n id: string;\n createdAt: string;\n environment: 'production' | 'development';\n}\n\nexport interface CustomClaims {\n accountEnvironments: AccountEnvironment[];\n}\n\nexport interface FronteggUserTokens {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface AllUserData {\n user?: ILoginResponse | null;\n tenants?: ITenantsResponse[] | null;\n activeTenant?: ITenantsResponse;\n session?: FronteggNextJSSession | null;\n}\nexport interface FronteggUserSession {\n sub: string;\n name: string;\n email: string;\n email_verified: boolean;\n metadata: any;\n roles: string[];\n permissions: string[];\n tenantId: string;\n tenantIds: string[];\n profilePictureUrl: string;\n type: string; // \"userToken\"\n customClaims: CustomClaims;\n iat: number;\n exp: number;\n aud: string;\n iss: string;\n}\n\nexport interface FronteggNextJSSession extends FronteggUserTokens {\n user: FronteggUserSession;\n}\n\nexport interface FronteggProviderOptions extends Omit<FronteggAppOptions, 'contextOptions'>, AllUserData {\n envAppUrl: string;\n envBaseUrl: string;\n envClientId: string;\n contextOptions?: Omit<FronteggAppOptions['contextOptions'], 'baseUrl'>;\n}\n\nexport interface FronteggProviderProps extends FronteggProviderOptions {\n children?: ReactNode;\n router: AppRouterInstance | NextRouter;\n appName?: string;\n}\n\ntype CustomLoginOptionsWithParamKeyType = {\n /**\n *The param key from your tenant login url, for 'frontegg.com?organization=[tenant]' would be 'organization'\n */\n paramKey: string;\n subDomainIndex?: never;\n};\n\ntype CustomLoginOptionsWithSubDomainType = {\n /**\n *The index of sub domain from your tenant login url, for 'https://[tenant].frontegg.com' would be 0\n */\n subDomainIndex: number;\n paramKey?: never;\n};\n\nexport type CustomLoginOptionsType = CustomLoginOptionsWithParamKeyType | CustomLoginOptionsWithSubDomainType;\n\ntype PagesDirectoryProviderProps = {\n customLoginOptions?: CustomLoginOptionsType;\n};\n\nexport type ClientFronteggProviderProps = Omit<FronteggProviderProps, 'router'> & PagesDirectoryProviderProps;\n\ndeclare module 'iron-session' {\n interface IronSessionData {\n accessToken: FronteggNextJSSession['accessToken'];\n user: FronteggNextJSSession['user'];\n }\n}\n\ndeclare global {\n interface ProcessEnv {\n FRONTEGG_BASE_URL: string;\n PORT?: string;\n PWD: string;\n }\n}\n"],"mappings":""}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../packages/nextjs/src/types/index.ts"],"sourcesContent":["import type { FronteggAppOptions } from '@frontegg/types';\nimport type { ILoginResponse, ITenantsResponse } from '@frontegg/rest-api';\nimport type { IncomingMessage } from 'http';\nimport type { ReactNode } from 'react';\nimport type { AppRouterInstance } from 'next/dist/shared/lib/app-router-context';\nimport type { NextRouter } from 'next/router';\n\nexport interface EncryptionUtils {\n unsealTokens(data: string): Promise<FronteggUserTokens | undefined>;\n\n sealTokens(tokens: FronteggUserTokens, ttl: number): Promise<string>;\n}\n\nexport interface FronteggUserTokens {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface FronteggNextJSSession extends FronteggUserTokens {\n user: FronteggUserSession;\n}\n\nexport type RequestType = IncomingMessage | Request;\n\nexport interface AccountEnvironment {\n id: string;\n createdAt: string;\n environment: 'production' | 'development';\n}\n\nexport interface CustomClaims {\n accountEnvironments: AccountEnvironment[];\n}\n\nexport interface FronteggUserTokens {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface AllUserData {\n user?: ILoginResponse | null;\n tenants?: ITenantsResponse[] | null;\n activeTenant?: ITenantsResponse;\n session?: FronteggNextJSSession | null;\n}\nexport interface FronteggUserSession {\n sub: string;\n name: string;\n email: string;\n email_verified: boolean;\n metadata: any;\n roles: string[];\n permissions: string[];\n tenantId: string;\n tenantIds: string[];\n profilePictureUrl: string;\n type: string; // \"userToken\"\n customClaims: CustomClaims;\n iat: number;\n exp: number;\n aud: string;\n iss: string;\n}\n\nexport interface FronteggNextJSSession extends FronteggUserTokens {\n user: FronteggUserSession;\n}\n\nexport interface FronteggProviderOptions extends Omit<FronteggAppOptions, 'contextOptions'>, AllUserData {\n envAppUrl: string;\n envBaseUrl: string;\n envClientId: string;\n contextOptions?: Omit<FronteggAppOptions['contextOptions'], 'baseUrl'>;\n}\n\nexport interface FronteggProviderProps extends FronteggProviderOptions {\n children?: ReactNode;\n router: AppRouterInstance | NextRouter;\n appName?: string;\n}\n\ntype CustomLoginOptionsWithParamKeyType = {\n /**\n *The param key from your tenant login url, for 'frontegg.com?organization=[tenant]' would be 'organization'\n */\n paramKey: string;\n subDomainIndex?: never;\n};\n\ntype CustomLoginOptionsWithSubDomainType = {\n /**\n *The index of sub domain from your tenant login url, for 'https://[tenant].frontegg.com' would be 0\n */\n subDomainIndex: number;\n paramKey?: never;\n};\n\nexport type CustomLoginOptionsType = CustomLoginOptionsWithParamKeyType | CustomLoginOptionsWithSubDomainType;\n\ntype PagesDirectoryProviderProps = {\n customLoginOptions?: CustomLoginOptionsType;\n};\n\nexport type ClientFronteggProviderProps = Omit<FronteggProviderProps, 'router'> & PagesDirectoryProviderProps;\n\ndeclare module 'iron-session' {\n interface IronSessionData {\n accessToken: FronteggNextJSSession['accessToken'];\n user: FronteggNextJSSession['user'];\n }\n}\n\ndeclare global {\n var customLoginAppUrl: string | undefined;\n interface ProcessEnv {\n FRONTEGG_BASE_URL: string;\n PORT?: string;\n PWD: string;\n }\n}\n"],"mappings":""}