@frontegg/nextjs 9.2.0 → 9.2.1-alpha.12073075767
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/edge/getSessionOnEdge.d.ts +2 -2
- package/edge/getSessionOnEdge.js +4 -2
- package/edge/getSessionOnEdge.js.map +1 -1
- package/index.js +1 -1
- package/middleware/FronteggApiMiddleware.d.ts +3 -2
- package/middleware/FronteggApiMiddleware.js +27 -3
- package/middleware/FronteggApiMiddleware.js.map +1 -1
- package/middleware/constants.d.ts +1 -0
- package/middleware/constants.js +2 -1
- package/middleware/constants.js.map +1 -1
- package/middleware/helpers.d.ts +1 -0
- package/middleware/helpers.js +3 -1
- package/middleware/helpers.js.map +1 -1
- package/middleware/types.d.ts +10 -0
- package/middleware/types.js +6 -0
- package/middleware/types.js.map +1 -0
- package/package.json +1 -1
- package/sdkVersion.js +1 -1
- package/sdkVersion.js.map +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IncomingMessage } from 'http';
|
|
2
|
-
import { FronteggEdgeSession } from '../types';
|
|
2
|
+
import { FronteggEdgeSession, FronteggNextJSSession } from '../types';
|
|
3
3
|
import { type NextRequest, NextResponse } from 'next/server';
|
|
4
4
|
export type HandleSessionOnEdge = {
|
|
5
5
|
request: IncomingMessage | Request;
|
|
@@ -30,7 +30,7 @@ export declare const handleSessionOnEdge: (params: HandleSessionOnEdge) => Promi
|
|
|
30
30
|
* ```
|
|
31
31
|
* @deprecated
|
|
32
32
|
*/
|
|
33
|
-
export declare const getSessionOnEdge: (req: IncomingMessage | Request) => Promise<
|
|
33
|
+
export declare const getSessionOnEdge: (req: IncomingMessage | Request) => Promise<FronteggNextJSSession | undefined>;
|
|
34
34
|
/**
|
|
35
35
|
* Check session on edge and return session if exists this method does not redirect to login page
|
|
36
36
|
* Example:
|
package/edge/getSessionOnEdge.js
CHANGED
|
@@ -94,8 +94,10 @@ Alternatively, to manually verify the session, you can use checkSessionOnEdge. N
|
|
|
94
94
|
* ```
|
|
95
95
|
* @deprecated
|
|
96
96
|
*/
|
|
97
|
-
|
|
98
|
-
|
|
97
|
+
|
|
98
|
+
const getSessionOnEdge = req => {
|
|
99
|
+
const cookies = _cookies.default.getSessionCookieFromRequest(req);
|
|
100
|
+
return (0, _createSession.default)(cookies, _encryptionEdge.default);
|
|
99
101
|
};
|
|
100
102
|
|
|
101
103
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getSessionOnEdge.js","names":["_cookies","_interopRequireDefault","require","_createSession","_encryptionEdge","_api","_server","_config","_jwt","_utils","_fronteggLogger","_refreshAccessTokenIfNeededOnEdge","_redirectToLogin","_shouldBypassMiddleware","logger","fronteggLogger","child","tag","handleSessionOnEdge","params","request","pathname","searchParams","headers","isHostedLoginCallback","handleHostedLoginCallback","shouldByPassMiddleware","NextResponse","next","edgeSession","checkSessionOnEdge","redirectToLogin","exports","GET_SESSION_ON_EDGE_DEPRECATED_ERROR","getSessionOnEdge","req","Error","sessionCookies","CookieManager","getSessionCookieFromRequest","existingSession","createSession","encryptionEdge","debug","session","refreshAccessTokenIfNeededOnEdge","createSessionFromAccessTokenEdge","data","_data$accessToken","_data$refreshToken","accessToken","access_token","refreshToken","refresh_token","payload","decodedJwt","JwtManager","verify","expiresIn","Math","floor","exp","Date","now","tokens","sealTokens","_searchParams$get","_req$headers","code","get","clientIp","undefined","_socket","socket","remoteAddress","_socket2","requestHeaders","_extends2","default","config","shouldForwardIp","_config$clientSecret","FRONTEGG_FORWARD_IP_HEADER","FRONTEGG_CLIENT_SECRET_HEADER","clientSecret","response","api","exchangeHostedLoginToken","buildRequestHeaders","clientId","json","redirect","appUrl","isSecured","isSSL","cookieValue","create","value","expires","secure","cookieName","replace","rewriteCookieByAppId","appId","refreshCookie","sessionCookieHeaders","map","cookie","refreshCookieHeaders","secureJwtEnabled","startsWith"],"sources":["../../../../packages/nextjs/src/edge/getSessionOnEdge.ts"],"sourcesContent":["import type { IncomingMessage } from 'http';\nimport { FronteggEdgeSession } from '../types';\nimport CookieManager from '../utils/cookies';\nimport createSession from '../utils/createSession';\nimport encryptionEdge from '../utils/encryption-edge';\nimport api from '../api';\nimport { type NextRequest, NextResponse } from 'next/server';\nimport config from '../config';\nimport JwtManager from '../utils/jwt';\nimport { buildRequestHeaders, FRONTEGG_CLIENT_SECRET_HEADER, FRONTEGG_FORWARD_IP_HEADER } from '../api/utils';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport { refreshAccessTokenIfNeededOnEdge } from './refreshAccessTokenIfNeededOnEdge';\nimport { redirectToLogin } from './redirectToLogin';\nimport { shouldByPassMiddleware } from './shouldBypassMiddleware';\n\nconst logger = fronteggLogger.child({ tag: 'EdgeRuntime.getSessionOnEdge' });\n\nexport type HandleSessionOnEdge = {\n request: IncomingMessage | Request;\n pathname: string;\n headers: NextRequest['headers'];\n searchParams: URLSearchParams;\n};\n\nexport const handleSessionOnEdge = async (params: HandleSessionOnEdge): Promise<NextResponse> => {\n const { request, pathname, searchParams, headers } = params;\n\n if (isHostedLoginCallback(pathname, searchParams)) {\n return handleHostedLoginCallback(request, pathname, searchParams);\n }\n\n if (shouldByPassMiddleware(pathname, headers /*, options: optional bypass configuration */)) {\n return NextResponse.next();\n }\n\n const edgeSession = await checkSessionOnEdge(request);\n if (!edgeSession) {\n return redirectToLogin(pathname, searchParams);\n }\n if (edgeSession.headers) {\n return NextResponse.next({\n headers: edgeSession.headers,\n });\n }\n return NextResponse.next();\n};\n\nconst GET_SESSION_ON_EDGE_DEPRECATED_ERROR = `Deprecation Notice: getSessionOnEdge has been deprecated. Please use handleSessionOnEdge instead. For example:\n\nfile: middleware.ts\n\\`\\`\\`ts\n import { NextRequest } from 'next/server';\n import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n \n export const middleware = async (request: NextRequest) => {\n const { pathname, searchParams } = request.nextUrl;\n const headers = request.headers;\n \n // Additional logic if needed\n \n return handleSessionOnEdge({ request, pathname, searchParams, headers });\n };\n \n \n export const config = {\n matcher: '/(.*)',\n };\n\n\\`\\`\\`\n\nAlternatively, to manually verify the session, you can use checkSessionOnEdge. Note that this method does not redirect to the login page if the session is invalid.\n`;\n\n/**\n * getSessionOnEdge is deprecated, please use handleSessionOnEdge instead example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * return handleSessionOnEdge({ request, pathname, searchParams, headers });\n * };\n *\n * export const config = {\n * matcher: '/(.*)',\n * };\n * ```\n * @deprecated\n */\nexport const getSessionOnEdge = async (req: IncomingMessage | Request): Promise<FronteggEdgeSession | undefined> => {\n throw new Error(GET_SESSION_ON_EDGE_DEPRECATED_ERROR);\n};\n\n/**\n * Check session on edge and return session if exists this method does not redirect to login page\n * Example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * // check if it's a hosted login callback\n * if (isHostedLoginCallback(pathname, searchParams)) {\n * return handleHostedLoginCallback(request, pathname, searchParams);\n * }\n *\n * // check if we should bypass the middleware\n * if (shouldByPassMiddleware(pathname)) {\n * return NextResponse.next();\n * }\n *\n * // check session\n * const session = await checkSessionOnEdge(request);\n *\n * if (!session) {\n * return redirectToLogin(pathname);\n * }\n *\n * // if headers are present return them to the next response\n * if (session.headers) {\n * return NextResponse.next({\n * headers: session.headers,\n * });\n * }\n * return NextResponse.next();\n * };\n * ```\n *\n *\n * @param req\n */\nexport const checkSessionOnEdge = async (req: IncomingMessage | Request): Promise<FronteggEdgeSession | undefined> => {\n const sessionCookies = CookieManager.getSessionCookieFromRequest(req);\n let existingSession = await createSession(sessionCookies, encryptionEdge);\n if (existingSession) {\n logger.debug('session resolved from session cookie');\n return {\n session: existingSession,\n };\n }\n\n logger.debug('Failed to resolve session from cookie, going to refresh token');\n return refreshAccessTokenIfNeededOnEdge(req);\n};\n\nasync function createSessionFromAccessTokenEdge(data: any): Promise<[string, any, string] | []> {\n const accessToken = data.accessToken ?? data.access_token;\n const refreshToken = data.refreshToken ?? data.refresh_token;\n const { payload: decodedJwt }: any = await JwtManager.verify(accessToken);\n decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);\n\n const tokens = { accessToken, refreshToken };\n const session = await encryptionEdge.sealTokens(tokens, decodedJwt.exp);\n return [session, decodedJwt, refreshToken];\n}\n\nexport const handleHostedLoginCallback = async (\n req: IncomingMessage | Request,\n pathname: string,\n searchParams: URLSearchParams\n): Promise<NextResponse> => {\n if (!isHostedLoginCallback(pathname, searchParams)) {\n return NextResponse.next();\n }\n\n const code = searchParams.get('code') ?? '';\n\n let headers: Record<string, string> = {};\n let clientIp: string | undefined = undefined;\n if (typeof req.headers?.get === 'function') {\n clientIp =\n req.headers.get('cf-connecting-ip') || req.headers.get('x-forwarded-for') || (req as any).socket?.remoteAddress;\n } else if (typeof req.headers === 'object') {\n let requestHeaders: any = { ...req.headers };\n clientIp =\n requestHeaders['cf-connecting-ip'] || requestHeaders['x-forwarded-for'] || (req as any).socket?.remoteAddress;\n }\n\n if (clientIp && config.shouldForwardIp) {\n headers[FRONTEGG_FORWARD_IP_HEADER] = clientIp;\n headers[FRONTEGG_CLIENT_SECRET_HEADER] = config.clientSecret ?? '';\n }\n\n const response = await api.exchangeHostedLoginToken(\n buildRequestHeaders(headers),\n code,\n config.clientId,\n config.clientSecret!\n );\n\n const data = await response.json();\n\n const [session, decodedJwt, refreshToken] = await createSessionFromAccessTokenEdge(data);\n\n if (!session) {\n return NextResponse.redirect(config.appUrl);\n }\n const isSecured = config.isSSL;\n const cookieValue = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n\n let cookieName = `fe_refresh_${config.clientId.replace('-', '')}`;\n if (config.rewriteCookieByAppId && config.appId) {\n cookieName = `fe_refresh_${config.appId.replace('-', '')}`;\n }\n const refreshCookie = CookieManager.create({\n cookieName,\n value: refreshToken ?? '',\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n const sessionCookieHeaders: [string, string][] = cookieValue.map((cookie) => ['set-cookie', cookie]);\n const refreshCookieHeaders: [string, string][] = refreshCookie.map((cookie) => ['set-cookie', cookie]);\n\n return NextResponse.redirect(config.appUrl, {\n headers: [...sessionCookieHeaders, ...refreshCookieHeaders],\n });\n};\n\nexport const isHostedLoginCallback = (pathname: string, searchParams: URLSearchParams): boolean => {\n if (config.secureJwtEnabled) {\n if (pathname.startsWith('/oauth/callback')) {\n return searchParams.get('code') != null;\n }\n }\n return false;\n};\n"],"mappings":";;;;;;;;AAEA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,cAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,eAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,IAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,OAAA,GAAAN,sBAAA,CAAAC,OAAA;AACA,IAAAM,IAAA,GAAAP,sBAAA,CAAAC,OAAA;AACA,IAAAO,MAAA,GAAAP,OAAA;AACA,IAAAQ,eAAA,GAAAT,sBAAA,CAAAC,OAAA;AACA,IAAAS,iCAAA,GAAAT,OAAA;AACA,IAAAU,gBAAA,GAAAV,OAAA;AACA,IAAAW,uBAAA,GAAAX,OAAA;AAEA,MAAMY,MAAM,GAAGC,uBAAc,CAACC,KAAK,CAAC;EAAEC,GAAG,EAAE;AAA+B,CAAC,CAAC;AASrE,MAAMC,mBAAmB,GAAG,MAAOC,MAA2B,IAA4B;EAC/F,MAAM;IAAEC,OAAO;IAAEC,QAAQ;IAAEC,YAAY;IAAEC;EAAQ,CAAC,GAAGJ,MAAM;EAE3D,IAAIK,qBAAqB,CAACH,QAAQ,EAAEC,YAAY,CAAC,EAAE;IACjD,OAAOG,yBAAyB,CAACL,OAAO,EAAEC,QAAQ,EAAEC,YAAY,CAAC;EACnE;EAEA,IAAI,IAAAI,8CAAsB,EAACL,QAAQ,EAAEE,OAAO,CAAC,6CAA6C,CAAC,EAAE;IAC3F,OAAOI,oBAAY,CAACC,IAAI,CAAC,CAAC;EAC5B;EAEA,MAAMC,WAAW,GAAG,MAAMC,kBAAkB,CAACV,OAAO,CAAC;EACrD,IAAI,CAACS,WAAW,EAAE;IAChB,OAAO,IAAAE,gCAAe,EAACV,QAAQ,EAAEC,YAAY,CAAC;EAChD;EACA,IAAIO,WAAW,CAACN,OAAO,EAAE;IACvB,OAAOI,oBAAY,CAACC,IAAI,CAAC;MACvBL,OAAO,EAAEM,WAAW,CAACN;IACvB,CAAC,CAAC;EACJ;EACA,OAAOI,oBAAY,CAACC,IAAI,CAAC,CAAC;AAC5B,CAAC;AAACI,OAAA,CAAAd,mBAAA,GAAAA,mBAAA;AAEF,MAAMe,oCAAoC,GAAG;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMC,gBAAgB,GAAG,MAAOC,GAA8B,IAA+C;EAClH,MAAM,IAAIC,KAAK,CAACH,oCAAoC,CAAC;AACvD,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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AIpC,IAAI,CAACP,UAAU,CAACM,GAAG,GAAG,IAAI,CAAC;IACxCsC,MAAM,EAAEN;EACV,CAAC,CAAC;EACF,MAAMY,oBAAwC,GAAGV,WAAW,CAACW,GAAG,CAAEC,MAAM,IAAK,CAAC,YAAY,EAAEA,MAAM,CAAC,CAAC;EACpG,MAAMC,oBAAwC,GAAGJ,aAAa,CAACE,GAAG,CAAEC,MAAM,IAAK,CAAC,YAAY,EAAEA,MAAM,CAAC,CAAC;EAEtG,OAAOhF,oBAAY,CAACgE,QAAQ,CAACZ,eAAM,CAACa,MAAM,EAAE;IAC1CrE,OAAO,EAAE,CAAC,GAAGkF,oBAAoB,EAAE,GAAGG,oBAAoB;EAC5D,CAAC,CAAC;AACJ,CAAC;AAAC5E,OAAA,CAAAP,yBAAA,GAAAA,yBAAA;AAEK,MAAMD,qBAAqB,GAAGA,CAACH,QAAgB,EAAEC,YAA6B,KAAc;EACjG,IAAIyD,eAAM,CAAC8B,gBAAgB,EAAE;IAC3B,IAAIxF,QAAQ,CAACyF,UAAU,CAAC,iBAAiB,CAAC,EAAE;MAC1C,OAAOxF,YAAY,CAAC+C,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI;IACzC;EACF;EACA,OAAO,KAAK;AACd,CAAC;AAACrC,OAAA,CAAAR,qBAAA,GAAAA,qBAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"getSessionOnEdge.js","names":["_cookies","_interopRequireDefault","require","_createSession","_encryptionEdge","_api","_server","_config","_jwt","_utils","_fronteggLogger","_refreshAccessTokenIfNeededOnEdge","_redirectToLogin","_shouldBypassMiddleware","logger","fronteggLogger","child","tag","handleSessionOnEdge","params","request","pathname","searchParams","headers","isHostedLoginCallback","handleHostedLoginCallback","shouldByPassMiddleware","NextResponse","next","edgeSession","checkSessionOnEdge","redirectToLogin","exports","GET_SESSION_ON_EDGE_DEPRECATED_ERROR","getSessionOnEdge","req","cookies","CookieManager","getSessionCookieFromRequest","createSession","encryptionEdge","sessionCookies","existingSession","debug","session","refreshAccessTokenIfNeededOnEdge","createSessionFromAccessTokenEdge","data","_data$accessToken","_data$refreshToken","accessToken","access_token","refreshToken","refresh_token","payload","decodedJwt","JwtManager","verify","expiresIn","Math","floor","exp","Date","now","tokens","sealTokens","_searchParams$get","_req$headers","code","get","clientIp","undefined","_socket","socket","remoteAddress","_socket2","requestHeaders","_extends2","default","config","shouldForwardIp","_config$clientSecret","FRONTEGG_FORWARD_IP_HEADER","FRONTEGG_CLIENT_SECRET_HEADER","clientSecret","response","api","exchangeHostedLoginToken","buildRequestHeaders","clientId","json","redirect","appUrl","isSecured","isSSL","cookieValue","create","value","expires","secure","cookieName","replace","rewriteCookieByAppId","appId","refreshCookie","sessionCookieHeaders","map","cookie","refreshCookieHeaders","secureJwtEnabled","startsWith"],"sources":["../../../../packages/nextjs/src/edge/getSessionOnEdge.ts"],"sourcesContent":["import type { IncomingMessage } from 'http';\nimport { FronteggEdgeSession, FronteggNextJSSession } from '../types';\nimport CookieManager from '../utils/cookies';\nimport createSession from '../utils/createSession';\nimport encryptionEdge from '../utils/encryption-edge';\nimport api from '../api';\nimport { type NextRequest, NextResponse } from 'next/server';\nimport config from '../config';\nimport JwtManager from '../utils/jwt';\nimport { buildRequestHeaders, FRONTEGG_CLIENT_SECRET_HEADER, FRONTEGG_FORWARD_IP_HEADER } from '../api/utils';\nimport fronteggLogger from '../utils/fronteggLogger';\nimport { refreshAccessTokenIfNeededOnEdge } from './refreshAccessTokenIfNeededOnEdge';\nimport { redirectToLogin } from './redirectToLogin';\nimport { shouldByPassMiddleware } from './shouldBypassMiddleware';\n\nconst logger = fronteggLogger.child({ tag: 'EdgeRuntime.getSessionOnEdge' });\n\nexport type HandleSessionOnEdge = {\n request: IncomingMessage | Request;\n pathname: string;\n headers: NextRequest['headers'];\n searchParams: URLSearchParams;\n};\n\nexport const handleSessionOnEdge = async (params: HandleSessionOnEdge): Promise<NextResponse> => {\n const { request, pathname, searchParams, headers } = params;\n\n if (isHostedLoginCallback(pathname, searchParams)) {\n return handleHostedLoginCallback(request, pathname, searchParams);\n }\n\n if (shouldByPassMiddleware(pathname, headers /*, options: optional bypass configuration */)) {\n return NextResponse.next();\n }\n\n const edgeSession = await checkSessionOnEdge(request);\n if (!edgeSession) {\n return redirectToLogin(pathname, searchParams);\n }\n if (edgeSession.headers) {\n return NextResponse.next({\n headers: edgeSession.headers,\n });\n }\n return NextResponse.next();\n};\n\nconst GET_SESSION_ON_EDGE_DEPRECATED_ERROR = `Deprecation Notice: getSessionOnEdge has been deprecated. Please use handleSessionOnEdge instead. For example:\n\nfile: middleware.ts\n\\`\\`\\`ts\n import { NextRequest } from 'next/server';\n import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n \n export const middleware = async (request: NextRequest) => {\n const { pathname, searchParams } = request.nextUrl;\n const headers = request.headers;\n \n // Additional logic if needed\n \n return handleSessionOnEdge({ request, pathname, searchParams, headers });\n };\n \n \n export const config = {\n matcher: '/(.*)',\n };\n\n\\`\\`\\`\n\nAlternatively, to manually verify the session, you can use checkSessionOnEdge. Note that this method does not redirect to the login page if the session is invalid.\n`;\n\n/**\n * getSessionOnEdge is deprecated, please use handleSessionOnEdge instead example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * return handleSessionOnEdge({ request, pathname, searchParams, headers });\n * };\n *\n * export const config = {\n * matcher: '/(.*)',\n * };\n * ```\n * @deprecated\n */\n\nexport const getSessionOnEdge = (req: IncomingMessage | Request): Promise<FronteggNextJSSession | undefined> => {\n const cookies = CookieManager.getSessionCookieFromRequest(req);\n return createSession(cookies, encryptionEdge);\n};\n\n/**\n * Check session on edge and return session if exists this method does not redirect to login page\n * Example:\n *\n * ```ts\n * import { NextRequest } from 'next/server';\n * import { handleSessionOnEdge } from '@frontegg/nextjs/edge';\n *\n * export const middleware = async (request: NextRequest) => {\n * const { pathname, searchParams } = request.nextUrl;\n * const headers = request.headers;\n *\n * // Additional logic if needed\n *\n * // check if it's a hosted login callback\n * if (isHostedLoginCallback(pathname, searchParams)) {\n * return handleHostedLoginCallback(request, pathname, searchParams);\n * }\n *\n * // check if we should bypass the middleware\n * if (shouldByPassMiddleware(pathname)) {\n * return NextResponse.next();\n * }\n *\n * // check session\n * const session = await checkSessionOnEdge(request);\n *\n * if (!session) {\n * return redirectToLogin(pathname);\n * }\n *\n * // if headers are present return them to the next response\n * if (session.headers) {\n * return NextResponse.next({\n * headers: session.headers,\n * });\n * }\n * return NextResponse.next();\n * };\n * ```\n *\n *\n * @param req\n */\nexport const checkSessionOnEdge = async (req: IncomingMessage | Request): Promise<FronteggEdgeSession | undefined> => {\n const sessionCookies = CookieManager.getSessionCookieFromRequest(req);\n let existingSession = await createSession(sessionCookies, encryptionEdge);\n if (existingSession) {\n logger.debug('session resolved from session cookie');\n return {\n session: existingSession,\n };\n }\n\n logger.debug('Failed to resolve session from cookie, going to refresh token');\n return refreshAccessTokenIfNeededOnEdge(req);\n};\n\nasync function createSessionFromAccessTokenEdge(data: any): Promise<[string, any, string] | []> {\n const accessToken = data.accessToken ?? data.access_token;\n const refreshToken = data.refreshToken ?? data.refresh_token;\n const { payload: decodedJwt }: any = await JwtManager.verify(accessToken);\n decodedJwt.expiresIn = Math.floor((decodedJwt.exp * 1000 - Date.now()) / 1000);\n\n const tokens = { accessToken, refreshToken };\n const session = await encryptionEdge.sealTokens(tokens, decodedJwt.exp);\n return [session, decodedJwt, refreshToken];\n}\n\nexport const handleHostedLoginCallback = async (\n req: IncomingMessage | Request,\n pathname: string,\n searchParams: URLSearchParams\n): Promise<NextResponse> => {\n if (!isHostedLoginCallback(pathname, searchParams)) {\n return NextResponse.next();\n }\n\n const code = searchParams.get('code') ?? '';\n\n let headers: Record<string, string> = {};\n let clientIp: string | undefined = undefined;\n if (typeof req.headers?.get === 'function') {\n clientIp =\n req.headers.get('cf-connecting-ip') || req.headers.get('x-forwarded-for') || (req as any).socket?.remoteAddress;\n } else if (typeof req.headers === 'object') {\n let requestHeaders: any = { ...req.headers };\n clientIp =\n requestHeaders['cf-connecting-ip'] || requestHeaders['x-forwarded-for'] || (req as any).socket?.remoteAddress;\n }\n\n if (clientIp && config.shouldForwardIp) {\n headers[FRONTEGG_FORWARD_IP_HEADER] = clientIp;\n headers[FRONTEGG_CLIENT_SECRET_HEADER] = config.clientSecret ?? '';\n }\n\n const response = await api.exchangeHostedLoginToken(\n buildRequestHeaders(headers),\n code,\n config.clientId,\n config.clientSecret!\n );\n\n const data = await response.json();\n\n const [session, decodedJwt, refreshToken] = await createSessionFromAccessTokenEdge(data);\n\n if (!session) {\n return NextResponse.redirect(config.appUrl);\n }\n const isSecured = config.isSSL;\n const cookieValue = CookieManager.create({\n value: session,\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n\n let cookieName = `fe_refresh_${config.clientId.replace('-', '')}`;\n if (config.rewriteCookieByAppId && config.appId) {\n cookieName = `fe_refresh_${config.appId.replace('-', '')}`;\n }\n const refreshCookie = CookieManager.create({\n cookieName,\n value: refreshToken ?? '',\n expires: new Date(decodedJwt.exp * 1000),\n secure: isSecured,\n });\n const sessionCookieHeaders: [string, string][] = cookieValue.map((cookie) => ['set-cookie', cookie]);\n const refreshCookieHeaders: [string, string][] = refreshCookie.map((cookie) => ['set-cookie', cookie]);\n\n return NextResponse.redirect(config.appUrl, {\n headers: [...sessionCookieHeaders, ...refreshCookieHeaders],\n });\n};\n\nexport const isHostedLoginCallback = (pathname: string, searchParams: URLSearchParams): boolean => {\n if (config.secureJwtEnabled) {\n if (pathname.startsWith('/oauth/callback')) {\n return searchParams.get('code') != null;\n }\n }\n return false;\n};\n"],"mappings":";;;;;;;;AAEA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,cAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAA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A,CAAAd,mBAAA,GAAAA,mBAAA;AAEF,MAAMe,oCAAoC,GAAG;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO,MAAMC,gBAAgB,GAAIC,GAA8B,IAAiD;EAC9G,MAAMC,OAAO,GAAGC,gBAAa,CAACC,2BAA2B,CAACH,GAAG,CAAC;EAC9D,OAAO,IAAAI,sBAAa,EAACH,OAAO,EAAEI,uBAAc,CAAC;AAC/C,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA3CAR,OAAA,CAAAE,gBAAA,GAAAA,gBAAA;AA4CO,MAAMJ,kBAAkB,GAAG,MAAOK,GAA8B,IAA+C;EACpH,MAAMM,cAAc,GAAGJ,gBAAa,CAACC,2BAA2B,CAACH,GAAG,CAAC;EACrE,IAAIO,eAAe,GAAG,MAAM,IAAAH,sBAAa,EAACE,cAAc,EAAED,uBAAc,CAAC;EACzE,IAAIE,eAAe,EAAE;IACnB5B,MAAM,CAAC6B,KAAK,CAAC,sCAAsC,CAAC;IACpD,OAAO;MACLC,OAAO,EAAEF;IACX,CAAC;EACH;EAEA5B,MAAM,CAAC6B,KAAK,CAAC,+DAA+D,CAAC;EAC7E,OAAO,IAAAE,kEAAgC,EAACV,GAAG,CAAC;AAC9C,CAAC;AAACH,OAAA,CAAAF,kBAAA,GAAAA,kBAAA;AAEF,eAAegB,gCAAgCA,CAACC,IAA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;EACjG,IAAIyD,eAAM,CAAC8B,gBAAgB,EAAE;IAC3B,IAAIxF,QAAQ,CAACyF,UAAU,CAAC,iBAAiB,CAAC,EAAE;MAC1C,OAAOxF,YAAY,CAAC+C,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI;IACzC;EACF;EACA,OAAO,KAAK;AACd,CAAC;AAACrC,OAAA,CAAAR,qBAAA,GAAAA,qBAAA","ignoreList":[]}
|
package/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { FronteggApiMiddlewareType } from './types';
|
|
2
2
|
/**
|
|
3
3
|
* Next.js HTTP Proxy Middleware
|
|
4
4
|
* @see https://nextjs.org/docs/api-routes/api-middlewares
|
|
5
5
|
* @param {NextApiRequest} req - NextJS api request passed from api routing
|
|
6
6
|
* @param {NextApiResponse} res - NextJS api response passed from api routing
|
|
7
7
|
*/
|
|
8
|
-
|
|
8
|
+
declare const FronteggApiMiddleware: FronteggApiMiddlewareType;
|
|
9
|
+
export { FronteggApiMiddleware };
|
|
@@ -4,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
|
|
|
4
4
|
Object.defineProperty(exports, "__esModule", {
|
|
5
5
|
value: true
|
|
6
6
|
});
|
|
7
|
-
exports.FronteggApiMiddleware =
|
|
7
|
+
exports.FronteggApiMiddleware = void 0;
|
|
8
8
|
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
|
9
9
|
var _FronteggProxy = require("./FronteggProxy");
|
|
10
10
|
var _constants = require("./constants");
|
|
@@ -40,7 +40,31 @@ const middlewarePromise = (req, res) => new Promise(async resolve => {
|
|
|
40
40
|
* @param {NextApiRequest} req - NextJS api request passed from api routing
|
|
41
41
|
* @param {NextApiResponse} res - NextJS api response passed from api routing
|
|
42
42
|
*/
|
|
43
|
-
async
|
|
43
|
+
const FronteggApiMiddleware = async (req, res) => {
|
|
44
44
|
return await middlewarePromise(req, res);
|
|
45
|
-
}
|
|
45
|
+
};
|
|
46
|
+
exports.FronteggApiMiddleware = FronteggApiMiddleware;
|
|
47
|
+
FronteggApiMiddleware.cors = options => async (req, res) => {
|
|
48
|
+
var _req$headers$host;
|
|
49
|
+
const {
|
|
50
|
+
allowedOrigins = ['*'],
|
|
51
|
+
allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
|
|
52
|
+
allowedHeaders = ['Content-Type', 'Authorization'],
|
|
53
|
+
allowCredentials = true
|
|
54
|
+
} = options;
|
|
55
|
+
if ((0, _helpers.isInternalRequest)((_req$headers$host = req.headers.host) != null ? _req$headers$host : '')) {
|
|
56
|
+
var _req$headers$origin;
|
|
57
|
+
const origin = (_req$headers$origin = req.headers.origin) != null ? _req$headers$origin : '';
|
|
58
|
+
const combinedHeaders = Array.from(new Set([..._constants.defaultFronteggHeaders, ...allowedHeaders]));
|
|
59
|
+
if (allowedOrigins.includes(origin)) {
|
|
60
|
+
res.setHeader('Access-Control-Allow-Origin', origin);
|
|
61
|
+
} else {
|
|
62
|
+
res.removeHeader('Access-Control-Allow-Origin');
|
|
63
|
+
}
|
|
64
|
+
res.setHeader('Access-Control-Allow-Methods', allowedMethods.join(','));
|
|
65
|
+
res.setHeader('Access-Control-Allow-Headers', combinedHeaders.join(','));
|
|
66
|
+
res.setHeader('Access-Control-Allow-Credentials', allowCredentials ? 'true' : 'false');
|
|
67
|
+
}
|
|
68
|
+
return middlewarePromise(req, res);
|
|
69
|
+
};
|
|
46
70
|
//# sourceMappingURL=FronteggApiMiddleware.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FronteggApiMiddleware.js","names":["_FronteggProxy","require","_constants","_helpers","_pages","middlewarePromise","req","res","Promise","resolve","_req$url","fronteggUrlPath","rewritePath","url","fronteggPathRewrite","rewriteUrl","fronteggSSOPathRewrite","on","options","target","process","env","headers","session","getSession","accessToken","FronteggProxy","web","_extends2","default","FronteggApiMiddleware"],"sources":["../../../../packages/nextjs/src/middleware/FronteggApiMiddleware.ts"],"sourcesContent":["import type { NextApiRequest, NextApiResponse } from 'next';\nimport { FronteggProxy } from './FronteggProxy';\nimport { fronteggSSOPathRewrite, fronteggPathRewrite } from './constants';\nimport { rewritePath } from './helpers';\nimport { getSession } from '../pages';\n\nconst middlewarePromise = (req: NextApiRequest, res: NextApiResponse) =>\n new Promise<void>(async (resolve) => {\n const fronteggUrlPath = rewritePath(req.url ?? '/', fronteggPathRewrite);\n const rewriteUrl = rewritePath(fronteggUrlPath ?? '/', fronteggSSOPathRewrite);\n req.url = rewriteUrl;\n res.on('close', () => resolve());\n const options = {\n target: process.env['FRONTEGG_BASE_URL'],\n };\n if (process.env['FRONTEGG_TEST_URL'] && req.url == '/frontegg/middleware-test') {\n options.target = process.env['FRONTEGG_TEST_URL'];\n }\n\n const headers: Record<string, string> = {};\n if (process.env['FRONTEGG_SECURE_JWT_ENABLED'] === 'true') {\n const session = await getSession(req);\n if (session?.accessToken) {\n headers['authorization'] = 'Bearer ' + session.accessToken;\n }\n }\n FronteggProxy.web(req, res, {\n ...options,\n headers,\n });\n });\n\n/**\n * Next.js HTTP Proxy Middleware\n * @see https://nextjs.org/docs/api-routes/api-middlewares\n * @param {NextApiRequest} req - NextJS api request passed from api routing\n * @param {NextApiResponse} res - NextJS api response passed from api routing\n */\
|
|
1
|
+
{"version":3,"file":"FronteggApiMiddleware.js","names":["_FronteggProxy","require","_constants","_helpers","_pages","middlewarePromise","req","res","Promise","resolve","_req$url","fronteggUrlPath","rewritePath","url","fronteggPathRewrite","rewriteUrl","fronteggSSOPathRewrite","on","options","target","process","env","headers","session","getSession","accessToken","FronteggProxy","web","_extends2","default","FronteggApiMiddleware","exports","cors","_req$headers$host","allowedOrigins","allowedMethods","allowedHeaders","allowCredentials","isInternalRequest","host","_req$headers$origin","origin","combinedHeaders","Array","from","Set","defaultFronteggHeaders","includes","setHeader","removeHeader","join"],"sources":["../../../../packages/nextjs/src/middleware/FronteggApiMiddleware.ts"],"sourcesContent":["import type { NextApiRequest, NextApiResponse } from 'next';\nimport { FronteggProxy } from './FronteggProxy';\nimport { fronteggSSOPathRewrite, fronteggPathRewrite, defaultFronteggHeaders } from './constants';\nimport { isInternalRequest, rewritePath } from './helpers';\nimport { getSession } from '../pages';\nimport { CorsOptions, FronteggApiMiddlewareType } from './types';\n\nconst middlewarePromise = (req: NextApiRequest, res: NextApiResponse) =>\n new Promise<void>(async (resolve) => {\n const fronteggUrlPath = rewritePath(req.url ?? '/', fronteggPathRewrite);\n const rewriteUrl = rewritePath(fronteggUrlPath ?? '/', fronteggSSOPathRewrite);\n req.url = rewriteUrl;\n res.on('close', () => resolve());\n const options = {\n target: process.env['FRONTEGG_BASE_URL'],\n };\n if (process.env['FRONTEGG_TEST_URL'] && req.url == '/frontegg/middleware-test') {\n options.target = process.env['FRONTEGG_TEST_URL'];\n }\n\n const headers: Record<string, string> = {};\n if (process.env['FRONTEGG_SECURE_JWT_ENABLED'] === 'true') {\n const session = await getSession(req);\n if (session?.accessToken) {\n headers['authorization'] = 'Bearer ' + session.accessToken;\n }\n }\n FronteggProxy.web(req, res, {\n ...options,\n headers,\n });\n });\n\n/**\n * Next.js HTTP Proxy Middleware\n * @see https://nextjs.org/docs/api-routes/api-middlewares\n * @param {NextApiRequest} req - NextJS api request passed from api routing\n * @param {NextApiResponse} res - NextJS api response passed from api routing\n */\nconst FronteggApiMiddleware: FronteggApiMiddlewareType = (async (\n req: NextApiRequest,\n res: NextApiResponse\n): Promise<void> => {\n return await middlewarePromise(req, res);\n}) as FronteggApiMiddlewareType;\n\nFronteggApiMiddleware.cors =\n (options: CorsOptions) =>\n async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {\n const {\n allowedOrigins = ['*'],\n allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders = ['Content-Type', 'Authorization'],\n allowCredentials = true,\n } = options;\n\n if (isInternalRequest(req.headers.host ?? '')) {\n const origin = req.headers.origin ?? '';\n const combinedHeaders = Array.from(new Set([...defaultFronteggHeaders, ...allowedHeaders]));\n\n if (allowedOrigins.includes(origin)) {\n res.setHeader('Access-Control-Allow-Origin', origin);\n } else {\n res.removeHeader('Access-Control-Allow-Origin');\n }\n\n res.setHeader('Access-Control-Allow-Methods', allowedMethods.join(','));\n res.setHeader('Access-Control-Allow-Headers', combinedHeaders.join(','));\n res.setHeader('Access-Control-Allow-Credentials', allowCredentials ? 'true' : 'false');\n }\n\n return middlewarePromise(req, res);\n };\n\nexport { FronteggApiMiddleware };\n"],"mappings":";;;;;;;;AACA,IAAAA,cAAA,GAAAC,OAAA;AACA,IAAAC,UAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;AAGA,MAAMI,iBAAiB,GAAGA,CAACC,GAAmB,EAAEC,GAAoB,KAClE,IAAIC,OAAO,CAAO,MAAOC,OAAO,IAAK;EAAA,IAAAC,QAAA;EACnC,MAAMC,eAAe,GAAG,IAAAC,oBAAW,GAAAF,QAAA,GAACJ,GAAG,CAACO,GAAG,YAAAH,QAAA,GAAI,GAAG,EAAEI,8BAAmB,CAAC;EACxE,MAAMC,UAAU,GAAG,IAAAH,oBAAW,EAACD,eAAe,WAAfA,eAAe,GAAI,GAAG,EAAEK,iCAAsB,CAAC;EAC9EV,GAAG,CAACO,GAAG,GAAGE,UAAU;EACpBR,GAAG,CAACU,EAAE,CAAC,OAAO,EAAE,MAAMR,OAAO,CAAC,CAAC,CAAC;EAChC,MAAMS,OAAO,GAAG;IACdC,MAAM,EAAEC,OAAO,CAACC,GAAG,CAAC,mBAAmB;EACzC,CAAC;EACD,IAAID,OAAO,CAACC,GAAG,CAAC,mBAAmB,CAAC,IAAIf,GAAG,CAACO,GAAG,IAAI,2BAA2B,EAAE;IAC9EK,OAAO,CAACC,MAAM,GAAGC,OAAO,CAACC,GAAG,CAAC,mBAAmB,CAAC;EACnD;EAEA,MAAMC,OAA+B,GAAG,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vC,MAAME,eAAe,GAAGC,KAAK,CAACC,IAAI,CAAC,IAAIC,GAAG,CAAC,CAAC,GAAGC,iCAAsB,EAAE,GAAGV,cAAc,CAAC,CAAC,CAAC;IAE3F,IAAIF,cAAc,CAACa,QAAQ,CAACN,MAAM,CAAC,EAAE;MACnClC,GAAG,CAACyC,SAAS,CAAC,6BAA6B,EAAEP,MAAM,CAAC;IACtD,CAAC,MAAM;MACLlC,GAAG,CAAC0C,YAAY,CAAC,6BAA6B,CAAC;IACjD;IAEA1C,GAAG,CAACyC,SAAS,CAAC,8BAA8B,EAAEb,cAAc,CAACe,IAAI,CAAC,GAAG,CAAC,CAAC;IACvE3C,GAAG,CAACyC,SAAS,CAAC,8BAA8B,EAAEN,eAAe,CAACQ,IAAI,CAAC,GAAG,CAAC,CAAC;IACxE3C,GAAG,CAACyC,SAAS,CAAC,kCAAkC,EAAEX,gBAAgB,GAAG,MAAM,GAAG,OAAO,CAAC;EACxF;EAEA,OAAOhC,iBAAiB,CAACC,GAAG,EAAEC,GAAG,CAAC;AACpC,CAAC","ignoreList":[]}
|
package/middleware/constants.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Object.defineProperty(exports, "__esModule", {
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
|
-
exports.fronteggSSOPathRewrite = exports.fronteggPathRewrite = void 0;
|
|
6
|
+
exports.fronteggSSOPathRewrite = exports.fronteggPathRewrite = exports.defaultFronteggHeaders = void 0;
|
|
7
7
|
const fronteggPathRewrite = exports.fronteggPathRewrite = [{
|
|
8
8
|
patternStr: '^/api/',
|
|
9
9
|
replaceStr: '/'
|
|
@@ -12,4 +12,5 @@ const fronteggSSOPathRewrite = exports.fronteggSSOPathRewrite = [{
|
|
|
12
12
|
patternStr: '/frontegg/saml/callback$',
|
|
13
13
|
replaceStr: '/auth/saml/callback'
|
|
14
14
|
}];
|
|
15
|
+
const defaultFronteggHeaders = exports.defaultFronteggHeaders = ['Content-Type', 'Authorization', 'x-frontegg-framework', 'x-frontegg-sdk', 'frontegg-source', 'frontegg-requested-application-id'];
|
|
15
16
|
//# sourceMappingURL=constants.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":["fronteggPathRewrite","exports","patternStr","replaceStr","fronteggSSOPathRewrite"],"sources":["../../../../packages/nextjs/src/middleware/constants.ts"],"sourcesContent":["export const fronteggPathRewrite = [\n {\n patternStr: '^/api/',\n replaceStr: '/',\n },\n];\nexport const fronteggSSOPathRewrite = [\n {\n patternStr: '/frontegg/saml/callback$',\n replaceStr: '/auth/saml/callback',\n },\n];\n"],"mappings":";;;;;;AAAO,MAAMA,mBAAmB,GAAAC,OAAA,CAAAD,mBAAA,GAAG,CACjC;EACEE,UAAU,EAAE,QAAQ;EACpBC,UAAU,EAAE;AACd,CAAC,CACF;AACM,MAAMC,sBAAsB,GAAAH,OAAA,CAAAG,sBAAA,GAAG,CACpC;EACEF,UAAU,EAAE,0BAA0B;EACtCC,UAAU,EAAE;AACd,CAAC,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"constants.js","names":["fronteggPathRewrite","exports","patternStr","replaceStr","fronteggSSOPathRewrite","defaultFronteggHeaders"],"sources":["../../../../packages/nextjs/src/middleware/constants.ts"],"sourcesContent":["export const fronteggPathRewrite = [\n {\n patternStr: '^/api/',\n replaceStr: '/',\n },\n];\nexport const fronteggSSOPathRewrite = [\n {\n patternStr: '/frontegg/saml/callback$',\n replaceStr: '/auth/saml/callback',\n },\n];\n\nexport const defaultFronteggHeaders = [\n 'Content-Type',\n 'Authorization',\n 'x-frontegg-framework',\n 'x-frontegg-sdk',\n 'frontegg-source',\n 'frontegg-requested-application-id',\n];\n"],"mappings":";;;;;;AAAO,MAAMA,mBAAmB,GAAAC,OAAA,CAAAD,mBAAA,GAAG,CACjC;EACEE,UAAU,EAAE,QAAQ;EACpBC,UAAU,EAAE;AACd,CAAC,CACF;AACM,MAAMC,sBAAsB,GAAAH,OAAA,CAAAG,sBAAA,GAAG,CACpC;EACEF,UAAU,EAAE,0BAA0B;EACtCC,UAAU,EAAE;AACd,CAAC,CACF;AAEM,MAAME,sBAAsB,GAAAJ,OAAA,CAAAI,sBAAA,GAAG,CACpC,cAAc,EACd,eAAe,EACf,sBAAsB,EACtB,gBAAgB,EAChB,iBAAiB,EACjB,mCAAmC,CACpC","ignoreList":[]}
|
package/middleware/helpers.d.ts
CHANGED
package/middleware/helpers.js
CHANGED
|
@@ -4,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
|
|
|
4
4
|
Object.defineProperty(exports, "__esModule", {
|
|
5
5
|
value: true
|
|
6
6
|
});
|
|
7
|
-
exports.rewritePath = exports.removeJwtSignatureFrom = exports.isFronteggOauthLogoutUrl = exports.isFronteggLogoutUrl = exports.getHostedLogoutUrl = exports.extractAccessToken = void 0;
|
|
7
|
+
exports.rewritePath = exports.removeJwtSignatureFrom = exports.isInternalRequest = exports.isFronteggOauthLogoutUrl = exports.isFronteggLogoutUrl = exports.getHostedLogoutUrl = exports.extractAccessToken = void 0;
|
|
8
8
|
var _urls = require("../api/urls");
|
|
9
9
|
var _config = _interopRequireDefault(require("../config"));
|
|
10
10
|
var _routing = require("../utils/routing");
|
|
@@ -120,4 +120,6 @@ const removeJwtSignatureFrom = body => {
|
|
|
120
120
|
return body;
|
|
121
121
|
};
|
|
122
122
|
exports.removeJwtSignatureFrom = removeJwtSignatureFrom;
|
|
123
|
+
const isInternalRequest = host => _config.default.appUrl.includes(host);
|
|
124
|
+
exports.isInternalRequest = isInternalRequest;
|
|
123
125
|
//# sourceMappingURL=helpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","names":["_urls","require","_config","_interopRequireDefault","_routing","rewritePath","url","pathRewrite","Array","isArray","item","patternStr","replaceStr","pattern","RegExp","test","replace","path","exports","isFronteggLogoutUrl","endsWith","isFronteggOauthLogoutUrl","getHostedLogoutUrl","referer","config","appUrl","_config$authRoutes$lo","_config$authRoutes","logoutPath","authRoutes","logoutUrl","defaultFronteggRoutes","refererUrl","URL","isLogoutRoute","toString","includes","redirectUrl","origin","search","buildLogoutRoute","baseUrl","extractAccessToken","bodyStr","body","JSON","parse","authResponse","Object","assign","accessToken","access_token","refreshToken","refresh_token","jwtKeys","refreshTokenKeys","removeJwtSignatureFrom","forEach","key","split"],"sources":["../../../../packages/nextjs/src/middleware/helpers.ts"],"sourcesContent":["import { BuildRouteResult, buildLogoutRoute } from '../api/urls';\nimport config from '../config';\nimport { defaultFronteggRoutes } from '../utils/routing';\n\n/**\n * If pattern information matching the input url information is found in the `pathRewrite` array,\n * the url value is partially replaced with the `pathRewrite.replaceStr` value.\n * @param url\n * @param pathRewrite\n */\nexport const rewritePath = (\n url: string,\n pathRewrite: { [key: string]: string } | { patternStr: string; replaceStr: string }[]\n) => {\n if (Array.isArray(pathRewrite)) {\n for (const item of pathRewrite) {\n const { patternStr, replaceStr } = item;\n const pattern = RegExp(patternStr);\n if (pattern.test(url as string)) {\n return url.replace(pattern, replaceStr);\n }\n }\n } else {\n for (const patternStr in pathRewrite) {\n const pattern = RegExp(patternStr);\n const path = pathRewrite[patternStr];\n if (pattern.test(url as string)) {\n return url.replace(pattern, path);\n }\n }\n }\n return url;\n};\n\n/**\n * Checks If route is a logout route\n * @param url\n */\nexport const isFronteggLogoutUrl = (url: string) => url.endsWith('/logout');\n\n/**\n * Checks If route is a hosted logout route\n * @param url\n */\nexport const isFronteggOauthLogoutUrl = (url: string) => url.endsWith('/oauth/logout');\n\n/**\n * Returns url to be redirected for hosted logout\n * @param referer the route to redirect to after logout\n */\nexport const getHostedLogoutUrl = (referer = config.appUrl): BuildRouteResult => {\n const logoutPath = config.authRoutes?.logoutUrl ?? defaultFronteggRoutes.logoutUrl;\n const refererUrl = new URL(referer);\n const isLogoutRoute = refererUrl.toString().includes(logoutPath);\n\n const redirectUrl = isLogoutRoute ? refererUrl.origin + refererUrl.search : refererUrl.toString();\n\n return buildLogoutRoute(redirectUrl, config.baseUrl);\n};\n\nexport type Tokens = {\n accessToken: string;\n refreshToken: string;\n};\n\n/**\n * Extracts the access token from the response body\n * @param bodyStr\n */\nexport const extractAccessToken = (bodyStr: string): Tokens => {\n const body = JSON.parse(bodyStr);\n\n if (body.authResponse) {\n Object.assign(body, body.authResponse);\n }\n return {\n accessToken: body.accessToken || body.access_token,\n refreshToken: body.refreshToken || body.refresh_token,\n };\n};\n\nconst jwtKeys = ['accessToken', 'access_token', 'idToken', 'id_token'];\nconst refreshTokenKeys = ['refreshToken', 'refresh_token'];\n/**\n * Removes the signature from the JWT token\n * @param body\n */\nexport const removeJwtSignatureFrom = <T extends any>(body: any): T => {\n if (!body) {\n return body;\n }\n\n if (body.authResponse) {\n jwtKeys.forEach((key) => {\n if (body.authResponse[key]) {\n // body.authResponse[key] = \"REDACTED_FOR_SECURITY\";\n // body.authResponse[key] = body.authResponse[key].split('.')[0] + '.' + body.authResponse[key].split('.')[1];\n body.authResponse[key] = `REDACTED_FOR_SECURITY.${body.authResponse[key].split('.')[1]}.REDACTED_FOR_SECURITY`;\n }\n });\n refreshTokenKeys.forEach((key) => {\n if (body.authResponse[key]) {\n delete body.authResponse[key];\n }\n });\n }\n\n jwtKeys.forEach((key) => {\n if (body[key]) {\n // body[key] = \"REDACTED_FOR_SECURITY\";\n // body[key] = body[key].split('.')[0] + '.' + body[key].split('.')[1];\n body[key] = `REDACTED_FOR_SECURITY.${body[key].split('.')[1]}.REDACTED_FOR_SECURITY`;\n }\n });\n refreshTokenKeys.forEach((key) => {\n if (body[key]) {\n delete body[key];\n }\n });\n return body;\n};\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMI,WAAW,GAAGA,CACzBC,GAAW,EACXC,WAAqF,KAClF;EACH,IAAIC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GAAG,CAAC,EAAE;QAC1B;QACA;QACAd,IAAI,CAACG,YAAY,CAACW,GAAG,CAAC,GAAG,yBAAyBd,IAAI,CAACG,YAAY,CAACW,GAAG,CAAC,CAACC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,wBAAwB;MAChH;IACF,CAAC,CAAC;IACFJ,gBAAgB,CAACE,OAAO,CAAEC,GAAG,IAAK;MAChC,IAAId,IAAI,CAACG,YAAY,CAACW,GAAG,CAAC,EAAE;QAC1B,OAAOd,IAAI,CAACG,YAAY,CAACW,GAAG,CAAC;MAC/B;IACF,CAAC,CAAC;EACJ;EAEAJ,OAAO,CAACG,OAAO,CAAEC,GAAG,IAAK;IACvB,IAAId,IAAI,CAACc,GAAG,CAAC,EAAE;MACb;MACA;MACAd,IAAI,CAACc,GAAG,CAAC,GAAG,yBAAyBd,IAAI,CAACc,GAAG,CAAC,CAACC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,wBAAwB;IACtF;EACF,CAAC,CAAC;EACFJ,gBAAgB,CAACE,OAAO,CAAEC,GAAG,IAAK;IAChC,IAAId,IAAI,CAACc,GAAG,CAAC,EAAE;MACb,OAAOd,IAAI,CAACc,GAAG,CAAC;IAClB;EACF,CAAC,CAAC;EACF,OAAOd,IAAI;AACb,CAAC;AAAC1B,OAAA,CAAAsC,sBAAA,GAAAA,sBAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"helpers.js","names":["_urls","require","_config","_interopRequireDefault","_routing","rewritePath","url","pathRewrite","Array","isArray","item","patternStr","replaceStr","pattern","RegExp","test","replace","path","exports","isFronteggLogoutUrl","endsWith","isFronteggOauthLogoutUrl","getHostedLogoutUrl","referer","config","appUrl","_config$authRoutes$lo","_config$authRoutes","logoutPath","authRoutes","logoutUrl","defaultFronteggRoutes","refererUrl","URL","isLogoutRoute","toString","includes","redirectUrl","origin","search","buildLogoutRoute","baseUrl","extractAccessToken","bodyStr","body","JSON","parse","authResponse","Object","assign","accessToken","access_token","refreshToken","refresh_token","jwtKeys","refreshTokenKeys","removeJwtSignatureFrom","forEach","key","split","isInternalRequest","host"],"sources":["../../../../packages/nextjs/src/middleware/helpers.ts"],"sourcesContent":["import { BuildRouteResult, buildLogoutRoute } from '../api/urls';\nimport config from '../config';\nimport { defaultFronteggRoutes } from '../utils/routing';\n\n/**\n * If pattern information matching the input url information is found in the `pathRewrite` array,\n * the url value is partially replaced with the `pathRewrite.replaceStr` value.\n * @param url\n * @param pathRewrite\n */\nexport const rewritePath = (\n url: string,\n pathRewrite: { [key: string]: string } | { patternStr: string; replaceStr: string }[]\n) => {\n if (Array.isArray(pathRewrite)) {\n for (const item of pathRewrite) {\n const { patternStr, replaceStr } = item;\n const pattern = RegExp(patternStr);\n if (pattern.test(url as string)) {\n return url.replace(pattern, replaceStr);\n }\n }\n } else {\n for (const patternStr in pathRewrite) {\n const pattern = RegExp(patternStr);\n const path = pathRewrite[patternStr];\n if (pattern.test(url as string)) {\n return url.replace(pattern, path);\n }\n }\n }\n return url;\n};\n\n/**\n * Checks If route is a logout route\n * @param url\n */\nexport const isFronteggLogoutUrl = (url: string) => url.endsWith('/logout');\n\n/**\n * Checks If route is a hosted logout route\n * @param url\n */\nexport const isFronteggOauthLogoutUrl = (url: string) => url.endsWith('/oauth/logout');\n\n/**\n * Returns url to be redirected for hosted logout\n * @param referer the route to redirect to after logout\n */\nexport const getHostedLogoutUrl = (referer = config.appUrl): BuildRouteResult => {\n const logoutPath = config.authRoutes?.logoutUrl ?? defaultFronteggRoutes.logoutUrl;\n const refererUrl = new URL(referer);\n const isLogoutRoute = refererUrl.toString().includes(logoutPath);\n\n const redirectUrl = isLogoutRoute ? refererUrl.origin + refererUrl.search : refererUrl.toString();\n\n return buildLogoutRoute(redirectUrl, config.baseUrl);\n};\n\nexport type Tokens = {\n accessToken: string;\n refreshToken: string;\n};\n\n/**\n * Extracts the access token from the response body\n * @param bodyStr\n */\nexport const extractAccessToken = (bodyStr: string): Tokens => {\n const body = JSON.parse(bodyStr);\n\n if (body.authResponse) {\n Object.assign(body, body.authResponse);\n }\n return {\n accessToken: body.accessToken || body.access_token,\n refreshToken: body.refreshToken || body.refresh_token,\n };\n};\n\nconst jwtKeys = ['accessToken', 'access_token', 'idToken', 'id_token'];\nconst refreshTokenKeys = ['refreshToken', 'refresh_token'];\n/**\n * Removes the signature from the JWT token\n * @param body\n */\nexport const removeJwtSignatureFrom = <T extends any>(body: any): T => {\n if (!body) {\n return body;\n }\n\n if (body.authResponse) {\n jwtKeys.forEach((key) => {\n if (body.authResponse[key]) {\n // body.authResponse[key] = \"REDACTED_FOR_SECURITY\";\n // body.authResponse[key] = body.authResponse[key].split('.')[0] + '.' + body.authResponse[key].split('.')[1];\n body.authResponse[key] = `REDACTED_FOR_SECURITY.${body.authResponse[key].split('.')[1]}.REDACTED_FOR_SECURITY`;\n }\n });\n refreshTokenKeys.forEach((key) => {\n if (body.authResponse[key]) {\n delete body.authResponse[key];\n }\n });\n }\n\n jwtKeys.forEach((key) => {\n if (body[key]) {\n // body[key] = \"REDACTED_FOR_SECURITY\";\n // body[key] = body[key].split('.')[0] + '.' + body[key].split('.')[1];\n body[key] = `REDACTED_FOR_SECURITY.${body[key].split('.')[1]}.REDACTED_FOR_SECURITY`;\n }\n });\n refreshTokenKeys.forEach((key) => {\n if (body[key]) {\n delete body[key];\n }\n });\n return body;\n};\n\nexport const isInternalRequest = (host: string) => config.appUrl.includes(host);\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMI,WAAW,GAAGA,CACzBC,GAAW,EACXC,WAAqF,KAClF;EACH,IAAIC,KAAK,CAACC,OAAO,CAACF,WAAW,CAAC,EAAE;IAC9B,KAAK,MAAMG,IAAI,IAAIH,WAAW,EAAE;MAC9B,MAAM;QAAEI,UAAU;QAA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AAC,CAACC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,wBAAwB;MAChH;IACF,CAAC,CAAC;IACFJ,gBAAgB,CAACE,OAAO,CAAEC,GAAG,IAAK;MAChC,IAAId,IAAI,CAACG,YAAY,CAACW,GAAG,CAAC,EAAE;QAC1B,OAAOd,IAAI,CAACG,YAAY,CAACW,GAAG,CAAC;MAC/B;IACF,CAAC,CAAC;EACJ;EAEAJ,OAAO,CAACG,OAAO,CAAEC,GAAG,IAAK;IACvB,IAAId,IAAI,CAACc,GAAG,CAAC,EAAE;MACb;MACA;MACAd,IAAI,CAACc,GAAG,CAAC,GAAG,yBAAyBd,IAAI,CAACc,GAAG,CAAC,CAACC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,wBAAwB;IACtF;EACF,CAAC,CAAC;EACFJ,gBAAgB,CAACE,OAAO,CAAEC,GAAG,IAAK;IAChC,IAAId,IAAI,CAACc,GAAG,CAAC,EAAE;MACb,OAAOd,IAAI,CAACc,GAAG,CAAC;IAClB;EACF,CAAC,CAAC;EACF,OAAOd,IAAI;AACb,CAAC;AAAC1B,OAAA,CAAAsC,sBAAA,GAAAA,sBAAA;AAEK,MAAMI,iBAAiB,GAAIC,IAAY,IAAKrC,eAAM,CAACC,MAAM,CAACW,QAAQ,CAACyB,IAAI,CAAC;AAAC3C,OAAA,CAAA0C,iBAAA,GAAAA,iBAAA","ignoreList":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
2
|
+
export type CorsOptions = {
|
|
3
|
+
allowedOrigins?: string[];
|
|
4
|
+
allowedMethods?: string[];
|
|
5
|
+
allowedHeaders?: string[];
|
|
6
|
+
allowCredentials?: boolean;
|
|
7
|
+
};
|
|
8
|
+
export type FronteggApiMiddlewareType = ((req: NextApiRequest, res: NextApiResponse) => Promise<void>) & {
|
|
9
|
+
cors: (options: CorsOptions) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
|
|
10
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../packages/nextjs/src/middleware/types.ts"],"sourcesContent":["import type { NextApiRequest, NextApiResponse } from 'next';\n\nexport type CorsOptions = {\n allowedOrigins?: string[];\n allowedMethods?: string[];\n allowedHeaders?: string[];\n allowCredentials?: boolean;\n};\n\nexport type FronteggApiMiddlewareType = ((req: NextApiRequest, res: NextApiResponse) => Promise<void>) & {\n cors: (options: CorsOptions) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;\n};\n"],"mappings":"","ignoreList":[]}
|
package/package.json
CHANGED
package/sdkVersion.js
CHANGED
package/sdkVersion.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdkVersion.js","names":["version"],"sources":["../../../packages/nextjs/src/sdkVersion.ts"],"sourcesContent":["export default { version: '9.2.
|
|
1
|
+
{"version":3,"file":"sdkVersion.js","names":["version"],"sources":["../../../packages/nextjs/src/sdkVersion.ts"],"sourcesContent":["export default { version: '9.2.1-alpha.12073075767' };\n"],"mappings":";;;;;;iCAAe;EAAEA,OAAO,EAAE;AAA0B,CAAC","ignoreList":[]}
|