@frontegg/nextjs 6.7.20 → 6.7.21-alpha.4441481917

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +19 -37
  3. package/api/index.d.ts +19 -0
  4. package/api/index.js +78 -0
  5. package/api/index.js.map +1 -0
  6. package/api/package.json +6 -0
  7. package/api/urls.d.ts +33 -0
  8. package/api/urls.js +46 -0
  9. package/api/urls.js.map +1 -0
  10. package/api/utils.d.ts +46 -0
  11. package/api/utils.js +108 -0
  12. package/api/utils.js.map +1 -0
  13. package/app/ClientFronteggProvider.d.ts +3 -0
  14. package/app/ClientFronteggProvider.js +25 -0
  15. package/app/ClientFronteggProvider.js.map +1 -0
  16. package/app/FronteggAppProvider.d.ts +4 -0
  17. package/app/FronteggAppProvider.js +17 -0
  18. package/app/FronteggAppProvider.js.map +1 -0
  19. package/{client → app}/FronteggAppRouter.d.ts +11 -10
  20. package/app/FronteggAppRouter.js +31 -0
  21. package/app/FronteggAppRouter.js.map +1 -0
  22. package/app/helpers.d.ts +5 -0
  23. package/app/helpers.js +32 -0
  24. package/app/helpers.js.map +1 -0
  25. package/app/index.d.ts +4 -0
  26. package/app/index.js +4 -0
  27. package/app/index.js.map +1 -0
  28. package/app/package.json +6 -0
  29. package/common/{client/AppContext.d.ts → AppContext.d.ts} +4 -4
  30. package/common/AppContext.js +6 -0
  31. package/common/AppContext.js.map +1 -0
  32. package/{AuthorizedContent.d.ts → common/AuthorizedContent.d.ts} +9 -8
  33. package/common/AuthorizedContent.js +48 -0
  34. package/common/AuthorizedContent.js.map +1 -0
  35. package/common/{client/FronteggBaseProvider.d.ts → FronteggBaseProvider.d.ts} +3 -3
  36. package/common/FronteggBaseProvider.js +67 -0
  37. package/common/FronteggBaseProvider.js.map +1 -0
  38. package/common/FronteggRouterBase.d.ts +9 -0
  39. package/common/FronteggRouterBase.js +42 -0
  40. package/common/FronteggRouterBase.js.map +1 -0
  41. package/common/helpers.d.ts +3 -9
  42. package/common/helpers.js +24 -0
  43. package/common/helpers.js.map +1 -0
  44. package/common/index.d.ts +4 -6
  45. package/common/index.js +5 -10
  46. package/common/index.js.map +1 -1
  47. package/common/package.json +6 -0
  48. package/common/useRequestAuthorizeSSR.d.ts +5 -0
  49. package/common/useRequestAuthorizeSSR.js +24 -0
  50. package/common/useRequestAuthorizeSSR.js.map +1 -0
  51. package/config/constants.d.ts +57 -0
  52. package/config/constants.js +13 -0
  53. package/config/constants.js.map +1 -0
  54. package/config/helpers.d.ts +28 -0
  55. package/config/helpers.js +87 -0
  56. package/config/helpers.js.map +1 -0
  57. package/config/index.d.ts +24 -0
  58. package/config/index.js +82 -0
  59. package/config/index.js.map +1 -0
  60. package/config/package.json +6 -0
  61. package/config/types.d.ts +18 -0
  62. package/config/types.js +2 -0
  63. package/config/types.js.map +1 -0
  64. package/edge/getSessionOnEdge.d.ts +3 -2
  65. package/edge/getSessionOnEdge.js +8 -0
  66. package/edge/getSessionOnEdge.js.map +1 -0
  67. package/edge/index.d.ts +3 -2
  68. package/edge/index.js +4 -64
  69. package/edge/index.js.map +1 -1
  70. package/edge/package.json +6 -0
  71. package/edge/redirectToLogin.d.ts +2 -0
  72. package/edge/redirectToLogin.js +9 -0
  73. package/edge/redirectToLogin.js.map +1 -0
  74. package/edge/shouldBypassMiddleware.d.ts +21 -7
  75. package/edge/shouldBypassMiddleware.js +42 -0
  76. package/edge/shouldBypassMiddleware.js.map +1 -0
  77. package/index.d.ts +7 -11
  78. package/index.js +13 -1401
  79. package/index.js.map +1 -1
  80. package/middleware/FronteggApiMiddleware.d.ts +8 -0
  81. package/middleware/FronteggApiMiddleware.js +28 -0
  82. package/middleware/FronteggApiMiddleware.js.map +1 -0
  83. package/middleware/FronteggProxy.d.ts +4 -0
  84. package/middleware/FronteggProxy.js +24 -0
  85. package/middleware/FronteggProxy.js.map +1 -0
  86. package/middleware/ProxyRequestCallback.d.ts +13 -0
  87. package/middleware/ProxyRequestCallback.js +48 -0
  88. package/middleware/ProxyRequestCallback.js.map +1 -0
  89. package/middleware/ProxyResponseCallback.d.ts +13 -0
  90. package/middleware/ProxyResponseCallback.js +103 -0
  91. package/middleware/ProxyResponseCallback.js.map +1 -0
  92. package/middleware/constants.d.ts +8 -0
  93. package/middleware/constants.js +9 -0
  94. package/middleware/constants.js.map +1 -0
  95. package/{common/FronteggProxy.d.ts → middleware/helpers.d.ts} +13 -26
  96. package/middleware/helpers.js +35 -0
  97. package/middleware/helpers.js.map +1 -0
  98. package/middleware/index.d.ts +23 -0
  99. package/middleware/index.js +24 -0
  100. package/middleware/index.js.map +1 -0
  101. package/middleware/package.json +6 -0
  102. package/no-ssr/ExpireInListener.d.ts +2 -0
  103. package/no-ssr/ExpireInListener.js +22 -0
  104. package/no-ssr/ExpireInListener.js.map +1 -0
  105. package/{FronteggProviderNoSSR.d.ts → no-ssr/FronteggProviderNoSSR.d.ts} +4 -4
  106. package/no-ssr/FronteggProviderNoSSR.js +76 -0
  107. package/no-ssr/FronteggProviderNoSSR.js.map +1 -0
  108. package/no-ssr/index.d.ts +2 -0
  109. package/no-ssr/index.js +2 -0
  110. package/no-ssr/index.js.map +1 -0
  111. package/no-ssr/package.json +6 -0
  112. package/package.json +6 -7
  113. package/pages/FronteggPagesProvider/index.d.ts +4 -0
  114. package/pages/FronteggPagesProvider/index.js +24 -0
  115. package/pages/FronteggPagesProvider/index.js.map +1 -0
  116. package/pages/FronteggPagesProvider/package.json +6 -0
  117. package/{FronteggRouter.d.ts → pages/FronteggRouter/FronteggRouter.d.ts} +6 -5
  118. package/pages/FronteggRouter/FronteggRouter.js +38 -0
  119. package/pages/FronteggRouter/FronteggRouter.js.map +1 -0
  120. package/pages/FronteggRouter/index.d.ts +26 -0
  121. package/pages/FronteggRouter/index.js +27 -0
  122. package/pages/FronteggRouter/index.js.map +1 -0
  123. package/pages/FronteggRouter/package.json +6 -0
  124. package/{session.d.ts → pages/helpers.d.ts} +10 -10
  125. package/pages/helpers.js +31 -0
  126. package/pages/helpers.js.map +1 -0
  127. package/pages/index.d.ts +3 -0
  128. package/pages/index.js +4 -0
  129. package/pages/index.js.map +1 -0
  130. package/pages/package.json +6 -0
  131. package/pages/withFronteggApp/index.d.ts +2 -0
  132. package/pages/withFronteggApp/index.js +2 -0
  133. package/pages/withFronteggApp/index.js.map +1 -0
  134. package/pages/withFronteggApp/package.json +6 -0
  135. package/pages/withFronteggApp/types.d.ts +12 -0
  136. package/pages/withFronteggApp/types.js +2 -0
  137. package/pages/withFronteggApp/types.js.map +1 -0
  138. package/pages/withFronteggApp/withFronteggApp.d.ts +2 -0
  139. package/pages/withFronteggApp/withFronteggApp.js +62 -0
  140. package/pages/withFronteggApp/withFronteggApp.js.map +1 -0
  141. package/sdkVersion.d.ts +4 -4
  142. package/sdkVersion.js +4 -0
  143. package/sdkVersion.js.map +1 -0
  144. package/{common/types.d.ts → types/index.d.ts} +80 -74
  145. package/types/index.js +2 -0
  146. package/types/index.js.map +1 -0
  147. package/types/package.json +6 -0
  148. package/utils/common/constants.d.ts +12 -0
  149. package/utils/common/constants.js +14 -0
  150. package/utils/common/constants.js.map +1 -0
  151. package/utils/common/index.d.ts +15 -0
  152. package/utils/common/index.js +26 -0
  153. package/utils/common/index.js.map +1 -0
  154. package/utils/common/package.json +6 -0
  155. package/utils/cookies/constants.d.ts +7 -0
  156. package/utils/cookies/constants.js +8 -0
  157. package/utils/cookies/constants.js.map +1 -0
  158. package/utils/cookies/helpers.d.ts +25 -0
  159. package/utils/cookies/helpers.js +53 -0
  160. package/utils/cookies/helpers.js.map +1 -0
  161. package/utils/cookies/index.d.ts +45 -0
  162. package/utils/cookies/index.js +232 -0
  163. package/utils/cookies/index.js.map +1 -0
  164. package/utils/cookies/package.json +6 -0
  165. package/utils/cookies/serializer.d.ts +22 -0
  166. package/utils/cookies/serializer.js +154 -0
  167. package/utils/cookies/serializer.js.map +1 -0
  168. package/utils/cookies/types.d.ts +31 -0
  169. package/utils/cookies/types.js +2 -0
  170. package/utils/cookies/types.js.map +1 -0
  171. package/utils/createSession/index.d.ts +2 -0
  172. package/utils/createSession/index.js +44 -0
  173. package/utils/createSession/index.js.map +1 -0
  174. package/utils/createSession/package.json +6 -0
  175. package/utils/encryption/index.d.ts +3 -0
  176. package/utils/encryption/index.js +29 -0
  177. package/utils/encryption/index.js.map +1 -0
  178. package/utils/encryption/package.json +6 -0
  179. package/utils/encryption-edge/index.d.ts +3 -0
  180. package/utils/encryption-edge/index.js +29 -0
  181. package/utils/encryption-edge/index.js.map +1 -0
  182. package/utils/encryption-edge/package.json +6 -0
  183. package/utils/errors/FronteggEnvNotFound.d.ts +3 -0
  184. package/utils/errors/FronteggEnvNotFound.js +8 -0
  185. package/utils/errors/FronteggEnvNotFound.js.map +1 -0
  186. package/utils/errors/InvalidFronteggEnv.d.ts +3 -0
  187. package/utils/errors/InvalidFronteggEnv.js +8 -0
  188. package/utils/errors/InvalidFronteggEnv.js.map +1 -0
  189. package/utils/errors/index.d.ts +2 -0
  190. package/utils/errors/index.js +3 -0
  191. package/utils/errors/index.js.map +1 -0
  192. package/utils/errors/package.json +6 -0
  193. package/utils/fetchUserData/index.d.ts +7 -0
  194. package/utils/fetchUserData/index.js +49 -0
  195. package/utils/fetchUserData/index.js.map +1 -0
  196. package/utils/fetchUserData/package.json +6 -0
  197. package/utils/fronteggLogger/constants.d.ts +13 -0
  198. package/utils/fronteggLogger/constants.js +20 -0
  199. package/utils/fronteggLogger/constants.js.map +1 -0
  200. package/utils/fronteggLogger/index.d.ts +17 -0
  201. package/utils/fronteggLogger/index.js +61 -0
  202. package/utils/fronteggLogger/index.js.map +1 -0
  203. package/utils/fronteggLogger/package.json +6 -0
  204. package/{common/client/createOrGetFronteggApp.d.ts → utils/initializeFronteggApp/index.d.ts} +11 -11
  205. package/utils/initializeFronteggApp/index.js +100 -0
  206. package/utils/initializeFronteggApp/index.js.map +1 -0
  207. package/utils/initializeFronteggApp/package.json +6 -0
  208. package/utils/jwt/index.d.ts +22 -0
  209. package/utils/jwt/index.js +53 -0
  210. package/utils/jwt/index.js.map +1 -0
  211. package/utils/jwt/package.json +6 -0
  212. package/utils/refreshAccessToken/helpers.d.ts +16 -0
  213. package/utils/refreshAccessToken/helpers.js +69 -0
  214. package/utils/refreshAccessToken/helpers.js.map +1 -0
  215. package/utils/refreshAccessToken/index.d.ts +9 -0
  216. package/utils/refreshAccessToken/index.js +88 -0
  217. package/utils/refreshAccessToken/index.js.map +1 -0
  218. package/utils/refreshAccessToken/package.json +6 -0
  219. package/utils/routing/index.d.ts +5 -0
  220. package/utils/routing/index.js +23 -0
  221. package/utils/routing/index.js.map +1 -0
  222. package/utils/routing/package.json +6 -0
  223. package/utils/useOnRedirectTo/index.d.ts +5 -0
  224. package/utils/useOnRedirectTo/index.js +21 -0
  225. package/utils/useOnRedirectTo/index.js.map +1 -0
  226. package/utils/useOnRedirectTo/package.json +6 -0
  227. package/CookieManager-e50dc144.js +0 -322
  228. package/CookieManager-e50dc144.js.map +0 -1
  229. package/FronteggClientProviderNext13-b3c1e7a0.js +0 -158
  230. package/FronteggClientProviderNext13-b3c1e7a0.js.map +0 -1
  231. package/FronteggMiddleware.d.ts +0 -15
  232. package/FronteggProvider.d.ts +0 -3
  233. package/api-25516652.js +0 -58
  234. package/api-25516652.js.map +0 -1
  235. package/client/FronteggClientProviderNext13.d.ts +0 -3
  236. package/client/index.d.ts +0 -2
  237. package/client/index.js +0 -64
  238. package/client/index.js.map +0 -1
  239. package/common/CookieManager.d.ts +0 -41
  240. package/common/FronteggConfig.d.ts +0 -31
  241. package/common/api.d.ts +0 -3
  242. package/common/client/ExpireInListener.d.ts +0 -2
  243. package/common/client/hooks/index.d.ts +0 -1
  244. package/common/client/hooks/useRequestAuthorizeSSR.d.ts +0 -5
  245. package/common/client/index.d.ts +0 -4
  246. package/common/consts.d.ts +0 -6
  247. package/common/createGetSession.d.ts +0 -7
  248. package/common/utils.d.ts +0 -1
  249. package/createGetSession-2e1e4506.js +0 -50
  250. package/createGetSession-2e1e4506.js.map +0 -1
  251. package/helpers-dac37998.js +0 -88
  252. package/helpers-dac37998.js.map +0 -1
  253. package/refreshToken.d.ts +0 -3
  254. package/server/FronteggProviderNext13.d.ts +0 -3
  255. package/server/getSessionNext13.d.ts +0 -4
  256. package/server/index.d.ts +0 -2
  257. package/server/index.js +0 -84
  258. package/server/index.js.map +0 -1
  259. package/withFronteggApp.d.ts +0 -11
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["LEVEL_NAMES","LEVELS","isGithubRunnerDebugMode","process","env","ACTIONS_STEP_DEBUG","ACTIONS_RUNNER_DEBUG","logLevel","FRONTEGG_LOG_LEVEL","Object","keys","indexOf","maxTagLength","repeat","num","Array","map","join","FronteggLogger","constructor","options","tag","level","length","slice","prepare","printLevel","args","levelName","Date","toISOString","debug","console","apply","info","warn","error","child"],"sources":["../../../../../packages/nextjs/src/utils/fronteggLogger/index.ts"],"sourcesContent":["import { LEVEL_NAMES, LEVELS } from './constants';\n\n/**\n * @see [enabling-debug-logging](https://docs.github.com/en/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging)\n * in GitHub actions in failed tests for more debugging logs\n */\nconst isGithubRunnerDebugMode =\n process.env.ACTIONS_STEP_DEBUG === 'true' || process.env.ACTIONS_RUNNER_DEBUG === 'true';\n\nlet logLevel: keyof typeof LEVEL_NAMES = 'warn';\nif (process.env.FRONTEGG_LOG_LEVEL) {\n logLevel = process.env.FRONTEGG_LOG_LEVEL as keyof typeof LEVEL_NAMES;\n}\nif (isGithubRunnerDebugMode) {\n logLevel = 'debug';\n}\nif (Object.keys(LEVEL_NAMES).indexOf(logLevel) === -1) {\n logLevel = 'warn';\n}\n\ntype FronteggLoggerOptions = {\n tag: string;\n level?: keyof typeof LEVEL_NAMES;\n};\n\nconst maxTagLength = 25;\n\nfunction repeat(num: number) {\n return [...new Array(num)].map(() => ' ').join('');\n}\n\nclass FronteggLogger {\n private readonly tag: string;\n private readonly level: keyof typeof LEVEL_NAMES;\n\n constructor(options: FronteggLoggerOptions) {\n if (options.tag.length > maxTagLength) {\n this.tag = options.tag.slice(0, 7) + '...' + options.tag.slice(options.tag.length - maxTagLength + 10);\n } else {\n this.tag = repeat(maxTagLength - options.tag.length) + options.tag;\n }\n\n this.level = options.level ?? logLevel;\n }\n\n private prepare(printLevel: keyof typeof LEVEL_NAMES, args: any[]) {\n const levelName = LEVELS[LEVEL_NAMES[printLevel]];\n return [new Date().toISOString(), `|${levelName}| ${this.tag}:`, ...args];\n }\n\n debug(...args: any[]) {\n if (LEVEL_NAMES[this.level] <= LEVEL_NAMES.debug) {\n console.debug.apply(console, this.prepare('debug', args));\n }\n }\n\n info(...args: any[]) {\n if (LEVEL_NAMES[this.level] <= LEVEL_NAMES.info) {\n console.info.apply(console, this.prepare('info', args));\n }\n }\n\n warn(...args: any[]) {\n if (LEVEL_NAMES[this.level] <= LEVEL_NAMES.warn) {\n console.warn.apply(console, this.prepare('warn', args));\n }\n }\n\n error(...args: any[]) {\n console.error.apply(console, this.prepare('error', args));\n }\n\n static child(options: FronteggLoggerOptions): FronteggLogger {\n return new FronteggLogger(options);\n }\n}\n\nexport default FronteggLogger;\n"],"mappings":"AAAA,SAASA,WAAW,EAAEC,MAAM,QAAQ,aAAa;;AAEjD;AACA;AACA;AACA;AACA,MAAMC,uBAAuB,GAC3BC,OAAO,CAACC,GAAG,CAACC,kBAAkB,KAAK,MAAM,IAAIF,OAAO,CAACC,GAAG,CAACE,oBAAoB,KAAK,MAAM;AAE1F,IAAIC,QAAkC,GAAG,MAAM;AAC/C,IAAIJ,OAAO,CAACC,GAAG,CAACI,kBAAkB,EAAE;EAClCD,QAAQ,GAAGJ,OAAO,CAACC,GAAG,CAACI,kBAA8C;AACvE;AACA,IAAIN,uBAAuB,EAAE;EAC3BK,QAAQ,GAAG,OAAO;AACpB;AACA,IAAIE,MAAM,CAACC,IAAI,CAACV,WAAW,CAAC,CAACW,OAAO,CAACJ,QAAQ,C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AAE;MAChDC,OAAO,CAACD,KAAK,CAACE,KAAK,CAACD,OAAO,EAAE,IAAI,CAACP,OAAO,CAAC,OAAO,EAAEE,IAAI,CAAC,CAAC;IAC3D;EACF;EAEAO,IAAI,CAAC,GAAGP,IAAW,EAAE;IACnB,IAAI3B,WAAW,CAAC,IAAI,CAACsB,KAAK,CAAC,IAAItB,WAAW,CAACkC,IAAI,EAAE;MAC/CF,OAAO,CAACE,IAAI,CAACD,KAAK,CAACD,OAAO,EAAE,IAAI,CAACP,OAAO,CAAC,MAAM,EAAEE,IAAI,CAAC,CAAC;IACzD;EACF;EAEAQ,IAAI,CAAC,GAAGR,IAAW,EAAE;IACnB,IAAI3B,WAAW,CAAC,IAAI,CAACsB,KAAK,CAAC,IAAItB,WAAW,CAACmC,IAAI,EAAE;MAC/CH,OAAO,CAACG,IAAI,CAACF,KAAK,CAACD,OAAO,EAAE,IAAI,CAACP,OAAO,CAAC,MAAM,EAAEE,IAAI,CAAC,CAAC;IACzD;EACF;EAEAS,KAAK,CAAC,GAAGT,IAAW,EAAE;IACpBK,OAAO,CAACI,KAAK,CAACH,KAAK,CAACD,OAAO,EAAE,IAAI,CAACP,OAAO,CAAC,OAAO,EAAEE,IAAI,CAAC,CAAC;EAC3D;EAEA,OAAOU,KAAK,CAACjB,OAA8B,EAAkB;IAC3D,OAAO,IAAIF,cAAc,CAACE,OAAO,CAAC;EACpC;AACF;AAEA,eAAeF,cAAc"}
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": false,
3
+ "module": "./index.js",
4
+ "main": "./index.js",
5
+ "types": "./index.d.ts"
6
+ }
@@ -1,11 +1,11 @@
1
- import { FronteggApp } from '@frontegg/js';
2
- import { AuthState } from '@frontegg/redux-store';
3
- import { FronteggProviderOptions } from '../types';
4
- type CreateOrGetFronteggAppParams = {
5
- options: FronteggProviderOptions;
6
- onRedirectTo: AuthState['onRedirectTo'];
7
- appName?: string;
8
- storeHolder: any;
9
- };
10
- export declare const createOrGetFronteggApp: ({ options, onRedirectTo, appName, storeHolder, }: CreateOrGetFronteggAppParams) => FronteggApp;
11
- export {};
1
+ import { FronteggApp } from '@frontegg/js';
2
+ import { AuthState } from '@frontegg/redux-store';
3
+ import type { FronteggProviderOptions } from '../../types';
4
+ type CreateOrGetFronteggAppParams = {
5
+ options: FronteggProviderOptions;
6
+ onRedirectTo: AuthState['onRedirectTo'];
7
+ appName?: string;
8
+ storeHolder: any;
9
+ };
10
+ declare const initializeFronteggApp: ({ options, onRedirectTo, appName, storeHolder, }: CreateOrGetFronteggAppParams) => FronteggApp;
11
+ export default initializeFronteggApp;
@@ -0,0 +1,100 @@
1
+ import _extends from "@babel/runtime/helpers/esm/extends";
2
+ import { AppHolder, initialize } from '@frontegg/js';
3
+ import { createFronteggStore, tenantsState as defaultTenantsState } from '@frontegg/redux-store';
4
+ import sdkVersion from '../../sdkVersion';
5
+ import nextjsPkg from 'next/package.json';
6
+ import { isAuthPath, isSocialLoginPath } from '../../api/utils';
7
+ const initializeFronteggApp = ({
8
+ options,
9
+ onRedirectTo,
10
+ appName,
11
+ storeHolder
12
+ }) => {
13
+ var _options$authOptions, _options$authOptions2, _options$hostedLoginB, _options$authOptions$, _options$authOptions3, _options$auditsOption;
14
+ const {
15
+ session,
16
+ user,
17
+ tenants
18
+ } = options;
19
+ const {
20
+ accessToken,
21
+ refreshToken
22
+ } = session != null ? session : {};
23
+ const contextOptions = _extends({
24
+ requestCredentials: 'include'
25
+ }, options.contextOptions, {
26
+ additionalHeadersResolver: async () => {
27
+ var _options$contextOptio;
28
+ const additionalHeaders = [];
29
+ const originalAdditionalHeadersResolver = (_options$contextOptio = options.contextOptions) == null ? void 0 : _options$contextOptio.additionalHeadersResolver;
30
+ if (typeof originalAdditionalHeadersResolver === 'function') {
31
+ try {
32
+ additionalHeaders.push(...(await originalAdditionalHeadersResolver()));
33
+ } catch (e) {
34
+ /** ignore failed additionalHeadersResolver */
35
+ }
36
+ } else if (Array.isArray(originalAdditionalHeadersResolver)) {
37
+ additionalHeaders.push(...originalAdditionalHeadersResolver);
38
+ }
39
+ additionalHeaders.push({
40
+ key: 'x-frontegg-framework',
41
+ value: `next@${nextjsPkg.version}`
42
+ });
43
+ additionalHeaders.push({
44
+ key: 'x-frontegg-sdk',
45
+ value: `@frontegg/nextjs@${sdkVersion.version}`
46
+ });
47
+ return additionalHeaders;
48
+ },
49
+ baseUrl: path => {
50
+ const shouldGoThroughFronteggMiddleWare = isAuthPath(path) && !isSocialLoginPath(path);
51
+ if (shouldGoThroughFronteggMiddleWare) {
52
+ return `${options.envAppUrl}/api`;
53
+ } else {
54
+ return options.envBaseUrl;
55
+ }
56
+ },
57
+ clientId: options.envClientId
58
+ });
59
+ const tenantsState = _extends({}, defaultTenantsState, {
60
+ tenants: tenants || []
61
+ }, (_options$authOptions = options.authOptions) == null ? void 0 : _options$authOptions.tenantsState);
62
+ const userData = user ? _extends({}, user, {
63
+ accessToken: accessToken != null ? accessToken : '',
64
+ refreshToken: refreshToken != null ? refreshToken : undefined
65
+ }, (_options$authOptions2 = options.authOptions) == null ? void 0 : _options$authOptions2.user) : null;
66
+ const authOptions = _extends({}, options.authOptions, {
67
+ onRedirectTo,
68
+ isLoading: false,
69
+ isAuthenticated: !!options.session,
70
+ hostedLoginBox: (_options$hostedLoginB = options.hostedLoginBox) != null ? _options$hostedLoginB : false,
71
+ disableSilentRefresh: (_options$authOptions$ = (_options$authOptions3 = options.authOptions) == null ? void 0 : _options$authOptions3.disableSilentRefresh) != null ? _options$authOptions$ : true,
72
+ user: userData,
73
+ tenantsState
74
+ });
75
+ const sharedStore = createFronteggStore({
76
+ context: contextOptions
77
+ }, storeHolder, options.previewMode, authOptions, {
78
+ auth: authOptions != null ? authOptions : {},
79
+ audits: (_options$auditsOption = options.auditsOptions) != null ? _options$auditsOption : {}
80
+ }, false, options.urlStrategy);
81
+ let createdApp;
82
+ try {
83
+ createdApp = AppHolder.getInstance(appName != null ? appName : 'default');
84
+ createdApp.store = sharedStore;
85
+ } catch (e) {
86
+ var _options$hostedLoginB2, _options$customLoginB;
87
+ createdApp = initialize(_extends({}, options, {
88
+ store: sharedStore,
89
+ hostedLoginBox: (_options$hostedLoginB2 = options.hostedLoginBox) != null ? _options$hostedLoginB2 : false,
90
+ customLoginBox: (_options$customLoginB = options.customLoginBox) != null ? _options$customLoginB : false,
91
+ basename: options.basename,
92
+ authOptions,
93
+ contextOptions,
94
+ onRedirectTo
95
+ }), appName != null ? appName : 'default');
96
+ }
97
+ return createdApp;
98
+ };
99
+ export default initializeFronteggApp;
100
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["AppHolder","initialize","createFronteggStore","tenantsState","defaultTenantsState","sdkVersion","nextjsPkg","isAuthPath","isSocialLoginPath","initializeFronteggApp","options","onRedirectTo","appName","storeHolder","session","user","tenants","accessToken","refreshToken","contextOptions","requestCredentials","additionalHeadersResolver","additionalHeaders","originalAdditionalHeadersResolver","push","e","Array","isArray","key","value","version","baseUrl","path","shouldGoThroughFronteggMiddleWare","envAppUrl","envBaseUrl","clientId","envClientId","authOptions","userData","undefined","isLoading","isAuthenticated","hostedLoginBox","disableSilentRefresh","sharedStore","context","previewMode","auth","audits","auditsOptions","urlStrategy","createdApp","getInstance","store","customLoginBox","basename"],"sources":["../../../../../packages/nextjs/src/utils/initializeFronteggApp/index.ts"],"sourcesContent":["import { AppHolder, FronteggApp, initialize } from '@frontegg/js';\nimport { createFronteggStore, AuthState, tenantsState as defaultTenantsState } from '@frontegg/redux-store';\nimport { KeyValuePair } from '@frontegg/rest-api';\nimport { FronteggAppOptions } from '@frontegg/types';\nimport sdkVersion from '../../sdkVersion';\nimport type { FronteggProviderOptions } from '../../types';\nimport nextjsPkg from 'next/package.json';\nimport { isAuthPath, isSocialLoginPath } from '../../api/utils';\n\ntype CreateOrGetFronteggAppParams = {\n options: FronteggProviderOptions;\n onRedirectTo: AuthState['onRedirectTo'];\n appName?: string;\n storeHolder: any;\n};\n\nconst initializeFronteggApp = ({\n options,\n onRedirectTo,\n appName,\n storeHolder,\n}: CreateOrGetFronteggAppParams): FronteggApp => {\n const { session, user, tenants } = options;\n const { accessToken, refreshToken } = session ?? {};\n\n const contextOptions: FronteggAppOptions['contextOptions'] = {\n requestCredentials: 'include' as RequestCredentials,\n ...options.contextOptions,\n additionalHeadersResolver: async () => {\n const additionalHeaders: KeyValuePair[] = [];\n const originalAdditionalHeadersResolver = options.contextOptions?.additionalHeadersResolver;\n if (typeof originalAdditionalHeadersResolver === 'function') {\n try {\n additionalHeaders.push(...(await originalAdditionalHeadersResolver()));\n } catch (e) {\n /** ignore failed additionalHeadersResolver */\n }\n } else if (Array.isArray(originalAdditionalHeadersResolver)) {\n additionalHeaders.push(...(originalAdditionalHeadersResolver as KeyValuePair[]));\n }\n additionalHeaders.push({\n key: 'x-frontegg-framework',\n value: `next@${nextjsPkg.version}`,\n });\n additionalHeaders.push({\n key: 'x-frontegg-sdk',\n value: `@frontegg/nextjs@${sdkVersion.version}`,\n });\n return additionalHeaders;\n },\n baseUrl: (path: string) => {\n const shouldGoThroughFronteggMiddleWare = isAuthPath(path) && !isSocialLoginPath(path);\n if (shouldGoThroughFronteggMiddleWare) {\n return `${options.envAppUrl}/api`;\n } else {\n return options.envBaseUrl;\n }\n },\n clientId: options.envClientId,\n };\n\n const tenantsState = {\n ...defaultTenantsState,\n tenants: tenants || [],\n ...options.authOptions?.tenantsState,\n };\n const userData = user\n ? {\n ...user,\n accessToken: accessToken ?? '',\n refreshToken: refreshToken ?? undefined,\n ...options.authOptions?.user,\n }\n : null;\n\n const authOptions: FronteggAppOptions['authOptions'] = {\n ...options.authOptions,\n onRedirectTo,\n isLoading: false,\n isAuthenticated: !!options.session,\n hostedLoginBox: options.hostedLoginBox ?? false,\n disableSilentRefresh: options.authOptions?.disableSilentRefresh ?? true,\n user: userData,\n tenantsState,\n };\n\n const sharedStore = createFronteggStore(\n { context: contextOptions },\n storeHolder,\n options.previewMode,\n authOptions,\n {\n auth: authOptions ?? {},\n audits: options.auditsOptions ?? {},\n },\n false,\n options.urlStrategy\n );\n\n let createdApp;\n try {\n createdApp = AppHolder.getInstance(appName ?? 'default');\n createdApp.store = sharedStore;\n } catch (e) {\n createdApp = initialize(\n {\n ...options,\n store: sharedStore,\n hostedLoginBox: options.hostedLoginBox ?? false,\n customLoginBox: options.customLoginBox ?? false,\n basename: options.basename,\n authOptions,\n contextOptions,\n onRedirectTo,\n },\n appName ?? 'default'\n );\n }\n return createdApp;\n};\n\nexport default initializeFronteggApp;\n"],"mappings":";AAAA,SAASA,SAAS,EAAeC,UAAU,QAAQ,cAAc;AACjE,SAASC,mBAAmB,EAAaC,YAAY,IAAIC,mBAAmB,QAAQ,uBAAuB;AAG3G,OAAOC,UAAU,MAAM,kBAAkB;AAEzC,OAAOC,SAAS,MAAM,mBAAmB;AACzC,SAASC,UAAU,EAAEC,iBAAiB,QAAQ,iBAAiB;AAS/D,MAAMC,qBAAqB,GAAG,CAAC;EAC7BC,OAAO;EACPC,YAAY;EACZC,OAAO;EACPC;AAC4B,CAAC,KAAkB;EAAA;EAC/C,MAAM;IAAEC,OAAO;IAAEC,IAAI;IAAEC;EAAQ,CAAC,GAAGN,OAAO;EAC1C,MAAM;IAAEO,WAAW;IAAEC;EAAa,CAAC,GAAGJ,OAAO,WAAPA,OAAO,GAAI,CAAC,CAAC;EAEnD,MAAMK,cAAoD;IACxDC,kBAAkB,EAAE;EAA+B,GAChDV,OAAO,CAACS,cAAc;IACzBE,yBAAyB,EAAE,YAAY;MAAA;MACrC,MAAMC,iBAAiC,GAAG,EAAE;MAC5C,MAAMC,iCAAiC,4BAAGb,OAAO,CAACS,cAAc,qBAAtB,sBAAwBE,yBAAyB;MAC3F,IAAI,OAAOE,iCAAiC,KAAK,UAAU,EAAE;QAC3D,IAAI;UACFD,iBAAiB,CAACE,IAAI,CAAC,IAAI,MAAMD,iCAAiC,EAAE,CAAC,CAAC;QACxE,CAAC,CAAC,OAAOE,CAAC,EAAE;UACV;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OAAO,CAACI,OAAO;IAClC6B,cAAc,2BAAEjC,OAAO,CAACiC,cAAc,oCAAI,KAAK;IAC/CC,oBAAoB,oDAAElC,OAAO,CAAC4B,WAAW,qBAAnB,sBAAqBM,oBAAoB,oCAAI,IAAI;IACvE7B,IAAI,EAAEwB,QAAQ;IACdpC;EAAY,EACb;EAED,MAAM0C,WAAW,GAAG3C,mBAAmB,CACrC;IAAE4C,OAAO,EAAE3B;EAAe,CAAC,EAC3BN,WAAW,EACXH,OAAO,CAACqC,WAAW,EACnBT,WAAW,EACX;IACEU,IAAI,EAAEV,WAAW,WAAXA,WAAW,GAAI,CAAC,CAAC;IACvBW,MAAM,2BAAEvC,OAAO,CAACwC,aAAa,oCAAI,CAAC;EACpC,CAAC,EACD,KAAK,EACLxC,OAAO,CAACyC,WAAW,CACpB;EAED,IAAIC,UAAU;EACd,IAAI;IACFA,UAAU,GAAGpD,SAAS,CAACqD,WAAW,CAACzC,OAAO,WAAPA,OAAO,GAAI,SAAS,CAAC;IACxDwC,UAAU,CAACE,KAAK,GAAGT,WAAW;EAChC,CAAC,CAAC,OAAOpB,CAAC,EAAE;IAAA;IACV2B,UAAU,GAAGnD,UAAU,cAEhBS,OAAO;MACV4C,KAAK,EAAET,WAAW;MAClBF,cAAc,4BAAEjC,OAAO,CAACiC,cAAc,qCAAI,KAAK;MAC/CY,cAAc,2BAAE7C,OAAO,CAAC6C,cAAc,oCAAI,KAAK;MAC/CC,QAAQ,EAAE9C,OAAO,CAAC8C,QAAQ;MAC1BlB,WAAW;MACXnB,cAAc;MACdR;IAAY,IAEdC,OAAO,WAAPA,OAAO,GAAI,SAAS,CACrB;EACH;EACA,OAAOwC,UAAU;AACnB,CAAC;AAED,eAAe3C,qBAAqB"}
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": false,
3
+ "module": "./index.js",
4
+ "main": "./index.js",
5
+ "types": "./index.d.ts"
6
+ }
@@ -0,0 +1,22 @@
1
+ import type { JWTVerifyResult } from 'jose/dist/types/types';
2
+ declare class JwtUtils {
3
+ private publicKey;
4
+ /**
5
+ * Get the JWT public key from Frontegg service
6
+ * to verify user's access token when calling getSession
7
+ * in getServerSideProps and ServerComponents
8
+ * @private
9
+ */
10
+ private loadPublicKey;
11
+ /**
12
+ * Load public key from Frontegg services if not cached
13
+ * @private
14
+ */
15
+ private getPublicKey;
16
+ /**
17
+ * verify JWT token with current loaded public key from Frontegg services
18
+ */
19
+ verify(jwt: string | Uint8Array): Promise<JWTVerifyResult>;
20
+ }
21
+ declare const _default: JwtUtils;
22
+ export default _default;
@@ -0,0 +1,53 @@
1
+ import { importJWK, jwtVerify } from 'jose';
2
+ import api from '../../api';
3
+ import fronteggLogger from '../fronteggLogger';
4
+ import config from '../../config';
5
+ class JwtUtils {
6
+ constructor() {
7
+ this.publicKey = void 0;
8
+ }
9
+ /**
10
+ * Get the JWT public key from Frontegg service
11
+ * to verify user's access token when calling getSession
12
+ * in getServerSideProps and ServerComponents
13
+ * @private
14
+ */
15
+ async loadPublicKey() {
16
+ const logger = fronteggLogger.child({
17
+ tag: 'JwtManager.loadPublicKey'
18
+ });
19
+ let publicKey;
20
+ try {
21
+ var _config$jwtPublicKeyJ;
22
+ publicKey = JSON.parse((_config$jwtPublicKeyJ = config.jwtPublicKeyJson) != null ? _config$jwtPublicKeyJ : '{}');
23
+ logger.info('Public key loaded from env variable');
24
+ } catch (e) {
25
+ logger.info('Going to load public key from frontegg jwks');
26
+ publicKey = await api.loadPublicKey();
27
+ }
28
+ logger.info('Importing Public key into jose');
29
+ this.publicKey = await importJWK(publicKey, publicKey.alg);
30
+ return this.publicKey;
31
+ }
32
+
33
+ /**
34
+ * Load public key from Frontegg services if not cached
35
+ * @private
36
+ */
37
+ async getPublicKey() {
38
+ if (this.publicKey === undefined) {
39
+ return await this.loadPublicKey();
40
+ }
41
+ return this.publicKey;
42
+ }
43
+
44
+ /**
45
+ * verify JWT token with current loaded public key from Frontegg services
46
+ */
47
+ async verify(jwt) {
48
+ const publicKey = await this.getPublicKey();
49
+ return await jwtVerify(jwt, publicKey);
50
+ }
51
+ }
52
+ export default new JwtUtils();
53
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["importJWK","jwtVerify","api","fronteggLogger","config","JwtUtils","publicKey","loadPublicKey","logger","child","tag","JSON","parse","jwtPublicKeyJson","info","e","alg","getPublicKey","undefined","verify","jwt"],"sources":["../../../../../packages/nextjs/src/utils/jwt/index.ts"],"sourcesContent":["import type { KeyLike } from 'jose';\nimport { importJWK, jwtVerify } from 'jose';\nimport api from '../../api';\nimport type { JWTVerifyResult } from 'jose/dist/types/types';\nimport fronteggLogger from '../fronteggLogger';\nimport config from '../../config';\n\nclass JwtUtils {\n private publicKey: (KeyLike | Uint8Array) | undefined;\n\n /**\n * Get the JWT public key from Frontegg service\n * to verify user's access token when calling getSession\n * in getServerSideProps and ServerComponents\n * @private\n */\n private async loadPublicKey(): Promise<KeyLike | Uint8Array> {\n const logger = fronteggLogger.child({ tag: 'JwtManager.loadPublicKey' });\n\n let publicKey;\n try {\n publicKey = JSON.parse(config.jwtPublicKeyJson ?? '{}');\n logger.info('Public key loaded from env variable');\n } catch (e) {\n logger.info('Going to load public key from frontegg jwks');\n publicKey = await api.loadPublicKey();\n }\n logger.info('Importing Public key into jose');\n this.publicKey = await importJWK(publicKey, publicKey.alg);\n return this.publicKey;\n }\n\n /**\n * Load public key from Frontegg services if not cached\n * @private\n */\n private async getPublicKey(): Promise<KeyLike | Uint8Array> {\n if (this.publicKey === undefined) {\n return await this.loadPublicKey();\n }\n return this.publicKey;\n }\n\n /**\n * verify JWT token with current loaded public key from Frontegg services\n */\n async verify(jwt: string | Uint8Array): Promise<JWTVerifyResult> {\n const publicKey = await this.getPublicKey();\n return await jwtVerify(jwt, publicKey);\n }\n}\n\nexport default new JwtUtils();\n"],"mappings":"AACA,SAASA,SAAS,EAAEC,SAAS,QAAQ,MAAM;AAC3C,OAAOC,GAAG,MAAM,WAAW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": "./index.d.ts"
6
+ }
@@ -0,0 +1,16 @@
1
+ import { IncomingMessage } from 'http';
2
+ export declare function hasRefreshTokenCookie(cookies: Record<string, any>): boolean;
3
+ export declare function refreshAccessTokenEmbedded(request: IncomingMessage): Promise<Response | null>;
4
+ export declare function refreshAccessTokenHostedLogin(request: IncomingMessage): Promise<Response | null>;
5
+ /**
6
+ * If url starts with /_next/ means that the user trying to navigate
7
+ * to a new nextjs page, in this scenario no need to refresh token
8
+ * we can just return the actual stateless session from
9
+ * the encrypted cookie
10
+ */
11
+ export declare function isRuntimeNextRequest(url: string): boolean;
12
+ /**
13
+ * If url starts with '/oauth/callback' means that the user navigated back
14
+ * from frontegg hosted login, in this scenario no need to refresh token
15
+ */
16
+ export declare function isOauthCallback(url: string): boolean;
@@ -0,0 +1,69 @@
1
+ import fronteggLogger from '../fronteggLogger';
2
+ import CookieManager from '../cookies';
3
+ import api from '../../api';
4
+ import { getTokensFromCookie } from '../../common';
5
+ export function hasRefreshTokenCookie(cookies) {
6
+ const logger = fronteggLogger.child({
7
+ tag: 'refreshToken.hasRefreshTokenCookie'
8
+ });
9
+ const refreshTokenKey = CookieManager.refreshTokenKey;
10
+ logger.debug(`Checking if '${refreshTokenKey}' exists in cookies`);
11
+ const cookieKey = Object.keys(cookies).find(cookie => {
12
+ return cookie.replace(/-/g, '') === refreshTokenKey;
13
+ });
14
+ const exists = cookieKey != null;
15
+ logger.debug(`Cookie '${refreshTokenKey}' ${exists ? 'exists' : 'NOT exists'} in cookies`);
16
+ return exists;
17
+ }
18
+ export async function refreshAccessTokenEmbedded(request) {
19
+ const logger = fronteggLogger.child({
20
+ tag: 'refreshToken.refreshAccessTokenEmbedded'
21
+ });
22
+ const headers = request.headers;
23
+ const cookies = request.cookies;
24
+ logger.info('check if has refresh token headers');
25
+ if (hasRefreshTokenCookie(cookies)) {
26
+ logger.info('going to refresh token (embedded mode)');
27
+ return await api.refreshTokenEmbedded(headers);
28
+ }
29
+ return null;
30
+ }
31
+ export async function refreshAccessTokenHostedLogin(request) {
32
+ const logger = fronteggLogger.child({
33
+ tag: 'refreshToken.refreshAccessTokenHostedLogin'
34
+ });
35
+ const headers = request.headers;
36
+ logger.info('trying to get token from cookies');
37
+ const sealFromCookies = CookieManager.getSessionCookieFromRequest(request);
38
+ try {
39
+ const tokens = await getTokensFromCookie(sealFromCookies);
40
+ if (!(tokens != null && tokens.refreshToken)) {
41
+ logger.info('refresh token not found');
42
+ return null;
43
+ }
44
+ logger.info('going to refresh token (hosted-login mode)');
45
+ return await api.refreshTokenHostedLogin(headers, tokens.refreshToken);
46
+ } catch (e) {
47
+ logger.error(e);
48
+ return null;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * If url starts with /_next/ means that the user trying to navigate
54
+ * to a new nextjs page, in this scenario no need to refresh token
55
+ * we can just return the actual stateless session from
56
+ * the encrypted cookie
57
+ */
58
+ export function isRuntimeNextRequest(url) {
59
+ return url.startsWith('/_next/');
60
+ }
61
+
62
+ /**
63
+ * If url starts with '/oauth/callback' means that the user navigated back
64
+ * from frontegg hosted login, in this scenario no need to refresh token
65
+ */
66
+ export function isOauthCallback(url) {
67
+ return url.startsWith('/oauth/callback');
68
+ }
69
+ //# sourceMappingURL=helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.js","names":["fronteggLogger","CookieManager","api","getTokensFromCookie","hasRefreshTokenCookie","cookies","logger","child","tag","refreshTokenKey","debug","cookieKey","Object","keys","find","cookie","replace","exists","refreshAccessTokenEmbedded","request","headers","info","refreshTokenEmbedded","refreshAccessTokenHostedLogin","sealFromCookies","getSessionCookieFromRequest","tokens","refreshToken","refreshTokenHostedLogin","e","error","isRuntimeNextRequest","url","startsWith","isOauthCallback"],"sources":["../../../../../packages/nextjs/src/utils/refreshAccessToken/helpers.ts"],"sourcesContent":["import fronteggLogger from '../fronteggLogger';\nimport CookieManager from '../cookies';\nimport { NextApiRequest } from 'next/dist/shared/lib/utils';\nimport api from '../../api';\nimport { getTokensFromCookie } from '../../common';\nimport { IncomingMessage } from 'http';\n\nexport function hasRefreshTokenCookie(cookies: Record<string, any>): boolean {\n const logger = fronteggLogger.child({ tag: 'refreshToken.hasRefreshTokenCookie' });\n const refreshTokenKey = CookieManager.refreshTokenKey;\n logger.debug(`Checking if '${refreshTokenKey}' exists in cookies`);\n const cookieKey = Object.keys(cookies).find((cookie) => {\n return cookie.replace(/-/g, '') === refreshTokenKey;\n });\n const exists: boolean = cookieKey != null;\n logger.debug(`Cookie '${refreshTokenKey}' ${exists ? 'exists' : 'NOT exists'} in cookies`);\n return exists;\n}\n\nexport async function refreshAccessTokenEmbedded(request: IncomingMessage): Promise<Response | null> {\n const logger = fronteggLogger.child({ tag: 'refreshToken.refreshAccessTokenEmbedded' });\n\n const headers = request.headers as Record<string, string>;\n const cookies = (request as NextApiRequest).cookies;\n\n logger.info('check if has refresh token headers');\n if (hasRefreshTokenCookie(cookies)) {\n logger.info('going to refresh token (embedded mode)');\n return await api.refreshTokenEmbedded(headers);\n }\n return null;\n}\n\nexport async function refreshAccessTokenHostedLogin(request: IncomingMessage): Promise<Response | null> {\n const logger = fronteggLogger.child({ tag: 'refreshToken.refreshAccessTokenHostedLogin' });\n const headers = request.headers as Record<string, string>;\n logger.info('trying to get token from cookies');\n\n const sealFromCookies = CookieManager.getSessionCookieFromRequest(request);\n try {\n const tokens = await getTokensFromCookie(sealFromCookies);\n if (!tokens?.refreshToken) {\n logger.info('refresh token not found');\n return null;\n }\n\n logger.info('going to refresh token (hosted-login mode)');\n return await api.refreshTokenHostedLogin(headers, tokens.refreshToken);\n } catch (e) {\n logger.error(e);\n return null;\n }\n}\n\n/**\n * If url starts with /_next/ means that the user trying to navigate\n * to a new nextjs page, in this scenario no need to refresh token\n * we can just return the actual stateless session from\n * the encrypted cookie\n */\nexport function isRuntimeNextRequest(url: string): boolean {\n return url.startsWith('/_next/');\n}\n\n/**\n * If url starts with '/oauth/callback' means that the user navigated back\n * from frontegg hosted login, in this scenario no need to refresh token\n */\n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OAAO,IAAI;AACb;AAEA,OAAO,eAAeG,6BAA6B,CAACJ,OAAwB,EAA4B;EACtG,MAAMb,MAAM,GAAGN,cAAc,CAACO,KAAK,CAAC;IAAEC,GAAG,EAAE;EAA6C,CAAC,CAAC;EAC1F,MAAMY,OAAO,GAAGD,OAAO,CAACC,OAAiC;EACzDd,MAAM,CAACe,IAAI,CAAC,kCAAkC,CAAC;EAE/C,MAAMG,eAAe,GAAGvB,aAAa,CAACwB,2BAA2B,CAACN,OAAO,CAAC;EAC1E,IAAI;IACF,MAAMO,MAAM,GAAG,MAAMvB,mBAAmB,CAACqB,eAAe,CAAC;IACzD,IAAI,EAACE,MAAM,YAANA,MAAM,CAAEC,YAAY,GAAE;MACzBrB,MAAM,CAACe,IAAI,CAAC,yBAAyB,CAAC;MACtC,OAAO,IAAI;IACb;IAEAf,MAAM,CAACe,IAAI,CAAC,4CAA4C,CAAC;IACzD,OAAO,MAAMnB,GAAG,CAAC0B,uBAAuB,CAACR,OAAO,EAAEM,MAAM,CAACC,YAAY,CAAC;EACxE,CAAC,CAAC,OAAOE,CAAC,EAAE;IACVvB,MAAM,CAACwB,KAAK,CAACD,CAAC,CAAC;IACf,OAAO,IAAI;EACb;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,oBAAoB,CAACC,GAAW,EAAW;EACzD,OAAOA,GAAG,CAACC,UAAU,CAAC,SAAS,CAAC;AAClC;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAe,CAACF,GAAW,EAAW;EACpD,OAAOA,GAAG,CAACC,UAAU,CAAC,iBAAiB,CAAC;AAC1C"}
@@ -0,0 +1,9 @@
1
+ import type { NextPageContext } from 'next/dist/shared/lib/utils';
2
+ import type { FronteggNextJSSession } from '../../types';
3
+ /**
4
+ * Refreshes the access token for the current session.
5
+ *
6
+ * @param {NextPageContext} ctx - The Next.js Page Context object.
7
+ * @returns {Promise<FronteggNextJSSession | null>} A Promise that resolves to the updated session object, or `null` if the refresh failed.
8
+ */
9
+ export default function refreshAccessToken(ctx: NextPageContext): Promise<FronteggNextJSSession | null>;
@@ -0,0 +1,88 @@
1
+ import { createSessionFromAccessToken } from '../../common';
2
+ import config from '../../config';
3
+ import CookieManager from '../cookies';
4
+ import { isOauthCallback, isRuntimeNextRequest, refreshAccessTokenEmbedded, refreshAccessTokenHostedLogin } from './helpers';
5
+ import fronteggLogger from '../fronteggLogger';
6
+ import encryption from '../encryption';
7
+ import createSession from '../createSession';
8
+
9
+ /**
10
+ * Refreshes the access token for the current session.
11
+ *
12
+ * @param {NextPageContext} ctx - The Next.js Page Context object.
13
+ * @returns {Promise<FronteggNextJSSession | null>} A Promise that resolves to the updated session object, or `null` if the refresh failed.
14
+ */
15
+ export default async function refreshAccessToken(ctx) {
16
+ const logger = fronteggLogger.child({
17
+ tag: 'refreshAccessToken'
18
+ });
19
+ logger.info(`Refreshing token by for PageContext ${ctx.pathname}`);
20
+ const nextJsRequest = ctx.req;
21
+ const nextJsResponse = ctx.res;
22
+ const url = nextJsRequest == null ? void 0 : nextJsRequest.url;
23
+ if (!nextJsResponse || !nextJsRequest || !url) {
24
+ logger.debug(`abandon refreshToken due to PageContext.req = null`);
25
+ return null;
26
+ }
27
+ try {
28
+ var _response$headers, _response$headers$raw, _CookieManager$modify, _ctx$res, _data$accessToken;
29
+ logger.info(`Check if should request made from first application load`);
30
+ if (isRuntimeNextRequest(url)) {
31
+ logger.debug(`Detect runtime next.js request, resolving existing session from cookies if exists`);
32
+ const cookies = CookieManager.getSessionCookieFromRequest(nextJsRequest);
33
+ const session = await createSession(cookies, encryption);
34
+ if (session) {
35
+ logger.debug(`session resolved from session cookie`);
36
+ return session;
37
+ } else {
38
+ logger.info('Failed to resolve session from cookie, going to refresh token');
39
+ }
40
+ }
41
+ if (isOauthCallback(url)) {
42
+ /* Prevent refresh token due to oauth login callback */
43
+ logger.debug(`abandon refreshToken for url='/oauth/callback'`);
44
+ return null;
45
+ }
46
+ let response;
47
+ if (config.isHostedLogin) {
48
+ response = await refreshAccessTokenHostedLogin(nextJsRequest);
49
+ } else {
50
+ response = await refreshAccessTokenEmbedded(nextJsRequest);
51
+ }
52
+ const isSecured = config.isSSL;
53
+ if (response === null || !response.ok) {
54
+ CookieManager.removeCookies({
55
+ cookieDomain: config.cookieDomain,
56
+ isSecured,
57
+ req: nextJsRequest,
58
+ res: nextJsResponse
59
+ });
60
+ return null;
61
+ }
62
+ const data = await response.json();
63
+
64
+ // @ts-ignore
65
+ const cookieHeader = (_response$headers = response.headers) == null ? void 0 : (_response$headers$raw = _response$headers.raw) == null ? void 0 : _response$headers$raw.call(_response$headers)['set-cookie'];
66
+ const newSetCookie = (_CookieManager$modify = CookieManager.modifySetCookie(cookieHeader, isSecured)) != null ? _CookieManager$modify : [];
67
+ const [session, decodedJwt, refreshToken] = await createSessionFromAccessToken(data);
68
+ if (!session) {
69
+ return null;
70
+ }
71
+ const cookieValue = CookieManager.create({
72
+ value: session,
73
+ expires: new Date(decodedJwt.exp * 1000),
74
+ secure: isSecured
75
+ });
76
+ newSetCookie.push(...cookieValue);
77
+ (_ctx$res = ctx.res) == null ? void 0 : _ctx$res.setHeader('set-cookie', newSetCookie);
78
+ return {
79
+ accessToken: (_data$accessToken = data.accessToken) != null ? _data$accessToken : data.access_token,
80
+ user: decodedJwt,
81
+ refreshToken
82
+ };
83
+ } catch (e) {
84
+ logger.error('[refreshToken] Failed to create session e', e);
85
+ return null;
86
+ }
87
+ }
88
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["createSessionFromAccessToken","config","CookieManager","isOauthCallback","isRuntimeNextRequest","refreshAccessTokenEmbedded","refreshAccessTokenHostedLogin","fronteggLogger","encryption","createSession","refreshAccessToken","ctx","logger","child","tag","info","pathname","nextJsRequest","req","nextJsResponse","res","url","debug","cookies","getSessionCookieFromRequest","session","response","isHostedLogin","isSecured","isSSL","ok","removeCookies","cookieDomain","data","json","cookieHeader","headers","raw","newSetCookie","modifySetCookie","decodedJwt","refreshToken","cookieValue","create","value","expires","Date","exp","secure","push","setHeader","accessToken","access_token","user","e","error"],"sources":["../../../../../packages/nextjs/src/utils/refreshAccessToken/index.ts"],"sourcesContent":["import type { NextPageContext } from 'next/dist/shared/lib/utils';\nimport type { FronteggNextJSSession } from '../../types';\nimport { createSessionFromAccessToken } from '../../common';\nimport config from '../../config';\nimport CookieManager from '../cookies';\nimport {\n isOauthCallback,\n isRuntimeNextRequest,\n refreshAccessTokenEmbedded,\n refreshAccessTokenHostedLogin,\n} from './helpers';\nimport fronteggLogger from '../fronteggLogger';\nimport encryption from '../encryption';\nimport createSession from '../createSession';\n\n/**\n * Refreshes the access token for the current session.\n *\n * @param {NextPageContext} ctx - The Next.js Page Context object.\n * @returns {Promise<FronteggNextJSSession | null>} A Promise that resolves to the updated session object, or `null` if the refresh failed.\n */\nexport default async function refreshAccessToken(ctx: NextPageContext): Promise<FronteggNextJSSession | null> {\n const logger = fronteggLogger.child({ tag: 'refreshAccessToken' });\n logger.info(`Refreshing token by for PageContext ${ctx.pathname}`);\n const nextJsRequest = ctx.req;\n const nextJsResponse = ctx.res;\n const url = nextJsRequest?.url;\n if (!nextJsResponse || !nextJsRequest || !url) {\n logger.debug(`abandon refreshToken due to PageContext.req = null`);\n return null;\n }\n\n try {\n logger.info(`Check if should request made from first application load`);\n\n if (isRuntimeNextRequest(url)) {\n logger.debug(`Detect runtime next.js request, resolving existing session from cookies if exists`);\n\n const cookies = CookieManager.getSessionCookieFromRequest(nextJsRequest);\n const session = await createSession(cookies, encryption);\n\n if (session) {\n logger.debug(`session resolved from session cookie`);\n return session;\n } else {\n logger.info('Failed to resolve session from cookie, going to refresh token');\n }\n }\n\n if (isOauthCallback(url)) {\n /* Prevent refresh token due to oauth login callback */\n logger.debug(`abandon refreshToken for url='/oauth/callback'`);\n return null;\n }\n\n let response: Response | null;\n if (config.isHostedLogin) {\n response = await refreshAccessTokenHostedLogin(nextJsRequest);\n } else {\n response = await refreshAccessTokenEmbedded(nextJsRequest);\n }\n\n const isSecured = config.isSSL;\n if (response === null || !response.ok) {\n CookieManager.removeCookies({\n cookieDomain: config.cookieDomain,\n isSecured,\n req: nextJsRequest,\n res: nextJsResponse,\n });\n return null;\n }\n\n const data = await response.json();\n\n // @ts-ignore\n const cookieHeader = response.headers?.raw?.()['set-cookie'];\n const newSetCookie = CookieManager.modifySetCookie(cookieHeader, isSecured) ?? [];\n const [session, decodedJwt, refreshToken] = await createSessionFromAccessToken(data);\n\n if (!session) {\n return null;\n }\n const cookieValue = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n newSetCookie.push(...cookieValue);\n ctx.res?.setHeader('set-cookie', newSetCookie);\n\n return {\n accessToken: data.accessToken ?? data.access_token,\n user: decodedJwt,\n refreshToken,\n };\n } catch (e) {\n logger.error('[refreshToken] Failed to create session e', e);\n return null;\n }\n}\n"],"mappings":"AAEA,SAASA,4BAA4B,QAAQ,cAAc;AAC3D,OAAOC,MAAM,MAAM,cAAc;AACjC,OAAOC,aAAa,MAAM,YAAY;AACtC,SACEC,eAAe,EACfC,oBAAoB,EACpBC,0BAA0B,EAC1BC,6BAA6B,QACxB,WAAW;AAClB,OAAOC,cAAc,MAAM,mBAAmB;AAC9C,OAAOC,UAAU,MAAM,eAAe;AACtC,OAAOC,aAAa,MAAM,kBAAkB;;AAE5C;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,eAAeC,kBAAkB,CAACC,GAAoB,EAAyC;EAC5G,MAAMC,MAAM,GAAGL,cAAc,CAACM,KAAK,CAAC;IAAEC,GAAG,EAAE;EAAqB,CAAC,CAAC;EAClEF,MAAM,CAACG,IAAI,CAAE,uCAAsCJ,GAAG,CAACK,QAAS,EAAC,CAAC;EAClE,MAAMC,aAAa,GAAGN,GAAG,CAACO,GAAG;EAC7B,MAAMC,cAAc,GAAGR,GAAG,CAACS,GAAG;EAC9B,MAAMC,GAAG,GAAGJ,aAAa,oBAAbA,aA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A,MAAMc,IAAI,GAAG,MAAMP,QAAQ,CAACQ,IAAI,EAAE;;IAElC;IACA,MAAMC,YAAY,wBAAGT,QAAQ,CAACU,OAAO,8CAAhB,kBAAkBC,GAAG,qBAArB,6CAAyB,CAAC,YAAY,CAAC;IAC5D,MAAMC,YAAY,4BAAGpC,aAAa,CAACqC,eAAe,CAACJ,YAAY,EAAEP,SAAS,CAAC,oCAAI,EAAE;IACjF,MAAM,CAACH,OAAO,EAAEe,UAAU,EAAEC,YAAY,CAAC,GAAG,MAAMzC,4BAA4B,CAACiC,IAAI,CAAC;IAEpF,IAAI,CAACR,OAAO,EAAE;MACZ,OAAO,IAAI;IACb;IACA,MAAMiB,WAAW,GAAGxC,aAAa,CAACyC,MAAM,CAAC;MACvCC,KAAK,EAAEnB,OAAO;MACdoB,OAAO,EAAE,IAAIC,IAAI,CAACN,UAAU,CAACO,GAAG,GAAG,IAAI,CAAC;MACxCC,MAAM,EAAEpB;IACV,CAAC,CAAC;IACFU,YAAY,CAACW,IAAI,CAAC,GAAGP,WAAW,CAAC;IACjC,YAAA/B,GAAG,CAACS,GAAG,qBAAP,SAAS8B,SAAS,CAAC,YAAY,EAAEZ,YAAY,CAAC;IAE9C,OAAO;MACLa,WAAW,uBAAElB,IAAI,CAACkB,WAAW,gCAAIlB,IAAI,CAACmB,YAAY;MAClDC,IAAI,EAAEb,UAAU;MAChBC;IACF,CAAC;EACH,CAAC,CAAC,OAAOa,CAAC,EAAE;IACV1C,MAAM,CAAC2C,KAAK,CAAC,2CAA2C,EAAED,CAAC,CAAC;IAC5D,OAAO,IAAI;EACb;AACF"}
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": false,
3
+ "module": "./index.js",
4
+ "main": "./index.js",
5
+ "types": "./index.d.ts"
6
+ }
@@ -0,0 +1,5 @@
1
+ export declare function getAuthRoutes(): {
2
+ routesArr: string[];
3
+ routesObj: Record<string, string>;
4
+ };
5
+ export declare function isAuthRoute(pathname: string): boolean;
@@ -0,0 +1,23 @@
1
+ import _extends from "@babel/runtime/helpers/esm/extends";
2
+ import { authInitialState } from '@frontegg/redux-store';
3
+ import config from '../../config';
4
+ export function getAuthRoutes() {
5
+ const routesObj = _extends({}, authInitialState.routes, config.authRoutes);
6
+ const routesArr = Object.keys(routesObj).reduce((p, key) => [...p, routesObj[key]], []);
7
+ return {
8
+ routesArr,
9
+ routesObj
10
+ };
11
+ }
12
+ export function isAuthRoute(pathname) {
13
+ const {
14
+ routesArr,
15
+ routesObj
16
+ } = getAuthRoutes();
17
+ if (config.fronteggAppOptions.hostedLoginBox) {
18
+ return routesObj.loginUrl === pathname || routesObj.logoutUrl === pathname || routesObj.hostedLoginRedirectUrl === pathname;
19
+ } else {
20
+ return routesArr.indexOf(pathname) !== -1;
21
+ }
22
+ }
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["authInitialState","config","getAuthRoutes","routesObj","routes","authRoutes","routesArr","Object","keys","reduce","p","key","isAuthRoute","pathname","fronteggAppOptions","hostedLoginBox","loginUrl","logoutUrl","hostedLoginRedirectUrl","indexOf"],"sources":["../../../../../packages/nextjs/src/utils/routing/index.ts"],"sourcesContent":["import { authInitialState } from '@frontegg/redux-store';\nimport config from '../../config';\n\nexport function getAuthRoutes(): { routesArr: string[]; routesObj: Record<string, string> } {\n const routesObj = {\n ...authInitialState.routes,\n ...config.authRoutes,\n };\n const routesArr: string[] = Object.keys(routesObj).reduce(\n (p: string[], key: string) => [...p, (routesObj as any)[key]],\n []\n );\n return { routesArr, routesObj };\n}\n\nexport function isAuthRoute(pathname: string): boolean {\n const { routesArr, routesObj } = getAuthRoutes();\n\n if (config.fronteggAppOptions.hostedLoginBox) {\n return (\n routesObj.loginUrl === pathname ||\n routesObj.logoutUrl === pathname ||\n routesObj.hostedLoginRedirectUrl === pathname\n );\n } else {\n return routesArr.indexOf(pathname) !== -1;\n }\n}\n"],"mappings":";AAAA,SAASA,gBAAgB,QAAQ,uBAAuB;AACxD,OAAOC,MAAM,MAAM,cAAc;AAEjC,OAAO,SAASC,aAAa,GAA+D;EAC1F,MAAMC,SAAS,gBACVH,gBAAgB,CAACI,MAAM,EACvBH,MAAM,CAACI,UAAU,CACrB;EACD,MAAMC,SAAmB,GAAGC,MAAM,CAACC,IAAI,CAACL,SAAS,CAAC,CAACM,MAAM,CACvD,CAACC,CAAW,EAAEC,GAAW,KAAK,CAAC,GAAGD,CAAC,EAAGP,SAAS,CAASQ,GAAG,CAAC,CAAC,EAC7D,EAAE,CACH;EACD,OAAO;IAAEL,SAAS;IAAEH;EAAU,CAAC;AACjC;AAEA,OAAO,SAASS,WAAW,CAACC,QAAgB,EAAW;EACrD,MAAM;IAAEP,SAAS;IAAEH;EAAU,CAAC,GAAGD,aAAa,EAAE;EAEhD,IAAID,MAAM,CAACa,kBAAkB,CAACC,cAAc,EAAE;IAC5C,OACEZ,SAAS,CAACa,QAAQ,KAAKH,QAAQ,IAC/BV,SAAS,CAACc,SAAS,KAAKJ,QAAQ,IAChCV,SAAS,CAACe,sBAAsB,KAAKL,QAAQ;EAEjD,CAAC,MAAM;IACL,OAAOP,SAAS,CAACa,OAAO,CAACN,QAAQ,CAAC,KAAK,CAAC,CAAC;EAC3C;AACF"}
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": false,
3
+ "module": "./index.js",
4
+ "main": "./index.js",
5
+ "types": "./index.d.ts"
6
+ }
@@ -0,0 +1,5 @@
1
+ import { RedirectOptions } from '@frontegg/rest-api';
2
+ import type { NextRouter } from 'next/router';
3
+ import type { AppRouterInstance } from 'next/dist/shared/lib/app-router-context';
4
+ declare const useOnRedirectTo: (baseName: string, router: AppRouterInstance | NextRouter) => (_path: string, opts?: RedirectOptions) => void;
5
+ export default useOnRedirectTo;
@@ -0,0 +1,21 @@
1
+ import { useCallback } from 'react';
2
+ const useOnRedirectTo = (baseName, router) => {
3
+ return useCallback((_path, opts) => {
4
+ const isSSR = typeof window == undefined;
5
+ let path = _path;
6
+ if (path.startsWith(baseName)) {
7
+ path = path.substring(baseName.length);
8
+ }
9
+ if (opts != null && opts.preserveQueryParams) {
10
+ path = `${path}${window.location.search}`;
11
+ }
12
+ if (opts != null && opts.refresh && !isSSR) {
13
+ // @ts-ignore
14
+ window.Cypress ? router.push(path) : window.location.href = path;
15
+ } else {
16
+ opts != null && opts.replace ? router.replace(path) : router.push(path);
17
+ }
18
+ }, []);
19
+ };
20
+ export default useOnRedirectTo;
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["useCallback","useOnRedirectTo","baseName","router","_path","opts","isSSR","window","undefined","path","startsWith","substring","length","preserveQueryParams","location","search","refresh","Cypress","push","href","replace"],"sources":["../../../../../packages/nextjs/src/utils/useOnRedirectTo/index.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { RedirectOptions } from '@frontegg/rest-api';\nimport type { NextRouter } from 'next/router';\nimport type { AppRouterInstance } from 'next/dist/shared/lib/app-router-context';\n\nconst useOnRedirectTo = (baseName: string, router: AppRouterInstance | NextRouter) => {\n return useCallback((_path: string, opts?: RedirectOptions) => {\n const isSSR = typeof window == undefined;\n let path = _path;\n if (path.startsWith(baseName)) {\n path = path.substring(baseName.length);\n }\n if (opts?.preserveQueryParams) {\n path = `${path}${window.location.search}`;\n }\n if (opts?.refresh && !isSSR) {\n // @ts-ignore\n window.Cypress ? router.push(path) : (window.location.href = path);\n } else {\n opts?.replace ? router.replace(path) : router.push(path);\n }\n }, []);\n};\n\nexport default useOnRedirectTo;\n"],"mappings":"AAAA,SAASA,WAAW,QAAQ,OAAO;AAKnC,MAAMC,eAAe,GAAG,CAACC,QAAgB,EAAEC,MAAsC,KAAK;EACpF,OAAOH,WAAW,CAAC,CAACI,KAAa,EAAEC,IAAsB,KAAK;IAC5D,MAAMC,KAAK,GAAG,OAAOC,MAAM,IAAIC,SAAS;IACxC,IAAIC,IAAI,GAAGL,KAAK;IAChB,IAAIK,IAAI,CAACC,UAAU,CAACR,QAAQ,CAAC,EAAE;MAC7BO,IAAI,GAAGA,IAAI,CAACE,SAAS,CAACT,QAAQ,CAACU,MAAM,CAAC;IACxC;IACA,IAAIP,IAAI,YAAJA,IAAI,CAAEQ,mBAAmB,EAAE;MAC7BJ,IAAI,GAAI,GAAEA,IAAK,GAAEF,MAAM,CAACO,QAAQ,CAACC,MAAO,EAAC;IAC3C;IACA,IAAIV,IAAI,YAAJA,IAAI,CAAEW,OAAO,IAAI,CAACV,KAAK,EAAE;MAC3B;MACAC,MAAM,CAACU,OAAO,GAAGd,MAAM,CAACe,IAAI,CAACT,IAAI,CAAC,GAAIF,MAAM,CAACO,QAAQ,CAACK,IAAI,GAAGV,IAAK;IACpE,CAAC,MAAM;MACLJ,IAAI,YAAJA,IAAI,CAAEe,OAAO,GAAGjB,MAAM,CAACiB,OAAO,CAACX,IAAI,CAAC,GAAGN,MAAM,CAACe,IAAI,CAACT,IAAI,CAAC;IAC1D;EACF,CAAC,EAAE,EAAE,CAAC;AACR,CAAC;AAED,eAAeR,eAAe"}
@@ -0,0 +1,6 @@
1
+ {
2
+ "sideEffects": false,
3
+ "module": "./index.js",
4
+ "main": "./index.js",
5
+ "types": "./index.d.ts"
6
+ }