@frontegg/nextjs 6.7.20 → 6.7.21-alpha.4441971157

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 +11 -0
  2. package/README.md +19 -37
  3. package/api/index.d.ts +19 -0
  4. package/api/index.js +87 -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 +56 -0
  9. package/api/urls.js.map +1 -0
  10. package/api/utils.d.ts +46 -0
  11. package/api/utils.js +123 -0
  12. package/api/utils.js.map +1 -0
  13. package/app/ClientFronteggProvider.d.ts +3 -0
  14. package/app/ClientFronteggProvider.js +32 -0
  15. package/app/ClientFronteggProvider.js.map +1 -0
  16. package/app/FronteggAppProvider.d.ts +4 -0
  17. package/app/FronteggAppProvider.js +25 -0
  18. package/app/FronteggAppProvider.js.map +1 -0
  19. package/{client → app}/FronteggAppRouter.d.ts +11 -10
  20. package/app/FronteggAppRouter.js +38 -0
  21. package/app/FronteggAppRouter.js.map +1 -0
  22. package/app/helpers.d.ts +5 -0
  23. package/app/helpers.js +43 -0
  24. package/app/helpers.js.map +1 -0
  25. package/app/index.d.ts +4 -0
  26. package/app/index.js +39 -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 +12 -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 +54 -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 +76 -0
  37. package/common/FronteggBaseProvider.js.map +1 -0
  38. package/common/FronteggRouterBase.d.ts +9 -0
  39. package/common/FronteggRouterBase.js +48 -0
  40. package/common/FronteggRouterBase.js.map +1 -0
  41. package/common/helpers.d.ts +3 -9
  42. package/common/helpers.js +32 -0
  43. package/common/helpers.js.map +1 -0
  44. package/common/index.d.ts +4 -6
  45. package/common/index.js +45 -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 +30 -0
  50. package/common/useRequestAuthorizeSSR.js.map +1 -0
  51. package/config/constants.d.ts +57 -0
  52. package/config/constants.js +20 -0
  53. package/config/constants.js.map +1 -0
  54. package/config/helpers.d.ts +28 -0
  55. package/config/helpers.js +97 -0
  56. package/config/helpers.js.map +1 -0
  57. package/config/index.d.ts +24 -0
  58. package/config/index.js +94 -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 +6 -0
  63. package/config/types.js.map +1 -0
  64. package/edge/getSessionOnEdge.d.ts +3 -2
  65. package/edge/getSessionOnEdge.js +16 -0
  66. package/edge/getSessionOnEdge.js.map +1 -0
  67. package/edge/index.d.ts +3 -2
  68. package/edge/index.js +38 -63
  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 +16 -0
  73. package/edge/redirectToLogin.js.map +1 -0
  74. package/edge/shouldBypassMiddleware.d.ts +21 -7
  75. package/edge/shouldBypassMiddleware.js +50 -0
  76. package/edge/shouldBypassMiddleware.js.map +1 -0
  77. package/index.d.ts +7 -11
  78. package/index.js +98 -1392
  79. package/index.js.map +1 -1
  80. package/middleware/FronteggApiMiddleware.d.ts +8 -0
  81. package/middleware/FronteggApiMiddleware.js +34 -0
  82. package/middleware/FronteggApiMiddleware.js.map +1 -0
  83. package/middleware/FronteggProxy.d.ts +4 -0
  84. package/middleware/FronteggProxy.js +31 -0
  85. package/middleware/FronteggProxy.js.map +1 -0
  86. package/middleware/ProxyRequestCallback.d.ts +13 -0
  87. package/middleware/ProxyRequestCallback.js +56 -0
  88. package/middleware/ProxyRequestCallback.js.map +1 -0
  89. package/middleware/ProxyResponseCallback.d.ts +13 -0
  90. package/middleware/ProxyResponseCallback.js +111 -0
  91. package/middleware/ProxyResponseCallback.js.map +1 -0
  92. package/middleware/constants.d.ts +8 -0
  93. package/middleware/constants.js +17 -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 +42 -0
  97. package/middleware/helpers.js.map +1 -0
  98. package/middleware/index.d.ts +23 -0
  99. package/middleware/index.js +13 -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 +29 -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 +84 -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 +13 -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 +32 -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 +46 -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 +19 -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 +40 -0
  126. package/pages/helpers.js.map +1 -0
  127. package/pages/index.d.ts +3 -0
  128. package/pages/index.js +47 -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 +13 -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 +6 -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 +70 -0
  140. package/pages/withFronteggApp/withFronteggApp.js.map +1 -0
  141. package/sdkVersion.d.ts +4 -4
  142. package/sdkVersion.js +11 -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 +6 -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 +23 -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 +32 -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 +15 -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 +64 -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 +239 -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 +161 -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 +6 -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 +51 -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 +37 -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 +37 -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 +15 -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 +15 -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 +28 -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 +56 -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 +28 -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 +67 -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 +108 -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 +61 -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 +80 -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 +94 -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 +31 -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 +28 -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,239 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ var _serializer = _interopRequireDefault(require("./serializer"));
