@frontegg/nextjs 9.2.1-alpha.12073075767 → 9.2.1-alpha.12811360407

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.
@@ -14,10 +14,12 @@ var _config = _interopRequireDefault(require("../config"));
14
14
  var _fetchUserData = _interopRequireDefault(require("../utils/fetchUserData"));
15
15
  var _getAppUrlForCustomLoginWithSubdomain = require("./getAppUrlForCustomLoginWithSubdomain");
16
16
  var _helpers2 = require("../middleware/helpers");
17
+ var _fronteggLogger = _interopRequireDefault(require("../utils/fronteggLogger"));
18
+ var _consts = require("./consts");
17
19
  var _jsxRuntime = require("react/jsx-runtime");
18
20
  const _excluded = ["envAppUrl"];
19
21
  const FronteggAppProvider = async options => {
20
- var _options$customLoginO, _options$secureJwtEna;
22
+ var _options$customLoginO, _options$secureJwtEna, _ref, _appEnvConfig$envHost;
21
23
  const _config$appEnvConfig = _config.default.appEnvConfig,
22
24
  {
23
25
  envAppUrl
@@ -28,14 +30,21 @@ const FronteggAppProvider = async options => {
28
30
  getHeaders: _helpers.getAppHeaders
29
31
  });
30
32
  const subDomainAppUrl = await (0, _getAppUrlForCustomLoginWithSubdomain.getAppUrlForCustomLoginWithSubdomain)((_options$customLoginO = options.customLoginOptions) == null ? void 0 : _options$customLoginO.subDomainIndex);
33
+ const logger = _fronteggLogger.default.child({
34
+ tag: 'FronteggAppProvider'
35
+ });
31
36
  if (process.env['FRONTEGG_SECURE_JWT_ENABLED'] === 'true' && userData) {
32
37
  var _userData;
33
38
  userData = (0, _helpers2.removeJwtSignatureFrom)(userData);
34
39
  userData.session = (0, _helpers2.removeJwtSignatureFrom)((_userData = userData) == null ? void 0 : _userData.session);
35
40
  }
41
+ if (Object.hasOwn(options, 'hostedLoginBox')) {
42
+ logger.warn(_consts.FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING);
43
+ }
36
44
  const providerProps = (0, _extends2.default)({}, appEnvConfig, userData, options, {
37
45
  envAppUrl: subDomainAppUrl != null ? subDomainAppUrl : envAppUrl,
38
- secureJwtEnabled: (_options$secureJwtEna = options.secureJwtEnabled) != null ? _options$secureJwtEna : false
46
+ secureJwtEnabled: (_options$secureJwtEna = options.secureJwtEnabled) != null ? _options$secureJwtEna : false,
47
+ hostedLoginBox: (_ref = (_appEnvConfig$envHost = appEnvConfig.envHostedLoginBox) != null ? _appEnvConfig$envHost : options.hostedLoginBox) != null ? _ref : false
39
48
  });
40
49
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ClientFronteggProvider.ClientFronteggProvider, (0, _extends2.default)({}, providerProps));
41
50
  };