9
+ var _config = _interopRequireDefault(require("../../config"));
10
+ var _constants = require("./constants");
11
+ var _helpers = require("./helpers");
12
+ var _fronteggLogger = _interopRequireDefault(require("../fronteggLogger"));
13
+ class CookieManager {
14
+ constructor() {
15
+ this.getCookieName = (cookieNumber, cookieName = _config.default.cookieName) => cookieNumber ? (0, _helpers.getIndexedCookieName)(cookieNumber, cookieName) : cookieName;
16
+ this.createEmptySingleCookie = (cookieName, isSecured, cookieDomain) => {
17
+ return this.create({
18
+ cookieName,
19
+ value: '',
20
+ expires: new Date(),
21
+ secure: isSecured,
22
+ domain: cookieDomain,
23
+ silent: true
24
+ });
25
+ };
26
+ this.createEmptyCookies = (isSecured, cookieDomain, _cookiesToRemove) => {
27
+ const allEmptyCookies = [];
28
+ const refreshTokenVariants = (0, _helpers.getRefreshTokenCookieNameVariants)();
29
+ const cookiesToRemove = [..._cookiesToRemove, ...refreshTokenVariants];
30
+ cookiesToRemove.forEach(name => {
31
+ allEmptyCookies.push(...this.createEmptySingleCookie(name, isSecured, cookieDomain));
32
+ });
33
+ return allEmptyCookies;
34
+ };
35
+ this.getCookiesToRemove = request => {
36
+ const logger = _fronteggLogger.default.child({
37
+ tag: 'getCookiesToRemove'
38
+ });
39
+ if (!request) {
40
+ return [];
41
+ }
42
+ try {
43
+ logger.info('extract cookie from request headers');
44
+ const cookieStr = (0, _helpers.getCookieHeader)(request);
45
+ const cookies = cookieStr && _serializer.default.parse(cookieStr);
46
+ if (!cookies) {
47
+ return [];
48
+ }
49
+ let cookieNumber = 1;
50
+ const cookieToRemove = [];
51
+ while (cookies[this.getCookieName(cookieNumber)]) {
52
+ cookieToRemove.push(this.getCookieName(cookieNumber));
53
+ cookieNumber++;
54
+ }
55
+ logger.info(`number of cookies to remove: ${cookieToRemove.length}`);
56
+ return cookieToRemove;
57
+ } catch (e) {
58
+ logger.error(e);
59
+ return [];
60
+ }
61
+ };
62
+ this.modifySetCookie = (setCookieValue, isSecured) => {
63
+ const logger = _fronteggLogger.default.child({
64
+ tag: 'CookieManager.modifySetCookie'
65
+ });
66
+ if (!setCookieValue || setCookieValue.length === 0) {
67
+ logger.info(`No headers to modify`);
68
+ return setCookieValue;
69
+ }
70
+ logger.info(`modifying cookie headers (count: ${setCookieValue.length})`);
71
+ return setCookieValue.map(c => {
72
+ let cookie = c.split('; ');
73
+ logger.debug(`modifying cookie ${cookie[0]}, isSecured: ${isSecured}`);
74
+ if (!isSecured) {
75
+ cookie = cookie.filter(property => property !== 'Secure' && property !== 'SameSite=None');
76
+ }
77
+ return cookie.map(property => {
78
+ if (property.toLowerCase() === `domain=${_config.default.baseUrlHost}`) {
79
+ return `Domain=${_config.default.cookieDomain}`;
80
+ }
81
+ return property;
82
+ }).join(';') + ';';
83
+ });
84
+ };
85
+ }
86
+ get refreshTokenKey() {
87
+ return `fe_refresh_${_config.default.clientId}`.replace(/-/g, '');
88
+ }
89
+
90
+ /**
91
+ * Validate and create new cookie headers.
92
+ * The default value of `cookieName` is {@link config.cookieName}
93
+ * @param {CreateCookieOptions} options - Create cookie options
94
+ */
95
+ create(options) {
96
+ var _options$cookieName, _options$httpOnly, _options$domain, _options$path;
97
+ const logger = _fronteggLogger.default.child({
98
+ tag: 'CookieManager.create',
99
+ level: options.silent ? 'error' : undefined
100
+ });
101
+ const cookieName = (_options$cookieName = options.cookieName) != null ? _options$cookieName : _config.default.cookieName;
102
+ const cookieValue = options.value;
103
+ logger.info(`Creating new cookie for '${cookieName}'`);
104
+ const serializeOptions = {
105
+ expires: options.expires,
106
+ httpOnly: (_options$httpOnly = options.httpOnly) != null ? _options$httpOnly : true,
107
+ domain: (_options$domain = options.domain) != null ? _options$domain : _config.default.cookieDomain,
108
+ path: (_options$path = options.path) != null ? _options$path : '/',
109
+ priority: 'high'
110
+ };
111
+ if (options.secure) {
112
+ logger.debug(`Set cookie '${cookieName}' as secure`);
113
+ serializeOptions.secure = options.secure;
114
+ serializeOptions.sameSite = 'none';
115
+ }
116
+ const serializedCookie = _serializer.default.serialize(cookieName, cookieValue, serializeOptions);
117
+ if (serializedCookie.length <= _constants.COOKIE_MAX_LENGTH) {
118
+ logger.info(`Successfully create a cookie header, '${cookieName}'`);
119
+ return [serializedCookie];
120
+ } else {
121
+ logger.debug('Going to split cookie into chunks');
122
+ /** Create chunked cookie headers and store value as array of headers */
123
+ const cookies = (0, _helpers.splitValueToChunks)(cookieName, cookieValue, serializeOptions);
124
+ logger.info(`Successfully create chunked cookie headers, '${cookieName}' (count: ${cookies.length})`);
125
+ return cookies;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Receive incoming http request, and extract the cookie header.
131
+ * @return cookie as string if exists, else empty string
132
+ *
133
+ * @param {RequestType} request - Incoming HTTP Request
134
+ */
135
+ parseCookieHeader(request) {
136
+ const logger = _fronteggLogger.default.child({
137
+ tag: 'CookieManager.parseCookieHeader'
138
+ });
139
+ logger.info('Going to extract all cookies header from request');
140
+ const cookieHeader = (0, _helpers.getCookieHeader)(request);
141
+ logger.info('Parsing cookie header to map');
142
+ return _serializer.default.parse(cookieHeader);
143
+ }
144
+
145
+ /**
146
+ * Loop over cookie headers, extract, parse cookies and merged divided cookies from incoming http request,
147
+ * @return full session cookie headers if exists, else return undefined
148
+ * @param {RequestType} request - Incoming HTTP Request
149
+ */
150
+ getSessionCookieFromRequest(request) {
151
+ const logger = _fronteggLogger.default.child({
152
+ tag: 'CookieManager.getSessionCookieFromRequest'
153
+ });
154
+ logger.info('Going to extract session cookies header from request');
155
+ if (!request) {
156
+ logger.info(`'request' argument is null, Cookie header not found`);
157
+ return undefined;
158
+ }
159
+ logger.debug('Getting cookie header');
160
+ const cookieStr = (0, _helpers.getCookieHeader)(request);
161
+ logger.debug('Parsing cookie header string');
162
+ const cookies = _serializer.default.parse(cookieStr);
163
+ logger.debug('Loop over session cookie headers');
164
+ let i = 1;
165
+ let sessionCookies = '';
166
+ let sessionCookieChunk = cookies[this.getCookieName()];
167
+ if (sessionCookieChunk === undefined) {
168
+ do {
169
+ sessionCookieChunk = cookies[(0, _helpers.getIndexedCookieName)(i++)];
170
+ if (sessionCookieChunk) {
171
+ sessionCookies += sessionCookieChunk;
172
+ }
173
+ } while (sessionCookieChunk);
174
+ }
175
+ if (sessionCookies.length === 0) {
176
+ logger.info('Session cookie NOT found');
177
+ return undefined;
178
+ }
179
+ logger.info(`Session cookie found, (count: ${sessionCookies.length})`);
180
+ return sessionCookies;
181
+ }
182
+ parseCookieFromArray(cookies) {
183
+ const logger = _fronteggLogger.default.child({
184
+ tag: 'CookieManager.parseCookieFromArray'
185
+ });
186
+ const cookieChunks = cookies.filter(c => c.name.includes(this.getCookieName()));
187
+ logger.info('Parsing session cookie from RequestCookie for Next.JS 13+');
188
+ if (!cookieChunks || cookieChunks.length === 0) {
189
+ logger.info(`No session cookies found`);
190
+ return undefined;
191
+ }
192
+ logger.debug(`Found ${cookieChunks.length} chunks`);
193
+ cookieChunks.sort((a, b) => {
194
+ const firstCookieNumber = parseInt(a.name.slice(-1));
195
+ const secondCookieNumber = parseInt(b.name.slice(-1));
196
+ return firstCookieNumber > secondCookieNumber ? 1 : -1;
197
+ });
198
+ logger.info(`Concatenate session cookies chunks`);
199
+ return cookieChunks.map(c => c.value).join('');
200
+ }
201
+ /**
202
+ * Take a list of cookieNames and modify request/response headers
203
+ * to proxy the cookies from Next.js to Frontegg Services and vice-versa
204
+ * @param {string[]} setCookieValue - list of cookies to modify
205
+ * @param {boolean} isSecured - if the running application behind SSL
206
+ */
207
+ removeCookies({
208
+ cookieNames,
209
+ isSecured,
210
+ cookieDomain,
211
+ res,
212
+ req
213
+ }) {
214
+ var _ref;
215
+ const logger = _fronteggLogger.default.child({
216
+ tag: 'CookieManager.removeCookies'
217
+ });
218
+ logger.debug('Setting empty cookie headers remove cookies from client side');
219
+ const cookiesToRemove = this.getCookiesToRemove(req);
220
+ const cookieValue = this.createEmptyCookies(isSecured, cookieDomain, cookieNames != null ? cookieNames : cookiesToRemove);
221
+ let existingSetCookie = (_ref = res.getHeader('set-cookie')) != null ? _ref : [];
222
+ if (typeof existingSetCookie === 'string') {
223
+ existingSetCookie = [existingSetCookie];
224
+ }
225
+ const setCookieHeaders = [...existingSetCookie, ...cookieValue];
226
+ logger.debug(`removing headers (count: ${setCookieHeaders.length})`);
227
+ res.setHeader('set-cookie', setCookieHeaders);
228
+ }
229
+
230
+ /**
231
+ * Take a list of cookie headers and modify the Domain / Secure / SameSite
232
+ * to proxy the cookies to Frontegg Services and vice-versa
233
+ * @param {string[]} setCookieValue - list of cookies to modify
234
+ * @param {boolean} isSecured - if the running application behind SSL
235
+ */
236
+ }
237
+ var _default = new CookieManager();
238
+ exports.default = _default;
239
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["CookieManager","getCookieName","cookieNumber","cookieName","config","getIndexedCookieName","createEmptySingleCookie","isSecured","cookieDomain","create","value","expires","Date","secure","domain","silent","createEmptyCookies","_cookiesToRemove","allEmptyCookies","refreshTokenVariants","getRefreshTokenCookieNameVariants","cookiesToRemove","forEach","name","push","getCookiesToRemove","request","logger","fronteggLogger","child","tag","info","cookieStr","getCookieHeader","cookies","cookieSerializer","parse","cookieToRemove","length","e","error","modifySetCookie","setCookieValue","map","c","cookie","split","debug","filter","property","toLowerCase","baseUrlHost","join","refreshTokenKey","clientId","replace","options","level","undefined","cookieValue","serializeOptions","httpOnly","path","priority","sameSite","serializedCookie","serialize","COOKIE_MAX_LENGTH","splitValueToChunks","parseCookieHeader","cookieHeader","getSessionCookieFromRequest","i","sessionCookies","sessionCookieChunk","parseCookieFromArray","cookieChunks","includes","sort","a","b","firstCookieNumber","parseInt","slice","secondCookieNumber","removeCookies","cookieNames","res","req","existingSetCookie","getHeader","setCookieHeaders","setHeader"],"sources":["../../../../../packages/nextjs/src/utils/cookies/index.ts"],"sourcesContent":["import cookieSerializer from './serializer';\nimport type { RequestCookie } from 'next/dist/server/web/spec-extension/cookies';\nimport config from '../../config';\nimport { CookieSerializeOptions, CreateCookieOptions, RemoveCookiesOptions, RequestType } from './types';\nimport { COOKIE_MAX_LENGTH } from './constants';\n\nimport {\n getCookieHeader,\n getIndexedCookieName,\n getRefreshTokenCookieNameVariants,\n splitValueToChunks,\n} from './helpers';\nimport fronteggLogger from '../fronteggLogger';\n\nclass CookieManager {\n getCookieName = (cookieNumber?: number, cookieName = config.cookieName) =>\n cookieNumber ? getIndexedCookieName(cookieNumber, cookieName) : cookieName;\n\n get refreshTokenKey(): string {\n return `fe_refresh_${config.clientId}`.replace(/-/g, '');\n }\n\n /**\n * Validate and create new cookie headers.\n * The default value of `cookieName` is {@link config.cookieName}\n * @param {CreateCookieOptions} options - Create cookie options\n */\n create(options: CreateCookieOptions): string[] {\n const logger = fronteggLogger.child({ tag: 'CookieManager.create', level: options.silent ? 'error' : undefined });\n const cookieName = options.cookieName ?? config.cookieName;\n const cookieValue = options.value;\n logger.info(`Creating new cookie for '${cookieName}'`);\n\n const serializeOptions: CookieSerializeOptions = {\n expires: options.expires,\n httpOnly: options.httpOnly ?? true,\n domain: options.domain ?? config.cookieDomain,\n path: options.path ?? '/',\n priority: 'high',\n };\n\n if (options.secure) {\n logger.debug(`Set cookie '${cookieName}' as secure`);\n serializeOptions.secure = options.secure;\n serializeOptions.sameSite = 'none';\n }\n\n const serializedCookie = cookieSerializer.serialize(cookieName, cookieValue, serializeOptions);\n\n if (serializedCookie.length <= COOKIE_MAX_LENGTH) {\n logger.info(`Successfully create a cookie header, '${cookieName}'`);\n return [serializedCookie];\n } else {\n logger.debug('Going to split cookie into chunks');\n /** Create chunked cookie headers and store value as array of headers */\n const cookies = splitValueToChunks(cookieName, cookieValue, serializeOptions);\n logger.info(`Successfully create chunked cookie headers, '${cookieName}' (count: ${cookies.length})`);\n return cookies;\n }\n }\n\n /**\n * Receive incoming http request, and extract the cookie header.\n * @return cookie as string if exists, else empty string\n *\n * @param {RequestType} request - Incoming HTTP Request\n */\n parseCookieHeader(request: RequestType): Record<string, string> {\n const logger = fronteggLogger.child({ tag: 'CookieManager.parseCookieHeader' });\n\n logger.info('Going to extract all cookies header from request');\n const cookieHeader = getCookieHeader(request);\n logger.info('Parsing cookie header to map');\n return cookieSerializer.parse(cookieHeader);\n }\n\n /**\n * Loop over cookie headers, extract, parse cookies and merged divided cookies from incoming http request,\n * @return full session cookie headers if exists, else return undefined\n * @param {RequestType} request - Incoming HTTP Request\n */\n getSessionCookieFromRequest(request?: RequestType): string | undefined {\n const logger = fronteggLogger.child({ tag: 'CookieManager.getSessionCookieFromRequest' });\n logger.info('Going to extract session cookies header from request');\n\n if (!request) {\n logger.info(`'request' argument is null, Cookie header not found`);\n return undefined;\n }\n\n logger.debug('Getting cookie header');\n const cookieStr = getCookieHeader(request);\n\n logger.debug('Parsing cookie header string');\n const cookies = cookieSerializer.parse(cookieStr);\n\n logger.debug('Loop over session cookie headers');\n let i = 1;\n let sessionCookies = '';\n let sessionCookieChunk: string | undefined = cookies[this.getCookieName()];\n if (sessionCookieChunk === undefined) {\n do {\n sessionCookieChunk = cookies[getIndexedCookieName(i++)];\n if (sessionCookieChunk) {\n sessionCookies += sessionCookieChunk;\n }\n } while (sessionCookieChunk);\n }\n\n if (sessionCookies.length === 0) {\n logger.info('Session cookie NOT found');\n return undefined;\n }\n\n logger.info(`Session cookie found, (count: ${sessionCookies.length})`);\n return sessionCookies;\n }\n\n parseCookieFromArray(cookies: RequestCookie[]): string | undefined {\n const logger = fronteggLogger.child({ tag: 'CookieManager.parseCookieFromArray' });\n const cookieChunks = cookies.filter((c) => c.name.includes(this.getCookieName()));\n logger.info('Parsing session cookie from RequestCookie for Next.JS 13+');\n\n if (!cookieChunks || cookieChunks.length === 0) {\n logger.info(`No session cookies found`);\n return undefined;\n }\n logger.debug(`Found ${cookieChunks.length} chunks`);\n cookieChunks.sort((a, b) => {\n const firstCookieNumber = parseInt(a.name.slice(-1));\n const secondCookieNumber = parseInt(b.name.slice(-1));\n return firstCookieNumber > secondCookieNumber ? 1 : -1;\n });\n\n logger.info(`Concatenate session cookies chunks`);\n return cookieChunks.map((c) => c.value).join('');\n }\n\n private createEmptySingleCookie = (cookieName: string, isSecured: boolean, cookieDomain: string) => {\n return this.create({\n cookieName,\n value: '',\n expires: new Date(),\n secure: isSecured,\n domain: cookieDomain,\n silent: true,\n });\n };\n\n createEmptyCookies = (isSecured: boolean, cookieDomain: string, _cookiesToRemove: string[]): string[] => {\n const allEmptyCookies: string[] = [];\n\n const refreshTokenVariants = getRefreshTokenCookieNameVariants();\n const cookiesToRemove = [..._cookiesToRemove, ...refreshTokenVariants];\n\n cookiesToRemove.forEach((name: string) => {\n allEmptyCookies.push(...this.createEmptySingleCookie(name, isSecured, cookieDomain));\n });\n\n return allEmptyCookies;\n };\n\n private getCookiesToRemove = (request?: RequestType): string[] => {\n const logger = fronteggLogger.child({ tag: 'getCookiesToRemove' });\n if (!request) {\n return [];\n }\n try {\n logger.info('extract cookie from request headers');\n const cookieStr = getCookieHeader(request);\n const cookies = cookieStr && cookieSerializer.parse(cookieStr);\n if (!cookies) {\n return [];\n }\n let cookieNumber = 1;\n const cookieToRemove = [];\n while (cookies[this.getCookieName(cookieNumber)]) {\n cookieToRemove.push(this.getCookieName(cookieNumber));\n cookieNumber++;\n }\n logger.info(`number of cookies to remove: ${cookieToRemove.length}`);\n return cookieToRemove;\n } catch (e) {\n logger.error(e);\n return [];\n }\n };\n\n /**\n * Take a list of cookieNames and modify request/response headers\n * to proxy the cookies from Next.js to Frontegg Services and vice-versa\n * @param {string[]} setCookieValue - list of cookies to modify\n * @param {boolean} isSecured - if the running application behind SSL\n */\n removeCookies({ cookieNames, isSecured, cookieDomain, res, req }: RemoveCookiesOptions): void {\n const logger = fronteggLogger.child({ tag: 'CookieManager.removeCookies' });\n logger.debug('Setting empty cookie headers remove cookies from client side');\n const cookiesToRemove = this.getCookiesToRemove(req);\n const cookieValue = this.createEmptyCookies(isSecured, cookieDomain, cookieNames ?? cookiesToRemove);\n let existingSetCookie = (res.getHeader('set-cookie') as string[] | string) ?? [];\n if (typeof existingSetCookie === 'string') {\n existingSetCookie = [existingSetCookie];\n }\n\n const setCookieHeaders = [...existingSetCookie, ...cookieValue];\n logger.debug(`removing headers (count: ${setCookieHeaders.length})`);\n res.setHeader('set-cookie', setCookieHeaders);\n }\n\n /**\n * Take a list of cookie headers and modify the Domain / Secure / SameSite\n * to proxy the cookies to Frontegg Services and vice-versa\n * @param {string[]} setCookieValue - list of cookies to modify\n * @param {boolean} isSecured - if the running application behind SSL\n */\n modifySetCookie = (setCookieValue: string[] | undefined, isSecured: boolean): string[] | undefined => {\n const logger = fronteggLogger.child({ tag: 'CookieManager.modifySetCookie' });\n if (!setCookieValue || setCookieValue.length === 0) {\n logger.info(`No headers to modify`);\n return setCookieValue;\n }\n logger.info(`modifying cookie headers (count: ${setCookieValue.length})`);\n return setCookieValue.map((c) => {\n let cookie = c.split('; ');\n\n logger.debug(`modifying cookie ${cookie[0]}, isSecured: ${isSecured}`);\n if (!isSecured) {\n cookie = cookie.filter((property) => property !== 'Secure' && property !== 'SameSite=None');\n }\n\n return (\n cookie\n .map((property) => {\n if (property.toLowerCase() === `domain=${config.baseUrlHost}`) {\n return `Domain=${config.cookieDomain}`;\n }\n return property;\n })\n .join(';') + ';'\n );\n });\n };\n}\n\nexport default new CookieManager();\n"],"mappings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,GAAG,CAAC;IACpD,MAAM7B,WAAW,GAAG,IAAI,CAAC3C,kBAAkB,CAACT,SAAS,EAAEC,YAAY,EAAE8E,WAAW,WAAXA,WAAW,GAAIjE,eAAe,CAAC;IACpG,IAAIoE,iBAAiB,WAAIF,GAAG,CAACG,SAAS,CAAC,YAAY,CAAC,mBAA0B,EAAE;IAChF,IAAI,OAAOD,iBAAiB,KAAK,QAAQ,EAAE;MACzCA,iBAAiB,GAAG,CAACA,iBAAiB,CAAC;IACzC;IAEA,MAAME,gBAAgB,GAAG,CAAC,GAAGF,iBAAiB,EAAE,GAAG9B,WAAW,CAAC;IAC/DhC,MAAM,CAACoB,KAAK,CAAE,4BAA2B4C,gBAAgB,CAACrD,MAAO,GAAE,CAAC;IACpEiD,GAAG,CAACK,SAAS,CAAC,YAAY,EAAED,gBAAgB,CAAC;EAC/C;;EAEA;AACF;AACA;AACA;AACA;AACA;AA4BA;AAAC,eAEc,IAAI3F,aAAa,EAAE;AAAA"}
@@ -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 { CookieSerializeOptions } from './types';
2
+ /**
3
+ * Parse an HTTP Cookie header string and returning an object of all cookie
4
+ * name-value pairs.
5
+ *
6
+ * @param str the string representing a `Cookie` header value
7
+ */
8
+ declare function parse(str: any): Record<string, string>;
9
+ /**
10
+ * Serialize a cookie name-value pair into a `Set-Cookie` header string.
11
+ *
12
+ * @param name the name for the cookie
13
+ * @param val value to set the cookie to
14
+ * @param [options] object containing serialization options
15
+ * @throws {TypeError} when `maxAge` options is invalid
16
+ */
17
+ declare function serialize(name: string, val: string, options?: CookieSerializeOptions): string;
18
+ declare const _default: {
19
+ serialize: typeof serialize;
20
+ parse: typeof parse;
21
+ };
22
+ export default _default;
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _constants = require("../common/constants");
8
+ /**
9
+ * Determine if value is a Date.
10
+ *
11
+ * @param {*} val
12
+ * @private
13
+ */
14
+
15
+ function isDate(val) {
16
+ return Object.prototype.toString.call(val) === '[object Date]' || val instanceof Date;
17
+ }
18
+
19
+ /**
20
+ * Parse an HTTP Cookie header string and returning an object of all cookie
21
+ * name-value pairs.
22
+ *
23
+ * @param str the string representing a `Cookie` header value
24
+ */
25
+ function parse(str) {
26
+ if (typeof str !== 'string') {
27
+ throw new TypeError('argument str must be a string');
28
+ }
29
+ const obj = {};
30
+ let index = 0;
31
+ while (index < str.length) {
32
+ const eqIdx = str.indexOf('=', index);
33
+
34
+ // no more cookie pairs
35
+ if (eqIdx === -1) {
36
+ break;
37
+ }
38
+ let endIdx = str.indexOf(';', index);
39
+ if (endIdx === -1) {
40
+ endIdx = str.length;
41
+ } else if (endIdx < eqIdx) {
42
+ // backtrack on prior semicolon
43
+ index = str.lastIndexOf(';', eqIdx - 1) + 1;
44
+ continue;
45
+ }
46
+ const key = str.slice(index, eqIdx).trim();
47
+
48
+ // only assign once
49
+ if (undefined === obj[key]) {
50
+ let val = str.slice(eqIdx + 1, endIdx).trim();
51
+
52
+ // quoted values
53
+ if (val.charCodeAt(0) === 0x22) {
54
+ val = val.slice(1, -1);
55
+ }
56
+ try {
57
+ obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val;
58
+ } catch (e) {
59
+ obj[key] = val;
60
+ }
61
+ }
62
+ index = endIdx + 1;
63
+ }
64
+ return obj;
65
+ }
66
+
67
+ /**
68
+ * Serialize a cookie name-value pair into a `Set-Cookie` header string.
69
+ *
70
+ * @param name the name for the cookie
71
+ * @param val value to set the cookie to
72
+ * @param [options] object containing serialization options
73
+ * @throws {TypeError} when `maxAge` options is invalid
74
+ */
75
+ function serialize(name, val, options) {
76
+ const opt = options || {};
77
+ if (!_constants.cookieContentRegExp.test(name)) {
78
+ throw new TypeError('argument name is invalid: ' + name);
79
+ }
80
+ const value = encodeURIComponent(val);
81
+ if (value && !_constants.cookieContentRegExp.test(value)) {
82
+ throw new TypeError('argument val is invalid');
83
+ }
84
+ let str = name + '=' + value;
85
+ if (null != opt.maxAge) {
86
+ // noinspection PointlessArithmeticExpressionJS
87
+ const maxAge = opt.maxAge - 0;
88
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
89
+ throw new TypeError('option maxAge is invalid');
90
+ }
91
+ str += '; Max-Age=' + Math.floor(maxAge);
92
+ }
93
+ if (opt.domain) {
94
+ if (!_constants.cookieContentRegExp.test(opt.domain)) {
95
+ throw new TypeError('option domain is invalid');
96
+ }
97
+ str += '; Domain=' + opt.domain;
98
+ }
99
+ if (opt.path) {
100
+ if (!_constants.cookieContentRegExp.test(opt.path)) {
101
+ throw new TypeError('option path is invalid');
102
+ }
103
+ str += '; Path=' + opt.path;
104
+ }
105
+ if (opt.expires) {
106
+ const expires = opt.expires;
107
+ if (!isDate(expires) || isNaN(expires.valueOf())) {
108
+ throw new TypeError('option expires is invalid');
109
+ }
110
+ str += '; Expires=' + expires.toUTCString();
111
+ }
112
+ if (opt.httpOnly) {
113
+ str += '; HttpOnly';
114
+ }
115
+ if (opt.secure) {
116
+ str += '; Secure';
117
+ }
118
+ if (opt.priority) {
119
+ // noinspection SuspiciousTypeOfGuard
120
+ const priority = typeof opt.priority === 'string' ? opt.priority.toLowerCase() : opt.priority;
121
+ switch (priority) {
122
+ case 'low':
123
+ str += '; Priority=Low';
124
+ break;
125
+ case 'medium':
126
+ str += '; Priority=Medium';
127
+ break;
128
+ case 'high':
129
+ str += '; Priority=High';
130
+ break;
131
+ default:
132
+ throw new TypeError('option priority is invalid');
133
+ }
134
+ }
135
+ if (opt.sameSite) {
136
+ const sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;
137
+ switch (sameSite) {
138
+ case true:
139
+ str += '; SameSite=Strict';
140
+ break;
141
+ case 'lax':
142
+ str += '; SameSite=Lax';
143
+ break;
144
+ case 'strict':
145
+ str += '; SameSite=Strict';
146
+ break;
147
+ case 'none':
148
+ str += '; SameSite=None';
149
+ break;
150
+ default:
151
+ throw new TypeError('option sameSite is invalid');
152
+ }
153
+ }
154
+ return str;
155
+ }
156
+ var _default = {
157
+ serialize,
158
+ parse
159
+ };
160
+ exports.default = _default;
161
+ //# sourceMappingURL=serializer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serializer.js","names":["isDate","val","Object","prototype","toString","call","Date","parse","str","TypeError","obj","index","length","eqIdx","indexOf","endIdx","lastIndexOf","key","slice","trim","undefined","charCodeAt","decodeURIComponent","e","serialize","name","options","opt","cookieContentRegExp","test","value","encodeURIComponent","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite"],"sources":["../../../../../packages/nextjs/src/utils/cookies/serializer.ts"],"sourcesContent":["import { cookieContentRegExp } from '../common/constants';\nimport { CookieSerializeOptions } from './types';\n\n/**\n * Determine if value is a Date.\n *\n * @param {*} val\n * @private\n */\n\nfunction isDate(val: any) {\n return Object.prototype.toString.call(val) === '[object Date]' || val instanceof Date;\n}\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * @param str the string representing a `Cookie` header value\n */\nfunction parse(str: any): Record<string, string> {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n const obj: Record<string, string> = {};\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf('=', index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(';', index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(';', eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === obj[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val;\n } catch (e) {\n obj[key] = val;\n }\n }\n\n index = endIdx + 1;\n }\n\n return obj;\n}\n\n/**\n * Serialize a cookie name-value pair into a `Set-Cookie` header string.\n *\n * @param name the name for the cookie\n * @param val value to set the cookie to\n * @param [options] object containing serialization options\n * @throws {TypeError} when `maxAge` options is invalid\n */\nfunction serialize(name: string, val: string, options?: CookieSerializeOptions): string {\n const opt = options || {};\n\n if (!cookieContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid: ' + name);\n }\n\n const value = encodeURIComponent(val);\n\n if (value && !cookieContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n let str = name + '=' + value;\n\n if (null != opt.maxAge) {\n // noinspection PointlessArithmeticExpressionJS\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid');\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!cookieContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!cookieContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n const expires = opt.expires;\n\n if (!isDate(expires) || isNaN(expires.valueOf())) {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.priority) {\n // noinspection SuspiciousTypeOfGuard\n const priority = typeof opt.priority === 'string' ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case 'low':\n str += '; Priority=Low';\n break;\n case 'medium':\n str += '; Priority=Medium';\n break;\n case 'high':\n str += '; Priority=High';\n break;\n default:\n throw new TypeError('option priority is invalid');\n }\n }\n\n if (opt.sameSite) {\n const sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\nexport default {\n serialize,\n parse,\n};\n"],"mappings":";;;;;;AAAA;AAGA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,MAAM,CAACC,GAAQ,EAAE;EACxB,OAAOC,MAAM,CAACC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACJ,GAAG,CAAC,KAAK,eAAe,IAAIA,GAAG,YAAYK,IAAI;AACvF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,KAAK,CAACC,GAAQ,EAA0B;EAC/C,IAAI,OAAOA,GAAG,KAAK,QAAQ,EAAE;IAC3B,MAAM,IAAIC,SAAS,CAAC,+BAA+B,CAAC;EACtD;EAEA,MAAMC,GAA2B,GAAG,CAAC,CAAC;EAEtC,IAAIC,KAAK,GAAG,CAAC;EACb,OAAOA,KAAK,GAAGH,GAAG,CAACI,MAAM,EAAE;IACzB,MAAMC,KAAK,GAAGL,GAAG,CAACM,OAAO,CAAC,GAAG,EAAEH,KAAK,CAAC;;IAErC;IACA,IAAIE,KAAK,KAAK,CAAC,CAAC,EAAE;MAChB;IACF;IAEA,IAAIE,MAAM,GAAGP,GAAG,CAACM,OAAO,CAAC,GAAG,EAAEH,KAAK,CAAC;IAEpC,IAAII,MAAM,KAAK,CAAC,CAAC,EAAE;MACjBA,MAAM,GAAGP,GAAG,CAACI,MAAM;IACrB,CAAC,MAAM,IAAIG,MAAM,GAAGF,KAAK,EAAE;MACzB;MACAF,KAAK,GAAGH,GAAG,CAACQ,WAAW,CAAC,GAAG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YAAY;EACrB;EAEA,IAAImB,GAAG,CAACgB,MAAM,EAAE;IACdnC,GAAG,IAAI,UAAU;EACnB;EAEA,IAAImB,GAAG,CAACiB,QAAQ,EAAE;IAChB;IACA,MAAMA,QAAQ,GAAG,OAAOjB,GAAG,CAACiB,QAAQ,KAAK,QAAQ,GAAGjB,GAAG,CAACiB,QAAQ,CAACC,WAAW,EAAE,GAAGlB,GAAG,CAACiB,QAAQ;IAE7F,QAAQA,QAAQ;MACd,KAAK,KAAK;QACRpC,GAAG,IAAI,gBAAgB;QACvB;MACF,KAAK,QAAQ;QACXA,GAAG,IAAI,mBAAmB;QAC1B;MACF,KAAK,MAAM;QACTA,GAAG,IAAI,iBAAiB;QACxB;MACF;QACE,MAAM,IAAIC,SAAS,CAAC,4BAA4B,CAAC;IAAC;EAExD;EAEA,IAAIkB,GAAG,CAACmB,QAAQ,EAAE;IAChB,MAAMA,QAAQ,GAAG,OAAOnB,GAAG,CAACmB,QAAQ,KAAK,QAAQ,GAAGnB,GAAG,CAACmB,QAAQ,CAACD,WAAW,EAAE,GAAGlB,GAAG,CAACmB,QAAQ;IAE7F,QAAQA,QAAQ;MACd,KAAK,IAAI;QACPtC,GAAG,IAAI,mBAAmB;QAC1B;MACF,KAAK,KAAK;QACRA,GAAG,IAAI,gBAAgB;QACvB;MACF,KAAK,QAAQ;QACXA,GAAG,IAAI,mBAAmB;QAC1B;MACF,KAAK,MAAM;QACTA,GAAG,IAAI,iBAAiB;QACxB;MACF;QACE,MAAM,IAAIC,SAAS,CAAC,4BAA4B,CAAC;IAAC;EAExD;EAEA,OAAOD,GAAG;AACZ;AAAC,eAEc;EACbgB,SAAS;EACTjB;AACF,CAAC;AAAA"}
@@ -0,0 +1,31 @@
1
+ /// <reference types="node" />
2
+ import { IncomingMessage, ServerResponse } from 'http';
3
+ export type RequestType = IncomingMessage | Request;
4
+ export type ResponseType = ServerResponse;
5
+ export interface CreateCookieOptions extends Pick<CookieSerializeOptions, 'domain' | 'httpOnly' | 'path'> {
6
+ cookieName?: string;
7
+ value: string;
8
+ secure: boolean;
9
+ expires: Date;
10
+ silent?: boolean;
11
+ }
12
+ export interface RemoveCookiesOptions {
13
+ cookieNames?: string[];
14
+ isSecured: boolean;
15
+ cookieDomain: string;
16
+ res: ResponseType;
17
+ req?: RequestType;
18
+ }
19
+ /**
20
+ * Cookie serialization options
21
+ */
22
+ export interface CookieSerializeOptions {
23
+ domain?: string | undefined;
24
+ expires?: Date | undefined;
25
+ httpOnly?: boolean | undefined;
26
+ maxAge?: number | undefined;
27
+ path?: string | undefined;
28
+ priority?: 'low' | 'medium' | 'high' | undefined;
29
+ sameSite?: true | false | 'lax' | 'strict' | 'none' | undefined;
30
+ secure?: boolean | undefined;
31
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../../../../packages/nextjs/src/utils/cookies/types.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from 'http';\n\nexport type RequestType = IncomingMessage | Request;\nexport type ResponseType = ServerResponse;\n\nexport interface CreateCookieOptions extends Pick<CookieSerializeOptions, 'domain' | 'httpOnly' | 'path'> {\n cookieName?: string;\n value: string;\n secure: boolean;\n expires: Date;\n silent?: boolean;\n}\n\nexport interface RemoveCookiesOptions {\n cookieNames?: string[];\n isSecured: boolean;\n cookieDomain: string;\n res: ResponseType;\n req?: RequestType;\n}\n\n/**\n * Cookie serialization options\n */\nexport interface CookieSerializeOptions {\n domain?: string | undefined;\n expires?: Date | undefined;\n httpOnly?: boolean | undefined;\n maxAge?: number | undefined;\n path?: string | undefined;\n priority?: 'low' | 'medium' | 'high' | undefined;\n sameSite?: true | false | 'lax' | 'strict' | 'none' | undefined;\n secure?: boolean | undefined;\n}\n"],"mappings":""}
@@ -0,0 +1,2 @@
1
+ import type { EncryptionUtils, FronteggNextJSSession } from '../../types';
2
+ export default function createSession(cookie: string | undefined, encryption: EncryptionUtils): Promise<FronteggNextJSSession | undefined>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = createSession;
8
+ var _jwt = _interopRequireDefault(require("../jwt"));
9
+ var _fronteggLogger = _interopRequireDefault(require("../fronteggLogger"));
10
+ async function createSession(cookie, encryption) {
11
+ const logger = _fronteggLogger.default.child({
12
+ tag: 'SessionCreator.createSession'
13
+ });
14
+ logger.info('Creating new session');
15
+ try {
16
+ if (!cookie) {
17
+ logger.info('no cookies');
18
+ return undefined;
19
+ }
20
+ logger.debug('decrypting Session cookie');
21
+ const tokens = await encryption.unsealTokens(cookie);
22
+ if (!(tokens != null && tokens.accessToken)) {
23
+ logger.info('no accessToken in session');
24
+ return undefined;
25
+ }
26
+ const {
27
+ accessToken,
28
+ refreshToken
29
+ } = tokens;
30
+ logger.debug('Going to verify accessToken');
31
+ const {
32
+ payload
33
+ } = await _jwt.default.verify(accessToken);
34
+ logger.debug('Access token verified successfully');
35
+ const session = {
36
+ accessToken,
37
+ user: payload,
38
+ refreshToken
39
+ };
40
+ logger.debug('Check if access token will expire soon');
41
+ if (session.user.exp * 1000 < Date.now()) {
42
+ return undefined;
43
+ }
44
+ logger.info('Successfully create session object');
45
+ return session;
46
+ } catch (e) {
47
+ logger.error('Failed to create session', e);
48
+ return undefined;
49
+ }
50
+ }
51
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["createSession","cookie","encryption","logger","fronteggLogger","child","tag","info","undefined","debug","tokens","unsealTokens","accessToken","refreshToken","payload","JwtManager","verify","session","user","exp","Date","now","e","error"],"sources":["../../../../../packages/nextjs/src/utils/createSession/index.ts"],"sourcesContent":["import JwtManager from '../jwt';\nimport type { EncryptionUtils, FronteggNextJSSession } from '../../types';\nimport fronteggLogger from '../fronteggLogger';\n\nexport default async function createSession(\n cookie: string | undefined,\n encryption: EncryptionUtils\n): Promise<FronteggNextJSSession | undefined> {\n const logger = fronteggLogger.child({ tag: 'SessionCreator.createSession' });\n logger.info('Creating new session');\n try {\n if (!cookie) {\n logger.info('no cookies');\n return undefined;\n }\n\n logger.debug('decrypting Session cookie');\n const tokens = await encryption.unsealTokens(cookie);\n if (!tokens?.accessToken) {\n logger.info('no accessToken in session');\n return undefined;\n }\n const { accessToken, refreshToken } = tokens;\n\n logger.debug('Going to verify accessToken');\n const { payload }: any = await JwtManager.verify(accessToken);\n\n logger.debug('Access token verified successfully');\n const session: FronteggNextJSSession = {\n accessToken,\n user: payload,\n refreshToken,\n };\n\n logger.debug('Check if access token will expire soon');\n if (session.user.exp * 1000 < Date.now()) {\n return undefined;\n }\n\n logger.info('Successfully create session object');\n return session;\n } catch (e) {\n logger.error('Failed to create session', e);\n return undefined;\n }\n}\n"],"mappings":";;;;;;;AAAA;AAEA;AAEe,eAAeA,aAAa,CACzCC,MAA0B,EAC1BC,UAA2B,EACiB;EAC5C,MAAMC,MAAM,GAAGC,uBAAc,CAACC,KAAK,CAAC;IAAEC,GAAG,EAAE;EAA+B,CAAC,CAAC;EAC5EH,MAAM,CAACI,IAAI,CAAC,sBAAsB,CAAC;EACnC,IAAI;IACF,IAAI,CAACN,MAAM,EAAE;MACXE,MAAM,CAACI,IAAI,CAAC,YAAY,CAAC;MACzB,OAAOC,SAAS;IAClB;IAEAL,MAAM,CAACM,KAAK,CAAC,2BAA2B,CAAC;IACzC,MAAMC,MAAM,GAAG,MAAMR,UAAU,CAACS,YAAY,CAACV,MAAM,CAAC;IACpD,IAAI,EAACS,MAAM,YAANA,MAAM,CAAEE,WAAW,GAAE;MACxBT,MAAM,CAACI,IAAI,CAAC,2BAA2B,CAAC;MACxC,OAAOC,SAAS;IAClB;IACA,MAAM;MAAEI,WAAW;MAAEC;IAAa,CAAC,GAAGH,MAAM;IAE5CP,MAAM,CAACM,KAAK,CAAC,6BAA6B,CAAC;IAC3C,MAAM;MAAEK;IAAa,CAAC,GAAG,MAAMC,YAAU,CAACC,MAAM,CAACJ,WAAW,CAAC;IAE7DT,MAAM,CAACM,KAAK,CAAC,oCAAoC,CAAC;IAClD,MAAMQ,OAA8B,GAAG;MACrCL,WAAW;MACXM,IAAI,EAAEJ,OAAO;MACbD;IACF,CAAC;IAEDV,MAAM,CAACM,KAAK,CAAC,wCAAwC,CAAC;IACtD,IAAIQ,OAAO,CAACC,IAAI,CAACC,GAAG,GAAG,IAAI,GAAGC,IAAI,CAACC,GAAG,EAAE,EAAE;MACxC,OAAOb,SAAS;IAClB;IAEAL,MAAM,CAACI,IAAI,CAAC,oCAAoC,CAAC;IACjD,OAAOU,OAAO;EAChB,CAAC,CAAC,OAAOK,CAAC,EAAE;IACVnB,MAAM,CAACoB,KAAK,CAAC,0BAA0B,EAAED,CAAC,CAAC;IAC3C,OAAOd,SAAS;EAClB;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,3 @@
1
+ import type { EncryptionUtils } from '../../types';
2
+ declare const encryptionUtils: EncryptionUtils;
3
+ export default encryptionUtils;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ var _ironSession = require("iron-session");
9
+ var _config = _interopRequireDefault(require("../../config"));
10
+ // noinspection DuplicatedCode
11
+ // duplicated code for standard iron-session and iron-session/edge
12
+
13
+ /**
14
+ * IMPORTANT NOTE:
15
+ * This utils can be used only in server/client runtime, for edge runtime use the ./utils/encryption-edge
16
+ **/
17
+
18
+ const unsealTokens = async data => {
19
+ const jwtData = await (0, _ironSession.unsealData)(data, {
20
+ password: _config.default.password
21
+ });
22
+ return JSON.parse(jwtData);
23
+ };
24
+ const sealTokens = async (tokens, ttl) => {
25
+ const dataToSeal = JSON.stringify(tokens);
26
+ return (0, _ironSession.sealData)(dataToSeal, {
27
+ password: _config.default.password,
28
+ ttl
29
+ });
30
+ };
31
+ const encryptionUtils = {
32
+ unsealTokens,
33
+ sealTokens
34
+ };
35
+ var _default = encryptionUtils;
36
+ exports.default = _default;
37
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["unsealTokens","data","jwtData","unsealData","password","config","JSON","parse","sealTokens","tokens","ttl","dataToSeal","stringify","sealData","encryptionUtils"],"sources":["../../../../../packages/nextjs/src/utils/encryption/index.ts"],"sourcesContent":["// noinspection DuplicatedCode\n// duplicated code for standard iron-session and iron-session/edge\n\nimport { unsealData, sealData } from 'iron-session';\nimport config from '../../config';\nimport type { EncryptionUtils, FronteggUserTokens } from '../../types';\n\n/**\n * IMPORTANT NOTE:\n * This utils can be used only in server/client runtime, for edge runtime use the ./utils/encryption-edge\n **/\n\nconst unsealTokens = async (data: string): Promise<FronteggUserTokens | undefined> => {\n const jwtData: string = await unsealData(data, {\n password: config.password,\n });\n return JSON.parse(jwtData);\n};\n\nconst sealTokens = async (tokens: FronteggUserTokens, ttl: number): Promise<string> => {\n const dataToSeal = JSON.stringify(tokens);\n return sealData(dataToSeal, {\n password: config.password,\n ttl,\n });\n};\n\nconst encryptionUtils: EncryptionUtils = {\n unsealTokens,\n sealTokens,\n};\n\nexport default encryptionUtils;\n"],"mappings":";;;;;;;AAGA;AACA;AAJA;AACA;;AAMA;AACA;AACA;AACA;;AAEA,MAAMA,YAAY,GAAG,MAAOC,IAAY,IAA8C;EACpF,MAAMC,OAAe,GAAG,MAAM,IAAAC,uBAAU,EAACF,IAAI,EAAE;IAC7CG,QAAQ,EAAEC,eAAM,CAACD;EACnB,CAAC,CAAC;EACF,OAAOE,IAAI,CAACC,KAAK,CAACL,OAAO,CAAC;AAC5B,CAAC;AAED,MAAMM,UAAU,GAAG,OAAOC,MAA0B,EAAEC,GAAW,KAAsB;EACrF,MAAMC,UAAU,GAAGL,IAAI,CAACM,SAAS,CAACH,MAAM,CAAC;EACzC,OAAO,IAAAI,qBAAQ,EAACF,UAAU,EAAE;IAC1BP,QAAQ,EAAEC,eAAM,CAACD,QAAQ;IACzBM;EACF,CAAC,CAAC;AACJ,CAAC;AAED,MAAMI,eAAgC,GAAG;EACvCd,YAAY;EACZQ;AACF,CAAC;AAAC,eAEaM,eAAe;AAAA"}