@@ -1 +1 @@
1
- {"version":3,"file":"FronteggAppProvider.js","names":["_react","_interopRequireDefault","require","_ClientFronteggProvider","_helpers","_config","_fetchUserData","_getAppUrlForCustomLoginWithSubdomain","_helpers2","_jsxRuntime","_excluded","FronteggAppProvider","options","_options$customLoginO","_options$secureJwtEna","_config$appEnvConfig","config","appEnvConfig","envAppUrl","_objectWithoutPropertiesLoose2","default","userData","fetchUserData","getSession","getAppSession","getHeaders","getAppHeaders","subDomainAppUrl","getAppUrlForCustomLoginWithSubdomain","customLoginOptions","subDomainIndex","process","env","_userData","removeJwtSignatureFrom","session","providerProps","_extends2","secureJwtEnabled","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';\nimport { getAppUrlForCustomLoginWithSubdomain } from './getAppUrlForCustomLoginWithSubdomain';\nimport { removeJwtSignatureFrom } from '../middleware/helpers';\n\nexport type FronteggAppProviderProps = PropsWithChildren<\n Omit<ClientFronteggProviderProps, 'contextOptions' | 'envAppUrl' | 'envBaseUrl' | 'envClientId'>\n>;\n\nexport const FronteggAppProvider = async (options: FronteggAppProviderProps) => {\n const { envAppUrl, ...appEnvConfig } = config.appEnvConfig;\n let userData = await fetchUserData({ getSession: getAppSession, getHeaders: getAppHeaders });\n const subDomainAppUrl = await getAppUrlForCustomLoginWithSubdomain(options.customLoginOptions?.subDomainIndex);\n\n if (process.env['FRONTEGG_SECURE_JWT_ENABLED'] === 'true' && userData) {\n userData = removeJwtSignatureFrom(userData);\n userData.session = removeJwtSignatureFrom(userData?.session);\n }\n const providerProps = {\n ...appEnvConfig,\n ...userData,\n ...options,\n envAppUrl: subDomainAppUrl ?? envAppUrl,\n secureJwtEnabled: options.secureJwtEnabled ?? false,\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;AACA,IAAAM,SAAA,GAAAN,OAAA;AAA+D,IAAAO,WAAA,GAAAP,OAAA;AAAA,MAAAQ,SAAA;AAMxD,MAAMC,mBAAmB,GAAG,MAAOC,OAAiC,IAAK;EAAA,IAAAC,qBAAA,EAAAC,qBAAA;EAC9E,MAAAC,oBAAA,GAAuCC,eAAM,CAACC,YAAY;IAApD;MAAEC;IAA2B,CAAC,GAAAH,oBAAA;IAAdE,YAAY,OAAAE,8BAAA,CAAAC,OAAA,EAAAL,oBAAA,EAAAL,SAAA;EAClC,IAAIW,QAAQ,GAAG,MAAM,IAAAC,sBAAa,EAAC;IAAEC,UAAU,EAAEC,sBAAa;IAAEC,UAAU,EAAEC;EAAc,CAAC,CAAC;EAC5F,MAAMC,eAAe,GAAG,MAAM,IAAAC,0EAAoC,GAAAf,qBAAA,GAACD,OAAO,CAACiB,kBAAkB,qBAA1BhB,qBAAA,CAA4BiB,cAAc,CAAC;EAE9G,IAAIC,OAAO,CAACC,GAAG,CAAC,6BAA6B,CAAC,KAAK,MAAM,IAAIX,QAAQ,EAAE;IAAA,IAAAY,SAAA;IACrEZ,QAAQ,GAAG,IAAAa,gCAAsB,EAACb,QAAQ,CAAC;IAC3CA,QAAQ,CAACc,OAAO,GAAG,IAAAD,gCAAsB,GAAAD,SAAA,GAACZ,QAAQ,qBAARY,SAAA,CAAUE,OAAO,CAAC;EAC9D;EACA,MAAMC,aAAa,OAAAC,SAAA,CAAAjB,OAAA,MACdH,YAAY,EACZI,QAAQ,EACRT,OAAO;IACVM,SAAS,EAAES,eAAe,WAAfA,eAAe,GAAIT,SAAS;IACvCoB,gBAAgB,GAAAxB,qBAAA,GAAEF,OAAO,CAAC0B,gBAAgB,YAAAxB,qBAAA,GAAI;EAAK,EACpD;EAED,oBAAO,IAAAL,WAAA,CAAA8B,GAAA,EAACpC,uBAAA,CAAAqC,sBAAsB,MAAAH,SAAA,CAAAjB,OAAA,MAAKgB,aAAa,CAAG,CAAC;AACtD,CAAC;AAACK,OAAA,CAAA9B,mBAAA,GAAAA,mBAAA","ignoreList":[]}
1
+ {"version":3,"file":"FronteggAppProvider.js","names":["_react","_interopRequireDefault","require","_ClientFronteggProvider","_helpers","_config","_fetchUserData","_getAppUrlForCustomLoginWithSubdomain","_helpers2","_fronteggLogger","_consts","_jsxRuntime","_excluded","FronteggAppProvider","options","_options$customLoginO","_options$secureJwtEna","_ref","_appEnvConfig$envHost","_config$appEnvConfig","config","appEnvConfig","envAppUrl","_objectWithoutPropertiesLoose2","default","userData","fetchUserData","getSession","getAppSession","getHeaders","getAppHeaders","subDomainAppUrl","getAppUrlForCustomLoginWithSubdomain","customLoginOptions","subDomainIndex","logger","fronteggLogger","child","tag","process","env","_userData","removeJwtSignatureFrom","session","Object","hasOwn","warn","FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING","providerProps","_extends2","secureJwtEnabled","hostedLoginBox","envHostedLoginBox","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';\nimport { getAppUrlForCustomLoginWithSubdomain } from './getAppUrlForCustomLoginWithSubdomain';\nimport { removeJwtSignatureFrom } from '../middleware/helpers';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport { FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING } from './consts';\n\nexport type FronteggAppProviderProps = PropsWithChildren<\n Omit<ClientFronteggProviderProps, 'contextOptions' | 'envAppUrl' | 'envBaseUrl' | 'envClientId'>\n>;\n\nexport const FronteggAppProvider = async (options: FronteggAppProviderProps) => {\n const { envAppUrl, ...appEnvConfig } = config.appEnvConfig;\n let userData = await fetchUserData({ getSession: getAppSession, getHeaders: getAppHeaders });\n const subDomainAppUrl = await getAppUrlForCustomLoginWithSubdomain(options.customLoginOptions?.subDomainIndex);\n const logger = fronteggLogger.child({ tag: 'FronteggAppProvider' });\n\n if (process.env['FRONTEGG_SECURE_JWT_ENABLED'] === 'true' && userData) {\n userData = removeJwtSignatureFrom(userData);\n userData.session = removeJwtSignatureFrom(userData?.session);\n }\n if (Object.hasOwn(options, 'hostedLoginBox')) {\n logger.warn(FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING);\n }\n\n const providerProps = {\n ...appEnvConfig,\n ...userData,\n ...options,\n envAppUrl: subDomainAppUrl ?? envAppUrl,\n secureJwtEnabled: options.secureJwtEnabled ?? false,\n hostedLoginBox: appEnvConfig.envHostedLoginBox ?? options.hostedLoginBox ?? false,\n };\n\n return <ClientFronteggProvider {...providerProps} />;\n};\n"],"mappings":";;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAA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EAC9D;EACA,IAAIC,MAAM,CAACC,MAAM,CAAC/B,OAAO,EAAE,gBAAgB,CAAC,EAAE;IAC5CqB,MAAM,CAACW,IAAI,CAACC,+CAAuC,CAAC;EACtD;EAEA,MAAMC,aAAa,OAAAC,SAAA,CAAAzB,OAAA,MACdH,YAAY,EACZI,QAAQ,EACRX,OAAO;IACVQ,SAAS,EAAES,eAAe,WAAfA,eAAe,GAAIT,SAAS;IACvC4B,gBAAgB,GAAAlC,qBAAA,GAAEF,OAAO,CAACoC,gBAAgB,YAAAlC,qBAAA,GAAI,KAAK;IACnDmC,cAAc,GAAAlC,IAAA,IAAAC,qBAAA,GAAEG,YAAY,CAAC+B,iBAAiB,YAAAlC,qBAAA,GAAIJ,OAAO,CAACqC,cAAc,YAAAlC,IAAA,GAAI;EAAK,EAClF;EAED,oBAAO,IAAAN,WAAA,CAAA0C,GAAA,EAAClD,uBAAA,CAAAmD,sBAAsB,MAAAL,SAAA,CAAAzB,OAAA,MAAKwB,aAAa,CAAG,CAAC;AACtD,CAAC;AAACO,OAAA,CAAA1C,mBAAA,GAAAA,mBAAA","ignoreList":[]}
@@ -0,0 +1 @@
1
+ export declare const FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING = "\n**Deprecated**: The 'hostedLoginBox' prop is deprecated in frontegg NextJS SKD and will be removed in the next major version. Please use 'FRONTEGG_HOSTED_LOGIN' environment variable instead.";
package/app/consts.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING = void 0;
7
+ const FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING = exports.FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING = `\n**Deprecated**: The 'hostedLoginBox' prop is deprecated in frontegg NextJS SKD and will be removed in the next major version. Please use 'FRONTEGG_HOSTED_LOGIN' environment variable instead.`;
8
+ //# sourceMappingURL=consts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consts.js","names":["FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING","exports"],"sources":["../../../../packages/nextjs/src/app/consts.ts"],"sourcesContent":["export const FRONTEGG_HOSTED_LOGIN_MIGRATION_WARNING = `\\n**Deprecated**: The 'hostedLoginBox' prop is deprecated in frontegg NextJS SKD and will be removed in the next major version. Please use 'FRONTEGG_HOSTED_LOGIN' environment variable instead.`;\n"],"mappings":";;;;;;AAAO,MAAMA,uCAAuC,GAAAC,OAAA,CAAAD,uCAAA,GAAG,kMAAkM","ignoreList":[]}
@@ -30,7 +30,7 @@ export declare const handleSessionOnEdge: (params: HandleSessionOnEdge) => Promi
30
30
  * ```
31
31
  * @deprecated
32
32
  */
33
- export declare const getSessionOnEdge: (req: IncomingMessage | Request) => Promise<FronteggNextJSSession | undefined>;
33
+ export declare const getSessionOnEdge: (req: IncomingMessage | Request, disableWarning?: boolean) => Promise<FronteggNextJSSession | undefined>;
34
34
  /**
35
35
  * Check session on edge and return session if exists this method does not redirect to login page
36
36
  * Example:
@@ -62,11 +62,14 @@ export declare const getSessionOnEdge: (req: IncomingMessage | Request) => Promi
62
62
  * return redirectToLogin(pathname);
63
63
  * }
64
64
  *
65
- * // if headers are present return them to the next response
65
+ * // if headers are present forward them to the next response / request
66
66
  * if (session.headers) {
67
- * return NextResponse.next({
68
- * headers: session.headers,
69
- * });
67
+ * return NextResponse.next({
68
+ * headers: edgeSession.headers,
69
+ * request:{
70
+ * headers: edgeSession.forwardedHeaders
71
+ * }
72
+ * });
70
73
  * }
71
74
  * return NextResponse.next();
72
75
  * };
@@ -40,13 +40,16 @@ const handleSessionOnEdge = async params => {
40
40
  }
41
41
  if (edgeSession.headers) {
42
42
  return _server.NextResponse.next({
43
- headers: edgeSession.headers
43
+ headers: edgeSession.headers,
44
+ request: {
45
+ headers: edgeSession.forwardedHeaders
46
+ }
44
47
  });
45
48
  }
46
49
  return _server.NextResponse.next();
47
50
  };
48
51
  exports.handleSessionOnEdge = handleSessionOnEdge;
49
- const GET_SESSION_ON_EDGE_DEPRECATED_ERROR = `Deprecation Notice: getSessionOnEdge has been deprecated. Please use handleSessionOnEdge instead. For example:
52
+ const GET_SESSION_ON_EDGE_DEPRECATED_WARN = `Deprecation Notice: getSessionOnEdge has been deprecated. Please use handleSessionOnEdge instead. For example:
50
53
 
51
54
  file: middleware.ts
52
55
  \`\`\`ts
@@ -95,8 +98,14 @@ Alternatively, to manually verify the session, you can use checkSessionOnEdge. N
95
98
  * @deprecated
96
99
  */
97
100
 
98
- const getSessionOnEdge = req => {
101
+ const getSessionOnEdge = (req, disableWarning = false) => {
102
+ const logger = _fronteggLogger.default.child({
103
+ tag: 'EdgeRuntime.getSessionOnEdge'
104
+ });
99
105
  const cookies = _cookies.default.getSessionCookieFromRequest(req);
106
+ if (!disableWarning) {
107
+ logger.info(GET_SESSION_ON_EDGE_DEPRECATED_WARN);
108
+ }
100
109
  return (0, _createSession.default)(cookies, _encryptionEdge.default);
101
110
  };
102
111
 
@@ -131,11 +140,14 @@ const getSessionOnEdge = req => {
131
140
  * return redirectToLogin(pathname);
132
141
  * }
133
142
  *
134
- * // if headers are present return them to the next response
143
+ * // if headers are present forward them to the next response / request
135
144
  * if (session.headers) {
136
- * return NextResponse.next({
137
- * headers: session.headers,
138
- * });
145
+ * return NextResponse.next({
146
+ * headers: edgeSession.headers,
147
+ * request:{
148
+ * headers: edgeSession.forwardedHeaders
149
+ * }
150
+ * });
139
151
  * }
140
152
  * return NextResponse.next();
141
153
  * };
@@ -1 +1 @@
1
- {"version":3,"file":"getSessionOnEdge.js","names":["_cookies","_interopRequireDefault","require","_createSession","_encryptionEdge","_api","_server","_config","_jwt","_utils","_fronteggLogger","_refreshAccessTokenIfNeededOnEdge","_redirectToLogin","_shouldBypassMiddleware","logger","fronteggLogger","child","tag","handleSessionOnEdge","params","request","pathname","searchParams","headers","isHostedLoginCallback","handleHostedLoginCallback","shouldByPassMiddleware","NextResponse","next","edgeSession","checkSessionOnEdge","redirectToLogin","exports","GET_SESSION_ON_EDGE_DEPRECATED_ERROR","getSessionOnEdge","req","cookies","CookieManager","getSessionCookieFromRequest","createSession","encryptionEdge","sessionCookies","existingSession","debug","session","refreshAccessTokenIfNeededOnEdge","createSessionFromAccessTokenEdge","data","_data$accessToken","_data$refreshToken","accessToken","access_token","refreshToken","refresh_token","payload","decodedJwt","JwtManager","verify","expiresIn","Math","floor","exp","Date","now","tokens","sealTokens","_searchParams$get","_req$headers","code","get","clientIp","undefined","_socket","socket","remoteAddress","_socket2","requestHeaders","_extends2","default","config","shouldForwardIp","_config$clientSecret","FRONTEGG_FORWARD_IP_HEADER","FRONTEGG_CLIENT_SECRET_HEADER","clientSecret","response","api","exchangeHostedLoginToken","buildRequestHeaders","clientId","json","redirect","appUrl","isSecured","isSSL","cookieValue","create","value","expires","secure","cookieName","replace","rewriteCookieByAppId","appId","refreshCookie","sessionCookieHeaders","map","cookie","refreshCookieHeaders","secureJwtEnabled","startsWith"],"sources":["../../../../packages/nextjs/src/edge/getSessionOnEdge.ts"],"sourcesContent":["import type { IncomingMessage } from 'http';\nimport { FronteggEdgeSession, FronteggNextJSSession } from '../types';\nimport CookieManager from '../utils/cookies';\nimport createSession from '../utils/createSession';\nimport encryptionEdge from '../utils/encryption-edge';\nimport api from '../api';\nimport { type NextRequest, NextResponse } from 'next/server';\nimport config from '../config';\nimport JwtManager from '../utils/jwt';\nimport { buildRequestHeaders, FRONTEGG_CLIENT_SECRET_HEADER, FRONTEGG_FORWARD_IP_HEADER } from '../api/utils';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport { refreshAccessTokenIfNeededOnEdge } from './refreshAccessTokenIfNeededOnEdge';\nimport { redirectToLogin } from './redirectToLogin';\nimport { shouldByPassMiddleware } from './shouldBypassMiddleware';\n\nconst logger = fronteggLogger.child({ tag: 'EdgeRuntime.getSessionOnEdge' });\n\nexport type HandleSessionOnEdge = {\n request: IncomingMessage | Request;\n pathname: string;\n headers: NextRequest['headers'];\n searchParams: URLSearchParams;\n};\n\nexport const handleSessionOnEdge = async (params: HandleSessionOnEdge): Promise<NextResponse> => {\n const { request, pathname, searchParams, headers } = params;\n\n if (isHostedLoginCallback(pathname, searchParams)) {\n return handleHostedLoginCallback(request, pathname, searchParams);\n }\n\n if (shouldByPassMiddleware(pathname, headers /*, options: optional bypass configuration */)) {\n return NextResponse.next();\n }\n\n const edgeSession = await checkSessionOnEdge(request);\n if (!edgeSession) {\n return redirectToLogin(pathname, searchParams);\n }\n if (edgeSession.headers) {\n return NextResponse.next({\n headers: edgeSession.headers,\n });\n }\n return NextResponse.next();\n};\n\nconst GET_SESSION_ON_EDGE_DEPRECATED_ERROR = `Deprecation Notice: getSessionOnEdge has been deprecated. Please use handleSessionOnEdge instead. For example:\n\nfile: middleware.ts\n\\`\\`\\`ts\n import { NextRequest } from 'next/server';\n import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n \n export const middleware = async (request: NextRequest) => {\n const { pathname, searchParams } = request.nextUrl;\n const headers = request.headers;\n \n // Additional logic if needed\n \n return handleSessionOnEdge({ request, pathname, searchParams, headers });\n };\n \n \n export const config = {\n matcher: '/(.*)',\n };\n\n\\`\\`\\`\n\nAlternatively, to manually verify the session, you can use checkSessionOnEdge. Note that this method does not redirect to the login page if the session is invalid.\n`;\n\n/**\n * getSessionOnEdge is deprecated, please use handleSessionOnEdge instead example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * return handleSessionOnEdge({ request, pathname, searchParams, headers });\n * };\n *\n * export const config = {\n * matcher: '/(.*)',\n * };\n * ```\n * @deprecated\n */\n\nexport const getSessionOnEdge = (req: IncomingMessage | Request): Promise<FronteggNextJSSession | undefined> => {\n const cookies = CookieManager.getSessionCookieFromRequest(req);\n return createSession(cookies, encryptionEdge);\n};\n\n/**\n * Check session on edge and return session if exists this method does not redirect to login page\n * Example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * // check if it's a hosted login callback\n * if (isHostedLoginCallback(pathname, searchParams)) {\n * return handleHostedLoginCallback(request, pathname, searchParams);\n * }\n *\n * // check if we should bypass the middleware\n * if (shouldByPassMiddleware(pathname)) {\n * return NextResponse.next();\n * }\n *\n * // check session\n * const session = await checkSessionOnEdge(request);\n *\n * if (!session) {\n * return redirectToLogin(pathname);\n * }\n *\n * // if headers are present return them to the next response\n * if (session.headers) {\n * return NextResponse.next({\n * headers: session.headers,\n * });\n * }\n * return NextResponse.next();\n * };\n * ```\n *\n *\n * @param req\n */\nexport const checkSessionOnEdge = async (req: IncomingMessage | Request): Promise<FronteggEdgeSession | undefined> => {\n const sessionCookies = CookieManager.getSessionCookieFromRequest(req);\n let existingSession = await createSession(sessionCookies, encryptionEdge);\n if (existingSession) {\n logger.debug('session resolved from session cookie');\n return {\n session: existingSession,\n };\n }\n\n logger.debug('Failed to resolve session from cookie, going to refresh token');\n return refreshAccessTokenIfNeededOnEdge(req);\n};\n\nasync function createSessionFromAccessTokenEdge(data: any): Promise<[string, any, string] | []> {\n const accessToken = data.accessToken ?? data.access_token;\n const refreshToken = data.refreshToken ?? data.refresh_token;\n const { payload: decodedJwt }: any = await JwtManager.verify(accessToken);\n decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);\n\n const tokens = { accessToken, refreshToken };\n const session = await encryptionEdge.sealTokens(tokens, decodedJwt.exp);\n return [session, decodedJwt, refreshToken];\n}\n\nexport const handleHostedLoginCallback = async (\n req: IncomingMessage | Request,\n pathname: string,\n searchParams: URLSearchParams\n): Promise<NextResponse> => {\n if (!isHostedLoginCallback(pathname, searchParams)) {\n return NextResponse.next();\n }\n\n const code = searchParams.get('code') ?? '';\n\n let headers: Record<string, string> = {};\n let clientIp: string | undefined = undefined;\n if (typeof req.headers?.get === 'function') {\n clientIp =\n req.headers.get('cf-connecting-ip') || req.headers.get('x-forwarded-for') || (req as any).socket?.remoteAddress;\n } else if (typeof req.headers === 'object') {\n let requestHeaders: any = { ...req.headers };\n clientIp =\n requestHeaders['cf-connecting-ip'] || requestHeaders['x-forwarded-for'] || (req as any).socket?.remoteAddress;\n }\n\n if (clientIp && config.shouldForwardIp) {\n headers[FRONTEGG_FORWARD_IP_HEADER] = clientIp;\n headers[FRONTEGG_CLIENT_SECRET_HEADER] = config.clientSecret ?? '';\n }\n\n const response = await api.exchangeHostedLoginToken(\n buildRequestHeaders(headers),\n code,\n config.clientId,\n config.clientSecret!\n );\n\n const data = await response.json();\n\n const [session, decodedJwt, refreshToken] = await createSessionFromAccessTokenEdge(data);\n\n if (!session) {\n return NextResponse.redirect(config.appUrl);\n }\n const isSecured = config.isSSL;\n const cookieValue = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n\n let cookieName = `fe_refresh_${config.clientId.replace('-', '')}`;\n if (config.rewriteCookieByAppId && config.appId) {\n cookieName = `fe_refresh_${config.appId.replace('-', '')}`;\n }\n const refreshCookie = CookieManager.create({\n cookieName,\n value: refreshToken ?? '',\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n const sessionCookieHeaders: [string, string][] = cookieValue.map((cookie) => ['set-cookie', cookie]);\n const refreshCookieHeaders: [string, string][] = refreshCookie.map((cookie) => ['set-cookie', cookie]);\n\n return NextResponse.redirect(config.appUrl, {\n headers: [...sessionCookieHeaders, ...refreshCookieHeaders],\n });\n};\n\nexport const isHostedLoginCallback = (pathname: string, searchParams: URLSearchParams): boolean => {\n if (config.secureJwtEnabled) {\n if (pathname.startsWith('/oauth/callback')) {\n return searchParams.get('code') != null;\n }\n }\n return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AAC;MACvBL,OAAO,EAAEM,WAAW,CAACN;IACvB,CAAC,CAAC;EACJ;EACA,OAAOI,oBAAY,CAACC,IAAI,CAAC,CAAC;AAC5B,CAAC;AAACI,OAAA,CAAAd,mBAAA,GAAAA,mBAAA;AAEF,MAAMe,oCAAoC,GAAG;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO,MAAMC,gBAAgB,GAAIC,GAA8B,IAAiD;EAC9G,MAAMC,OAAO,GAAGC,gBAAa,CAACC,2BAA2B,CAACH,GAAG,CAAC;EAC9D,OAAO,IAAAI,sBAAa,EAACH,OAAO,EAAEI,uBAAc,CAAC;AAC/C,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA3CAR,OAAA,CAAAE,gBAAA,GAAAA,gBAAA;AA4CO,MAAMJ,kBAAkB,GAAG,MAAOK,GAA8B,IAA+C;EACpH,MAAMM,cAAc,GAAGJ,gBAAa,CAACC,2BAA2B,CAACH,GAAG,CAAC;EACrE,IAAIO,eAAe,GAAG,MAAM,IAAAH,sBAAa,EAACE,cAAc,EAAED,uBAAc,CAAC;EACzE,IAAIE,eAAe,EAAE;IACnB5B,MAAM,CAAC6B,KAAK,CAAC,sCAAsC,CAAC;IACpD,OAAO;MACLC,OAAO,EAAEF;IACX,CAAC;EACH;EAEA5B,MAAM,CAAC6B,KAAK,CAAC,+DAA+D,CAAC;EAC7E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AAC,CAAC;AACJ,CAAC;AAAC5E,OAAA,CAAAP,yBAAA,GAAAA,yBAAA;AAEK,MAAMD,qBAAqB,GAAGA,CAACH,QAAgB,EAAEC,YAA6B,KAAc;EACjG,IAAIyD,eAAM,CAAC8B,gBAAgB,EAAE;IAC3B,IAAIxF,QAAQ,CAACyF,UAAU,CAAC,iBAAiB,CAAC,EAAE;MAC1C,OAAOxF,YAAY,CAAC+C,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI;IACzC;EACF;EACA,OAAO,KAAK;AACd,CAAC;AAACrC,OAAA,CAAAR,qBAAA,GAAAA,qBAAA","ignoreList":[]}
1
+ {"version":3,"file":"getSessionOnEdge.js","names":["_cookies","_interopRequireDefault","require","_createSession","_encryptionEdge","_api","_server","_config","_jwt","_utils","_fronteggLogger","_refreshAccessTokenIfNeededOnEdge","_redirectToLogin","_shouldBypassMiddleware","logger","fronteggLogger","child","tag","handleSessionOnEdge","params","request","pathname","searchParams","headers","isHostedLoginCallback","handleHostedLoginCallback","shouldByPassMiddleware","NextResponse","next","edgeSession","checkSessionOnEdge","redirectToLogin","forwardedHeaders","exports","GET_SESSION_ON_EDGE_DEPRECATED_WARN","getSessionOnEdge","req","disableWarning","cookies","CookieManager","getSessionCookieFromRequest","info","createSession","encryptionEdge","sessionCookies","existingSession","debug","session","refreshAccessTokenIfNeededOnEdge","createSessionFromAccessTokenEdge","data","_data$accessToken","_data$refreshToken","accessToken","access_token","refreshToken","refresh_token","payload","decodedJwt","JwtManager","verify","expiresIn","Math","floor","exp","Date","now","tokens","sealTokens","_searchParams$get","_req$headers","code","get","clientIp","undefined","_socket","socket","remoteAddress","_socket2","requestHeaders","_extends2","default","config","shouldForwardIp","_config$clientSecret","FRONTEGG_FORWARD_IP_HEADER","FRONTEGG_CLIENT_SECRET_HEADER","clientSecret","response","api","exchangeHostedLoginToken","buildRequestHeaders","clientId","json","redirect","appUrl","isSecured","isSSL","cookieValue","create","value","expires","secure","cookieName","replace","rewriteCookieByAppId","appId","refreshCookie","sessionCookieHeaders","map","cookie","refreshCookieHeaders","secureJwtEnabled","startsWith"],"sources":["../../../../packages/nextjs/src/edge/getSessionOnEdge.ts"],"sourcesContent":["import type { IncomingMessage } from 'http';\nimport { FronteggEdgeSession, FronteggNextJSSession } from '../types';\nimport CookieManager from '../utils/cookies';\nimport createSession from '../utils/createSession';\nimport encryptionEdge from '../utils/encryption-edge';\nimport api from '../api';\nimport { type NextRequest, NextResponse } from 'next/server';\nimport config from '../config';\nimport JwtManager from '../utils/jwt';\nimport { buildRequestHeaders, FRONTEGG_CLIENT_SECRET_HEADER, FRONTEGG_FORWARD_IP_HEADER } from '../api/utils';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport { refreshAccessTokenIfNeededOnEdge } from './refreshAccessTokenIfNeededOnEdge';\nimport { redirectToLogin } from './redirectToLogin';\nimport { shouldByPassMiddleware } from './shouldBypassMiddleware';\n\nconst logger = fronteggLogger.child({ tag: 'EdgeRuntime.getSessionOnEdge' });\n\nexport type HandleSessionOnEdge = {\n request: IncomingMessage | Request;\n pathname: string;\n headers: NextRequest['headers'];\n searchParams: URLSearchParams;\n};\n\nexport const handleSessionOnEdge = async (params: HandleSessionOnEdge): Promise<NextResponse> => {\n const { request, pathname, searchParams, headers } = params;\n\n if (isHostedLoginCallback(pathname, searchParams)) {\n return handleHostedLoginCallback(request, pathname, searchParams);\n }\n\n if (shouldByPassMiddleware(pathname, headers /*, options: optional bypass configuration */)) {\n return NextResponse.next();\n }\n\n const edgeSession = await checkSessionOnEdge(request);\n if (!edgeSession) {\n return redirectToLogin(pathname, searchParams);\n }\n if (edgeSession.headers) {\n return NextResponse.next({\n headers: edgeSession.headers,\n request: {\n headers: edgeSession.forwardedHeaders,\n },\n });\n }\n return NextResponse.next();\n};\n\nconst GET_SESSION_ON_EDGE_DEPRECATED_WARN = `Deprecation Notice: getSessionOnEdge has been deprecated. Please use handleSessionOnEdge instead. For example:\n\nfile: middleware.ts\n\\`\\`\\`ts\n import { NextRequest } from 'next/server';\n import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n \n export const middleware = async (request: NextRequest) => {\n const { pathname, searchParams } = request.nextUrl;\n const headers = request.headers;\n \n // Additional logic if needed\n \n return handleSessionOnEdge({ request, pathname, searchParams, headers });\n };\n \n \n export const config = {\n matcher: '/(.*)',\n };\n\n\\`\\`\\`\n\nAlternatively, to manually verify the session, you can use checkSessionOnEdge. Note that this method does not redirect to the login page if the session is invalid.\n`;\n\n/**\n * getSessionOnEdge is deprecated, please use handleSessionOnEdge instead example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * return handleSessionOnEdge({ request, pathname, searchParams, headers });\n * };\n *\n * export const config = {\n * matcher: '/(.*)',\n * };\n * ```\n * @deprecated\n */\n\nexport const getSessionOnEdge = (\n req: IncomingMessage | Request,\n disableWarning = false\n): Promise<FronteggNextJSSession | undefined> => {\n const logger = fronteggLogger.child({ tag: 'EdgeRuntime.getSessionOnEdge' });\n const cookies = CookieManager.getSessionCookieFromRequest(req);\n if (!disableWarning) {\n logger.info(GET_SESSION_ON_EDGE_DEPRECATED_WARN);\n }\n return createSession(cookies, encryptionEdge);\n};\n\n/**\n * Check session on edge and return session if exists this method does not redirect to login page\n * Example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * // check if it's a hosted login callback\n * if (isHostedLoginCallback(pathname, searchParams)) {\n * return handleHostedLoginCallback(request, pathname, searchParams);\n * }\n *\n * // check if we should bypass the middleware\n * if (shouldByPassMiddleware(pathname)) {\n * return NextResponse.next();\n * }\n *\n * // check session\n * const session = await checkSessionOnEdge(request);\n *\n * if (!session) {\n * return redirectToLogin(pathname);\n * }\n *\n * // if headers are present forward them to the next response / request\n * if (session.headers) {\n * return NextResponse.next({\n * headers: edgeSession.headers,\n * request:{\n * headers: edgeSession.forwardedHeaders\n * }\n * });\n * }\n * return NextResponse.next();\n * };\n * ```\n *\n *\n * @param req\n */\nexport const checkSessionOnEdge = async (req: IncomingMessage | Request): Promise<FronteggEdgeSession | undefined> => {\n const sessionCookies = CookieManager.getSessionCookieFromRequest(req);\n let existingSession = await createSession(sessionCookies, encryptionEdge);\n if (existingSession) {\n logger.debug('session resolved from session cookie');\n return {\n session: existingSession,\n };\n }\n\n logger.debug('Failed to resolve session from cookie, going to refresh token');\n return refreshAccessTokenIfNeededOnEdge(req);\n};\n\nasync function createSessionFromAccessTokenEdge(data: any): Promise<[string, any, string] | []> {\n const accessToken = data.accessToken ?? data.access_token;\n const refreshToken = data.refreshToken ?? data.refresh_token;\n const { payload: decodedJwt }: any = await JwtManager.verify(accessToken);\n decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);\n\n const tokens = { accessToken, refreshToken };\n const session = await encryptionEdge.sealTokens(tokens, decodedJwt.exp);\n return [session, decodedJwt, refreshToken];\n}\n\nexport const handleHostedLoginCallback = async (\n req: IncomingMessage | Request,\n pathname: string,\n searchParams: URLSearchParams\n): Promise<NextResponse> => {\n if (!isHostedLoginCallback(pathname, searchParams)) {\n return NextResponse.next();\n }\n\n const code = searchParams.get('code') ?? '';\n\n let headers: Record<string, string> = {};\n let clientIp: string | undefined = undefined;\n if (typeof req.headers?.get === 'function') {\n clientIp =\n req.headers.get('cf-connecting-ip') || req.headers.get('x-forwarded-for') || (req as any).socket?.remoteAddress;\n } else if (typeof req.headers === 'object') {\n let requestHeaders: any = { ...req.headers };\n clientIp =\n requestHeaders['cf-connecting-ip'] || requestHeaders['x-forwarded-for'] || (req as any).socket?.remoteAddress;\n }\n\n if (clientIp && config.shouldForwardIp) {\n headers[FRONTEGG_FORWARD_IP_HEADER] = clientIp;\n headers[FRONTEGG_CLIENT_SECRET_HEADER] = config.clientSecret ?? '';\n }\n\n const response = await api.exchangeHostedLoginToken(\n buildRequestHeaders(headers),\n code,\n config.clientId,\n config.clientSecret!\n );\n\n const data = await response.json();\n\n const [session, decodedJwt, refreshToken] = await createSessionFromAccessTokenEdge(data);\n\n if (!session) {\n return NextResponse.redirect(config.appUrl);\n }\n const isSecured = config.isSSL;\n const cookieValue = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n\n let cookieName = `fe_refresh_${config.clientId.replace('-', '')}`;\n if (config.rewriteCookieByAppId && config.appId) {\n cookieName = `fe_refresh_${config.appId.replace('-', '')}`;\n }\n const refreshCookie = CookieManager.create({\n cookieName,\n value: refreshToken ?? '',\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n const sessionCookieHeaders: [string, string][] = cookieValue.map((cookie) => ['set-cookie', cookie]);\n const refreshCookieHeaders: [string, string][] = refreshCookie.map((cookie) => ['set-cookie', cookie]);\n\n return NextResponse.redirect(config.appUrl, {\n headers: [...sessionCookieHeaders, ...refreshCookieHeaders],\n });\n};\n\nexport const isHostedLoginCallback = (pathname: string, searchParams: URLSearchParams): boolean => {\n if (config.secureJwtEnabled) {\n if (pathname.startsWith('/oauth/callback')) {\n return searchParams.get('code') != null;\n }\n }\n return false;\n};\n"],"mappings":";;;;;;;;AAEA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,cAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,eAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,IAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,OAAA,GAAAN,sBAAA,CAAAC,OAAA;AACA,IAAAM,IAAA,GAAAP,sBAAA,CAAAC,OAAA;AACA,IAAAO,MAAA,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MAAMD,qBAAqB,GAAGA,CAACH,QAAgB,EAAEC,YAA6B,KAAc;EACjG,IAAI4D,eAAM,CAAC8B,gBAAgB,EAAE;IAC3B,IAAI3F,QAAQ,CAAC4F,UAAU,CAAC,iBAAiB,CAAC,EAAE;MAC1C,OAAO3F,YAAY,CAACkD,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI;IACzC;EACF;EACA,OAAO,KAAK;AACd,CAAC;AAACvC,OAAA,CAAAT,qBAAA,GAAAA,qBAAA","ignoreList":[]}
@@ -79,6 +79,12 @@ async function refreshAccessTokenIfNeededOnEdge(req) {
79
79
  req
80
80
  });
81
81
  newSetCookie.push(...cookieValue);
82
+ const forwardedHeaders = req.headers;
83
+ newSetCookie.forEach(cookie => {
84
+ // get cookie name and value only
85
+ const [name, value] = cookie.split(';')[0].split('=');
86
+ forwardedHeaders.set('cookie', `${name}=${value}`);
87
+ });
82
88
  return {
83
89
  session: {
84
90
  accessToken: (_data$accessToken = data.accessToken) != null ? _data$accessToken : data.access_token,
@@ -87,7 +93,8 @@ async function refreshAccessTokenIfNeededOnEdge(req) {
87
93
  },
88
94
  headers: {
89
95
  'set-cookie': newSetCookie.join(', ')
90
- }
96
+ },
97
+ forwardedHeaders
91
98
  };
92
99
  }
93
100
  async function createSessionFromAccessTokenOnEdge(data) {
@@ -1 +1 @@
1
- {"version":3,"file":"refreshAccessTokenIfNeededOnEdge.js","names":["_cookies","_interopRequireDefault","require","_config","_api","_fronteggLogger","_jwt","_encryptionEdge","logger","fronteggLogger","child","tag","refreshAccessTokenIfNeededOnEdge","req","_ref","_ref2","_response$headers$raw","_response$headers","_response$headers$raw2","_response$headers2","_response$headers2$ge","_response$headers3","_response$headers3$ge","_CookieManager$modify","_data$accessToken","refreshCookie","CookieManager","getRefreshCookieFromRequestEdge","info","undefined","reqHeaders","headers","forEach","value","key","clientId","config","clientSecret","response","isHostedLogin","api","refreshTokenHostedLogin","refreshTokenEmbedded","e","error","isSecured","isSSL","ok","cookiesToRemove","getRequestCookiesHeaderToRemove","cookieDomain","session","join","data","json","cookieHeader","raw","call","getSetCookie","get","newSetCookie","modifySetCookie","decodedJwt","refreshToken","createSessionFromAccessTokenOnEdge","cookieValue","create","expires","Date","exp","secure","push","accessToken","access_token","user","_data$accessToken2","_data$refreshToken","refresh_token","payload","JwtManager","verify","expiresIn","Math","floor","now","tokens","encryptionEdge","sealTokens"],"sources":["../../../../packages/nextjs/src/edge/refreshAccessTokenIfNeededOnEdge.ts"],"sourcesContent":["import { FronteggEdgeSession } from '../types';\nimport type { IncomingMessage } from 'http';\nimport CookieManager from '../utils/cookies';\nimport config from '../config';\nimport api from '../api';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport JwtManager from '../utils/jwt';\nimport encryptionEdge from '../utils/encryption-edge';\n\nconst logger = fronteggLogger.child({ tag: 'EdgeRuntime.refreshAccessTokenIfNeededOnEdge' });\n\nexport async function refreshAccessTokenIfNeededOnEdge(\n req: IncomingMessage | Request\n): Promise<FronteggEdgeSession | undefined> {\n const refreshCookie = CookieManager.getRefreshCookieFromRequestEdge(req);\n if (!refreshCookie) {\n logger.info('No refresh cookie found, No session found');\n return undefined;\n }\n\n logger.info('going to refresh token');\n\n const reqHeaders = req.headers as any as Map<string, string>;\n const headers: Record<string, string> = {};\n reqHeaders.forEach((value: string, key: string) => {\n headers[key] = value;\n });\n const clientId = config.clientId;\n const clientSecret = config.clientSecret;\n\n let response: Response | null;\n try {\n if (config.isHostedLogin) {\n response = await api.refreshTokenHostedLogin(headers, refreshCookie, clientId, clientSecret);\n } else {\n response = await api.refreshTokenEmbedded(headers);\n }\n } catch (e) {\n logger.error('Failed to refresh token', e);\n return undefined;\n }\n\n const isSecured = config.isSSL;\n if (response === null || !response.ok) {\n const cookiesToRemove = CookieManager.getRequestCookiesHeaderToRemove({\n cookieDomain: config.cookieDomain,\n isSecured,\n req,\n });\n if (cookiesToRemove) {\n return {\n session: undefined,\n headers: {\n 'set-cookie': cookiesToRemove.join(', '),\n },\n };\n }\n return undefined;\n }\n\n const data = await response.json();\n\n const cookieHeader: string[] =\n // @ts-ignore the first argument \"raw\" will only work before nextjs 13.4 and the second argument \"getSetCookie\" will only work after\n response.headers?.raw?.()['set-cookie'] ??\n // @ts-ignore the first argument \"raw\" will only work before nextjs 13.4 and the second argument \"getSetCookie\" will only work after\n response.headers?.getSetCookie?.() ??\n response.headers?.get?.('set-cookie') ??\n [];\n\n const newSetCookie = CookieManager.modifySetCookie(cookieHeader, isSecured) ?? [];\n const [session, decodedJwt, refreshToken] = await createSessionFromAccessTokenOnEdge(data);\n\n if (!session) {\n return {\n session: undefined,\n headers: {\n 'set-cookie': newSetCookie.join(', '),\n },\n };\n }\n\n const cookieValue = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n req,\n });\n newSetCookie.push(...cookieValue);\n\n return {\n session: {\n accessToken: data.accessToken ?? data.access_token,\n user: decodedJwt,\n refreshToken,\n },\n headers: {\n 'set-cookie': newSetCookie.join(', '),\n },\n };\n}\n\nexport async function createSessionFromAccessTokenOnEdge(data: any): Promise<[string, any, string] | []> {\n const accessToken = data.accessToken ?? data.access_token;\n const refreshToken = data.refreshToken ?? data.refresh_token;\n const { payload: decodedJwt }: any = await JwtManager.verify(accessToken);\n decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);\n\n const tokens = { accessToken, refreshToken };\n const session = await encryptionEdge.sealTokens(tokens, decodedJwt.exp);\n return [session, decodedJwt, refreshToken];\n}\n"],"mappings":";;;;;;;;AAEA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,IAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,eAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,IAAA,GAAAL,sBAAA,CAAAC,OAAA;AACA,IAAAK,eAAA,GAAAN,sBAAA,CAAAC,OAA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,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC;EAE9E,MAAMC,MAAM,GAAG;IAAEb,WAAW;IAAET;EAAa,CAAC;EAC5C,MAAMZ,OAAO,GAAG,MAAMmC,uBAAc,CAACC,UAAU,CAACF,MAAM,EAAEvB,UAAU,CAACO,GAAG,CAAC;EACvE,OAAO,CAAClB,OAAO,EAAEW,UAAU,EAAEC,YAAY,CAAC;AAC5C","ignoreList":[]}
1
+ {"version":3,"file":"refreshAccessTokenIfNeededOnEdge.js","names":["_cookies","_interopRequireDefault","require","_config","_api","_fronteggLogger","_jwt","_encryptionEdge","logger","fronteggLogger","child","tag","refreshAccessTokenIfNeededOnEdge","req","_ref","_ref2","_response$headers$raw","_response$headers","_response$headers$raw2","_response$headers2","_response$headers2$ge","_response$headers3","_response$headers3$ge","_CookieManager$modify","_data$accessToken","refreshCookie","CookieManager","getRefreshCookieFromRequestEdge","info","undefined","reqHeaders","headers","forEach","value","key","clientId","config","clientSecret","response","isHostedLogin","api","refreshTokenHostedLogin","refreshTokenEmbedded","e","error","isSecured","isSSL","ok","cookiesToRemove","getRequestCookiesHeaderToRemove","cookieDomain","session","join","data","json","cookieHeader","raw","call","getSetCookie","get","newSetCookie","modifySetCookie","decodedJwt","refreshToken","createSessionFromAccessTokenOnEdge","cookieValue","create","expires","Date","exp","secure","push","forwardedHeaders","cookie","name","split","set","accessToken","access_token","user","_data$accessToken2","_data$refreshToken","refresh_token","payload","JwtManager","verify","expiresIn","Math","floor","now","tokens","encryptionEdge","sealTokens"],"sources":["../../../../packages/nextjs/src/edge/refreshAccessTokenIfNeededOnEdge.ts"],"sourcesContent":["import { FronteggEdgeSession } from '../types';\nimport type { IncomingMessage } from 'http';\nimport CookieManager from '../utils/cookies';\nimport config from '../config';\nimport api from '../api';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport JwtManager from '../utils/jwt';\nimport encryptionEdge from '../utils/encryption-edge';\n\nconst logger = fronteggLogger.child({ tag: 'EdgeRuntime.refreshAccessTokenIfNeededOnEdge' });\n\nexport async function refreshAccessTokenIfNeededOnEdge(\n req: IncomingMessage | Request\n): Promise<FronteggEdgeSession | undefined> {\n const refreshCookie = CookieManager.getRefreshCookieFromRequestEdge(req);\n if (!refreshCookie) {\n logger.info('No refresh cookie found, No session found');\n return undefined;\n }\n\n logger.info('going to refresh token');\n\n const reqHeaders = req.headers as any as Map<string, string>;\n const headers: Record<string, string> = {};\n reqHeaders.forEach((value: string, key: string) => {\n headers[key] = value;\n });\n const clientId = config.clientId;\n const clientSecret = config.clientSecret;\n\n let response: Response | null;\n try {\n if (config.isHostedLogin) {\n response = await api.refreshTokenHostedLogin(headers, refreshCookie, clientId, clientSecret);\n } else {\n response = await api.refreshTokenEmbedded(headers);\n }\n } catch (e) {\n logger.error('Failed to refresh token', e);\n return undefined;\n }\n\n const isSecured = config.isSSL;\n if (response === null || !response.ok) {\n const cookiesToRemove = CookieManager.getRequestCookiesHeaderToRemove({\n cookieDomain: config.cookieDomain,\n isSecured,\n req,\n });\n if (cookiesToRemove) {\n return {\n session: undefined,\n headers: {\n 'set-cookie': cookiesToRemove.join(', '),\n },\n };\n }\n return undefined;\n }\n\n const data = await response.json();\n\n const cookieHeader: string[] =\n // @ts-ignore the first argument \"raw\" will only work before nextjs 13.4 and the second argument \"getSetCookie\" will only work after\n response.headers?.raw?.()['set-cookie'] ??\n // @ts-ignore the first argument \"raw\" will only work before nextjs 13.4 and the second argument \"getSetCookie\" will only work after\n response.headers?.getSetCookie?.() ??\n response.headers?.get?.('set-cookie') ??\n [];\n\n const newSetCookie = CookieManager.modifySetCookie(cookieHeader, isSecured) ?? [];\n const [session, decodedJwt, refreshToken] = await createSessionFromAccessTokenOnEdge(data);\n\n if (!session) {\n return {\n session: undefined,\n headers: {\n 'set-cookie': newSetCookie.join(', '),\n },\n };\n }\n\n const cookieValue = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n req,\n });\n newSetCookie.push(...cookieValue);\n\n const forwardedHeaders = req.headers as Headers;\n newSetCookie.forEach((cookie) => {\n // get cookie name and value only\n const [name, value] = cookie.split(';')[0].split('=');\n forwardedHeaders.set('cookie', `${name}=${value}`);\n });\n return {\n session: {\n accessToken: data.accessToken ?? data.access_token,\n user: decodedJwt,\n refreshToken,\n },\n headers: {\n 'set-cookie': newSetCookie.join(', '),\n },\n forwardedHeaders,\n };\n}\n\nexport async function createSessionFromAccessTokenOnEdge(data: any): Promise<[string, any, string] | []> {\n const accessToken = data.accessToken ?? data.access_token;\n const refreshToken = data.refreshToken ?? data.refresh_token;\n const { payload: decodedJwt }: any = await JwtManager.verify(accessToken);\n decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);\n\n const tokens = { accessToken, refreshToken };\n const session = await encryptionEdge.sealTokens(tokens, decodedJwt.exp);\n return [session, decodedJwt, refreshToken];\n}\n"],"mappings":";;;;;;;;AAEA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,IAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,eAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,IAAA,GAAAL,sBAAA,CAAAC,OAAA;AACA,IAAAK,eAAA,GAAAN,sBAAA,CAAAC,OAAA;AAEA,MAAMM,MAAM,GAAGC,uBAAc,CAACC,KAAK,CAAC;EAAEC,GAAG,EAAE;AAA+C,CAAC,CAAC;AAErF,eAAeC,gCAAgCA,CACpDC,GAA8B,EACY;EAAA,IAAAC,IAAA,EAAAC,KAAA,EAAAC,qBAAA,EAAAC,iBAAA,EAAAC,sBAAA,EAAAC,kBAAA,EAAAC,qBAAA,EAAAC,kBAAA,EAAAC,qBAAA,EAAAC,qBAAA,EAAAC,iBAAA;EAC1C,MAAMC,aAAa,GAAGC,gBAAa,CAACC,+BAA+B,CAACd,GAAG,CAAC;EACxE,IAAI,CAACY,aAAa,EAA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AI,CAAC;EAE9E,MAAMC,MAAM,GAAG;IAAEb,WAAW;IAAEd;EAAa,CAAC;EAC5C,MAAMZ,OAAO,GAAG,MAAMwC,uBAAc,CAACC,UAAU,CAACF,MAAM,EAAE5B,UAAU,CAACO,GAAG,CAAC;EACvE,OAAO,CAAClB,OAAO,EAAEW,UAAU,EAAEC,YAAY,CAAC;AAC5C","ignoreList":[]}
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- /** @license Frontegg v9.2.1-alpha.12073075767
1
+ /** @license Frontegg v9.2.1-alpha.12811360407
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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@frontegg/nextjs",
3
3
  "libName": "FronteggNextJs",
4
- "version": "9.2.1-alpha.12073075767",
4
+ "version": "9.2.1-alpha.12811360407",
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": "7.33.0",
31
- "@frontegg/react-hooks": "7.33.0",
30
+ "@frontegg/js": "7.50.0",
31
+ "@frontegg/react-hooks": "7.50.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,6 +5,6 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _default = exports.default = {
8
- version: '9.2.1-alpha.12073075767'
8
+ version: '9.2.1-alpha.12811360407'
9
9
  };
10
10
  //# sourceMappingURL=sdkVersion.js.map
package/sdkVersion.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdkVersion.js","names":["version"],"sources":["../../../packages/nextjs/src/sdkVersion.ts"],"sourcesContent":["export default { version: '9.2.1-alpha.12073075767' };\n"],"mappings":";;;;;;iCAAe;EAAEA,OAAO,EAAE;AAA0B,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"sdkVersion.js","names":["version"],"sources":["../../../packages/nextjs/src/sdkVersion.ts"],"sourcesContent":["export default { version: '9.2.1-alpha.12811360407' };\n"],"mappings":";;;;;;iCAAe;EAAEA,OAAO,EAAE;AAA0B,CAAC","ignoreList":[]}
package/types/index.d.ts CHANGED
@@ -18,6 +18,7 @@ export interface FronteggNextJSSession extends FronteggUserTokens {
18
18
  export interface FronteggEdgeSession {
19
19
  session?: FronteggNextJSSession;
20
20
  headers?: Record<string, string>;
21
+ forwardedHeaders?: Headers;
21
22
  }
22
23
  export type RequestType = IncomingMessage | Request;
23
24
  export interface AccountEnvironment {
@@ -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 interface FronteggEdgeSession {\n session?: FronteggNextJSSession;\n headers?: Record<string, string>;\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 AllUserData {\n user?: ILoginResponse | null;\n tenants?: ITenantsResponse[] | null;\n activeTenant?: ITenantsResponse;\n session?: FronteggNextJSSession | null;\n}\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 FronteggProviderOptions extends Omit<FronteggAppOptions, 'contextOptions'>, AllUserData {\n envAppUrl: string;\n envBaseUrl: string;\n envClientId: string;\n shouldRequestAuthorize?: boolean;\n isSSG?: boolean;\n envAppId?: string;\n secureJwtEnabled?: boolean;\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\n interface ProcessEnv {\n FRONTEGG_BASE_URL: string;\n PORT?: string;\n PWD: string;\n }\n}\n"],"mappings":"","ignoreList":[]}
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 interface FronteggEdgeSession {\n session?: FronteggNextJSSession;\n headers?: Record<string, string>;\n forwardedHeaders?: Headers;\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 AllUserData {\n user?: ILoginResponse | null;\n tenants?: ITenantsResponse[] | null;\n activeTenant?: ITenantsResponse;\n session?: FronteggNextJSSession | null;\n}\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 FronteggProviderOptions extends Omit<FronteggAppOptions, 'contextOptions'>, AllUserData {\n envAppUrl: string;\n envBaseUrl: string;\n envClientId: string;\n shouldRequestAuthorize?: boolean;\n isSSG?: boolean;\n envAppId?: string;\n secureJwtEnabled?: boolean;\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\n interface ProcessEnv {\n FRONTEGG_BASE_URL: string;\n PORT?: string;\n PWD: string;\n }\n}\n"],"mappings":"","ignoreList":[]}