@descope/nextjs-sdk 0.14.50 → 0.14.51
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/dist/cjs/server/authMiddleware.js +6 -12
- package/dist/cjs/server/authMiddleware.js.map +1 -1
- package/dist/cjs/server/constants.js +1 -1
- package/dist/cjs/server/session.js +17 -25
- package/dist/cjs/server/session.js.map +1 -1
- package/dist/cjs/shared/constants.js +1 -1
- package/dist/esm/server/authMiddleware.js +6 -12
- package/dist/esm/server/authMiddleware.js.map +1 -1
- package/dist/esm/server/constants.js +1 -1
- package/dist/esm/server/session.js +17 -25
- package/dist/esm/server/session.js.map +1 -1
- package/dist/esm/shared/constants.js +1 -1
- package/package.json +3 -3
|
@@ -44,25 +44,20 @@ const isPublicRoute = (req, options) => {
|
|
|
44
44
|
// If no routes are provided, all routes are private
|
|
45
45
|
return isDefaultPublicRoute;
|
|
46
46
|
};
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
return requestHeaders;
|
|
52
|
-
}
|
|
53
|
-
return headers;
|
|
47
|
+
const removeSessionHeader = (headers) => {
|
|
48
|
+
const requestHeaders = new Headers(headers);
|
|
49
|
+
requestHeaders.delete(constants.DESCOPE_SESSION_HEADER);
|
|
50
|
+
return requestHeaders;
|
|
54
51
|
};
|
|
55
52
|
// returns a Middleware that checks if the user is authenticated
|
|
56
53
|
// if the user is not authenticated, it redirects to the redirectUrl
|
|
57
|
-
// if the user is authenticated, it adds the session to the headers
|
|
58
54
|
const createAuthMiddleware = (options = {}) => async (req) => {
|
|
59
55
|
logger.setLogger(options.logLevel);
|
|
60
56
|
logger.logger.debug('Auth middleware starts');
|
|
61
57
|
const jwt = getSessionJwt(req, options);
|
|
62
58
|
// check if the user is authenticated
|
|
63
|
-
let session;
|
|
64
59
|
try {
|
|
65
|
-
|
|
60
|
+
await sdk.getGlobalSdk({
|
|
66
61
|
projectId: options.projectId,
|
|
67
62
|
baseUrl: options.baseUrl
|
|
68
63
|
}).validateJwt(jwt);
|
|
@@ -84,8 +79,7 @@ const createAuthMiddleware = (options = {}) => async (req) => {
|
|
|
84
79
|
}
|
|
85
80
|
}
|
|
86
81
|
logger.logger.debug('Auth middleware finishes');
|
|
87
|
-
|
|
88
|
-
const headers = addSessionToHeadersIfExists(req.headers, session);
|
|
82
|
+
const headers = removeSessionHeader(req.headers);
|
|
89
83
|
return server_js.NextResponse.next({
|
|
90
84
|
request: {
|
|
91
85
|
headers
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport
|
|
1
|
+
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER } from './constants';\nimport { getGlobalSdk } from './sdk';\nimport { mergeSearchParams } from './utils';\nimport { LogLevel } from '../types';\nimport { logger, setLogger } from './logger';\n\ntype MiddlewareOptions = {\n\t// The Descope project ID to use for authentication\n\t// Defaults to process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID\n\tprojectId?: string;\n\n\t// The base URL to use for authentication\n\t// Defaults to process.env.NEXT_PUBLIC_DESCOPE_BASE_URL\n\tbaseUrl?: string;\n\n\t// The URL to redirect to if the user is not authenticated\n\t// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided\n\t// NOTE: In case it contains query parameters that exist in the original URL, they will override the original query parameters. e.g. if the original URL is /page?param1=1¶m2=2 and the redirect URL is /sign-in?param1=3, the final redirect URL will be /sign-in?param1=3¶m2=2\n\tredirectUrl?: string;\n\n\t// An array of public routes that do not require authentication\n\t// In addition to the default public routes:\n\t// - process.env.SIGN_IN_ROUTE or /sign-in if not provided\n\t// - process.env.SIGN_UP_ROUTE or /sign-up if not provided\n\tpublicRoutes?: string[];\n\n\t// An array of private routes that require authentication\n\t// If privateRoutes is defined, routes not listed in this array will default to public routes\n\tprivateRoutes?: string[];\n\n\t// The log level to use for the middleware\n\t// Defaults to 'info'\n\tlogLevel?: LogLevel;\n\n\t// The name of the session cookie to look for the JWT\n\t// Defaults to 'DS'\n\t// Note: The middleware will also look for the JWT in the Authorization header\n\tsessionCookieName?: string;\n};\n\nconst getSessionJwt = (\n\treq: NextRequest,\n\toptions: MiddlewareOptions\n): string | undefined => {\n\tlet jwt = req.headers?.get('Authorization')?.split(' ')[1];\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\n\tjwt = req.cookies?.get(\n\t\toptions?.sessionCookieName || descopeSdk.SessionTokenCookieName\n\t)?.value;\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\treturn undefined;\n};\n\nconst matchWildcardRoute = (route: string, path: string) => {\n\tlet regexPattern = route.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n\t// Convert wildcard (*) to match path segments only\n\tregexPattern = regexPattern.replace(/\\*/g, '[^/]*');\n\tconst regex = new RegExp(`^${regexPattern}$`);\n\n\treturn regex.test(path);\n};\n\nconst isPublicRoute = (req: NextRequest, options: MiddlewareOptions) => {\n\t// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined\n\tconst { publicRoutes = [], privateRoutes = [] } = options;\n\tconst { pathname } = req.nextUrl;\n\n\tconst isDefaultPublicRoute = Object.values(DEFAULT_PUBLIC_ROUTES).includes(\n\t\tpathname\n\t);\n\n\tif (publicRoutes.length > 0) {\n\t\tif (privateRoutes.length > 0) {\n\t\t\tlogger.warn(\n\t\t\t\t'Both publicRoutes and privateRoutes are defined. Ignoring privateRoutes.'\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\tisDefaultPublicRoute ||\n\t\t\tpublicRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t\t);\n\t}\n\n\tif (privateRoutes.length > 0) {\n\t\treturn (\n\t\t\tisDefaultPublicRoute ||\n\t\t\t!privateRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t\t);\n\t}\n\n\t// If no routes are provided, all routes are private\n\treturn isDefaultPublicRoute;\n};\n\nconst removeSessionHeader = (headers: Headers): Headers => {\n\tconst requestHeaders = new Headers(headers);\n\trequestHeaders.delete(DESCOPE_SESSION_HEADER);\n\treturn requestHeaders;\n};\n\n// returns a Middleware that checks if the user is authenticated\n// if the user is not authenticated, it redirects to the redirectUrl\nconst createAuthMiddleware =\n\t(options: MiddlewareOptions = {}) =>\n\tasync (req: NextRequest) => {\n\t\tsetLogger(options.logLevel);\n\t\tlogger.debug('Auth middleware starts');\n\n\t\tconst jwt = getSessionJwt(req, options);\n\n\t\t// check if the user is authenticated\n\t\ttry {\n\t\t\tawait getGlobalSdk({\n\t\t\t\tprojectId: options.projectId,\n\t\t\t\tbaseUrl: options.baseUrl\n\t\t\t}).validateJwt(jwt);\n\t\t} catch (err) {\n\t\t\tlogger.debug('Auth middleware, Failed to validate JWT', err);\n\t\t\tif (!isPublicRoute(req, options)) {\n\t\t\t\tconst redirectUrl = options.redirectUrl || DEFAULT_PUBLIC_ROUTES.signIn;\n\t\t\t\tconst url = req.nextUrl.clone();\n\t\t\t\t// Create a URL object for redirectUrl. 'http://example.com' is just a placeholder.\n\t\t\t\tconst parsedRedirectUrl = new URL(redirectUrl, 'http://example.com');\n\t\t\t\turl.pathname = parsedRedirectUrl.pathname;\n\n\t\t\t\tconst searchParams = mergeSearchParams(\n\t\t\t\t\turl.search,\n\t\t\t\t\tparsedRedirectUrl.search\n\t\t\t\t);\n\t\t\t\tif (searchParams) {\n\t\t\t\t\turl.search = searchParams;\n\t\t\t\t}\n\t\t\t\tlogger.debug(`Auth middleware, Redirecting to ${redirectUrl}`);\n\t\t\t\treturn NextResponse.redirect(url);\n\t\t\t}\n\t\t}\n\n\t\tlogger.debug('Auth middleware finishes');\n\t\tconst headers = removeSessionHeader(req.headers);\n\t\treturn NextResponse.next({\n\t\t\trequest: {\n\t\t\t\theaders\n\t\t\t}\n\t\t});\n\t};\n\nexport default createAuthMiddleware;\n"],"names":["DEFAULT_PUBLIC_ROUTES","logger","DESCOPE_SESSION_HEADER","setLogger","getGlobalSdk","mergeSearchParams","NextResponse"],"mappings":";;;;;;;;;AA0CA,MAAM,aAAa,GAAG,CACrB,GAAgB,EAChB,OAA0B,KACH;AACvB,IAAA,IAAI,GAAG,GAAG,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,eAAe,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3D,IAAI,GAAG,EAAE;AACR,QAAA,OAAO,GAAG,CAAC;KACX;AAED,IAAA,GAAG,GAAG,GAAG,CAAC,OAAO,EAAE,GAAG,CACrB,OAAO,EAAE,iBAAiB,IAAI,UAAU,CAAC,sBAAsB,CAC/D,EAAE,KAAK,CAAC;IACT,IAAI,GAAG,EAAE;AACR,QAAA,OAAO,GAAG,CAAC;KACX;AACD,IAAA,OAAO,SAAS,CAAC;AAClB,CAAC,CAAC;AAEF,MAAM,kBAAkB,GAAG,CAAC,KAAa,EAAE,IAAY,KAAI;IAC1D,IAAI,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC;;IAG/D,YAAY,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACpD,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,CAAI,CAAA,EAAA,YAAY,CAAG,CAAA,CAAA,CAAC,CAAC;AAE9C,IAAA,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC,CAAC;AAEF,MAAM,aAAa,GAAG,CAAC,GAAgB,EAAE,OAA0B,KAAI;;IAEtE,MAAM,EAAE,YAAY,GAAG,EAAE,EAAE,aAAa,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC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3
|
const DESCOPE_SESSION_HEADER = 'x-descope-session';
|
|
4
4
|
const baseHeaders = {
|
|
5
5
|
'x-descope-sdk-name': 'nextjs',
|
|
6
|
-
'x-descope-sdk-version': "0.14.
|
|
6
|
+
'x-descope-sdk-version': "0.14.51"
|
|
7
7
|
};
|
|
8
8
|
const DEFAULT_PUBLIC_ROUTES = {
|
|
9
9
|
signIn: process.env.SIGN_IN_ROUTE || '/sign-in',
|
|
@@ -2,22 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
var descopeSdk = require('@descope/node-sdk');
|
|
4
4
|
var headers_js = require('next/headers.js');
|
|
5
|
-
var constants = require('./constants.js');
|
|
6
5
|
var sdk = require('./sdk.js');
|
|
7
6
|
var logger = require('./logger.js');
|
|
8
7
|
|
|
9
|
-
const extractSession = (descopeSession) => {
|
|
10
|
-
if (!descopeSession) {
|
|
11
|
-
return undefined;
|
|
12
|
-
}
|
|
13
|
-
try {
|
|
14
|
-
const authInfo = JSON.parse(Buffer.from(descopeSession, 'base64').toString());
|
|
15
|
-
return authInfo;
|
|
16
|
-
}
|
|
17
|
-
catch (err) {
|
|
18
|
-
return undefined;
|
|
19
|
-
}
|
|
20
|
-
};
|
|
21
8
|
const getSessionFromCookie = async (config) => {
|
|
22
9
|
logger.logger.debug('attempting to get session from cookie');
|
|
23
10
|
try {
|
|
@@ -34,27 +21,32 @@ const getSessionFromCookie = async (config) => {
|
|
|
34
21
|
return undefined;
|
|
35
22
|
}
|
|
36
23
|
};
|
|
37
|
-
// tries to
|
|
38
|
-
// if it doesn't exist, it will attempt to get the session from the cookie
|
|
39
|
-
const
|
|
40
|
-
const
|
|
41
|
-
if (
|
|
42
|
-
|
|
24
|
+
// tries to validate the Authorization header,
|
|
25
|
+
// if it doesn't exist or is invalid, it will attempt to get the session from the cookie
|
|
26
|
+
const getSessionFromAuthorizationOrCookie = async (authorization, config) => {
|
|
27
|
+
const sessionJwt = authorization?.split(' ')[1];
|
|
28
|
+
if (sessionJwt) {
|
|
29
|
+
try {
|
|
30
|
+
const sdk$1 = sdk.getGlobalSdk(config);
|
|
31
|
+
return await sdk$1.validateJwt(sessionJwt);
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
logger.logger.debug('Error validating session from Authorization header', err);
|
|
35
|
+
}
|
|
43
36
|
}
|
|
44
37
|
return getSessionFromCookie(config);
|
|
45
38
|
};
|
|
46
|
-
// returns the session token if it exists in the
|
|
39
|
+
// returns the session token if it exists in the Authorization header or cookie
|
|
47
40
|
const session = async (config) => {
|
|
48
41
|
logger.setLogger(config?.logLevel);
|
|
49
|
-
// first attempt to get the session from the headers
|
|
50
42
|
const reqHeaders = await headers_js.headers();
|
|
51
|
-
|
|
52
|
-
return extractOrGetSession(sessionHeader, config);
|
|
43
|
+
return getSessionFromAuthorizationOrCookie(reqHeaders.get('Authorization'), config);
|
|
53
44
|
};
|
|
54
|
-
// returns the session token if it exists in the request
|
|
45
|
+
// returns the session token if it exists in the request Authorization header or cookie
|
|
55
46
|
const getSession = async (req, config) => {
|
|
56
47
|
logger.setLogger(config?.logLevel);
|
|
57
|
-
|
|
48
|
+
const { authorization } = req.headers;
|
|
49
|
+
return getSessionFromAuthorizationOrCookie(typeof authorization === 'string' ? authorization : undefined, config);
|
|
58
50
|
};
|
|
59
51
|
|
|
60
52
|
exports.getSession = getSession;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sources":["../../../src/server/session.ts"],"sourcesContent":["import descopeSdk, { AuthenticationInfo } from '@descope/node-sdk';\nimport { NextApiRequest } from 'next';\nimport { cookies, headers } from 'next/headers';\nimport {
|
|
1
|
+
{"version":3,"file":"session.js","sources":["../../../src/server/session.ts"],"sourcesContent":["import descopeSdk, { AuthenticationInfo } from '@descope/node-sdk';\nimport { NextApiRequest } from 'next';\nimport { cookies, headers } from 'next/headers';\nimport { getGlobalSdk, CreateSdkParams } from './sdk';\nimport { LogLevel } from '../types';\nimport { logger, setLogger } from './logger';\n\ntype SessionConfig = CreateSdkParams & {\n\t// The log level to use for the middleware\n\t// Defaults to 'info'\n\tlogLevel?: LogLevel;\n\n\t// The name of the session cookie to look for the JWT\n\t// Defaults to 'DS'\n\t// Note: The middleware will also look for the JWT in the Authorization header\n\tsessionCookieName?: string;\n};\nconst getSessionFromCookie = async (\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tlogger.debug('attempting to get session from cookie');\n\ttry {\n\t\tconst sessionCookie = (await cookies()).get(\n\t\t\tconfig?.sessionCookieName || descopeSdk.SessionTokenCookieName\n\t\t);\n\t\tif (!sessionCookie?.value) {\n\t\t\tlogger.debug('Session cookie not found');\n\t\t\treturn undefined;\n\t\t}\n\t\tconst sdk = getGlobalSdk(config);\n\t\treturn await sdk.validateJwt(sessionCookie.value);\n\t} catch (err) {\n\t\tlogger.debug('Error getting session from cookie', err);\n\t\treturn undefined;\n\t}\n};\n\n// tries to validate the Authorization header,\n// if it doesn't exist or is invalid, it will attempt to get the session from the cookie\nconst getSessionFromAuthorizationOrCookie = async (\n\tauthorization?: string | null,\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tconst sessionJwt = authorization?.split(' ')[1];\n\tif (sessionJwt) {\n\t\ttry {\n\t\t\tconst sdk = getGlobalSdk(config);\n\t\t\treturn await sdk.validateJwt(sessionJwt);\n\t\t} catch (err) {\n\t\t\tlogger.debug('Error validating session from Authorization header', err);\n\t\t}\n\t}\n\n\treturn getSessionFromCookie(config);\n};\n\n// returns the session token if it exists in the Authorization header or cookie\nexport const session = async (\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tsetLogger(config?.logLevel);\n\tconst reqHeaders = await headers();\n\treturn getSessionFromAuthorizationOrCookie(\n\t\treqHeaders.get('Authorization'),\n\t\tconfig\n\t);\n};\n\n// returns the session token if it exists in the request Authorization header or cookie\nexport const getSession = async (\n\treq: NextApiRequest,\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tsetLogger(config?.logLevel);\n\tconst { authorization } = req.headers;\n\treturn getSessionFromAuthorizationOrCookie(\n\t\ttypeof authorization === 'string' ? authorization : undefined,\n\t\tconfig\n\t);\n};\n"],"names":["logger","cookies","sdk","getGlobalSdk","setLogger","headers"],"mappings":";;;;;;;AAiBA,MAAM,oBAAoB,GAAG,OAC5B,MAAsB,KACsB;AAC5C,IAAAA,aAAM,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACtD,IAAA,IAAI;AACH,QAAA,MAAM,aAAa,GAAG,CAAC,MAAMC,kBAAO,EAAE,EAAE,GAAG,CAC1C,MAAM,EAAE,iBAAiB,IAAI,UAAU,CAAC,sBAAsB,CAC9D,CAAC;AACF,QAAA,IAAI,CAAC,aAAa,EAAE,KAAK,EAAE;AAC1B,YAAAD,aAAM,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;AACzC,YAAA,OAAO,SAAS,CAAC;SACjB;AACD,QAAA,MAAME,KAAG,GAAGC,gBAAY,CAAC,MAAM,CAAC,CAAC;QACjC,OAAO,MAAMD,KAAG,CAAC,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;KAClD;IAAC,OAAO,GAAG,EAAE;AACb,QAAAF,aAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAC;AACvD,QAAA,OAAO,SAAS,CAAC;KACjB;AACF,CAAC,CAAC;AAEF;AACA;AACA,MAAM,mCAAmC,GAAG,OAC3C,aAA6B,EAC7B,MAAsB,KACsB;IAC5C,MAAM,UAAU,GAAG,aAAa,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,IAAI,UAAU,EAAE;AACf,QAAA,IAAI;AACH,YAAA,MAAME,KAAG,GAAGC,gBAAY,CAAC,MAAM,CAAC,CAAC;AACjC,YAAA,OAAO,MAAMD,KAAG,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;SACzC;QAAC,OAAO,GAAG,EAAE;AACb,YAAAF,aAAM,CAAC,KAAK,CAAC,oDAAoD,EAAE,GAAG,CAAC,CAAC;SACxE;KACD;AAED,IAAA,OAAO,oBAAoB,CAAC,MAAM,CAAC,CAAC;AACrC,CAAC,CAAC;AAEF;MACa,OAAO,GAAG,OACtB,MAAsB,KACsB;AAC5C,IAAAI,gBAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC5B,IAAA,MAAM,UAAU,GAAG,MAAMC,kBAAO,EAAE,CAAC;IACnC,OAAO,mCAAmC,CACzC,UAAU,CAAC,GAAG,CAAC,eAAe,CAAC,EAC/B,MAAM,CACN,CAAC;AACH,EAAE;AAEF;AACa,MAAA,UAAU,GAAG,OACzB,GAAmB,EACnB,MAAsB,KACsB;AAC5C,IAAAD,gBAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC5B,IAAA,MAAM,EAAE,aAAa,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC;AACtC,IAAA,OAAO,mCAAmC,CACzC,OAAO,aAAa,KAAK,QAAQ,GAAG,aAAa,GAAG,SAAS,EAC7D,MAAM,CACN,CAAC;AACH;;;;;"}
|
|
@@ -42,25 +42,20 @@ const isPublicRoute = (req, options) => {
|
|
|
42
42
|
// If no routes are provided, all routes are private
|
|
43
43
|
return isDefaultPublicRoute;
|
|
44
44
|
};
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
return requestHeaders;
|
|
50
|
-
}
|
|
51
|
-
return headers;
|
|
45
|
+
const removeSessionHeader = (headers) => {
|
|
46
|
+
const requestHeaders = new Headers(headers);
|
|
47
|
+
requestHeaders.delete(DESCOPE_SESSION_HEADER);
|
|
48
|
+
return requestHeaders;
|
|
52
49
|
};
|
|
53
50
|
// returns a Middleware that checks if the user is authenticated
|
|
54
51
|
// if the user is not authenticated, it redirects to the redirectUrl
|
|
55
|
-
// if the user is authenticated, it adds the session to the headers
|
|
56
52
|
const createAuthMiddleware = (options = {}) => async (req) => {
|
|
57
53
|
setLogger(options.logLevel);
|
|
58
54
|
logger.debug('Auth middleware starts');
|
|
59
55
|
const jwt = getSessionJwt(req, options);
|
|
60
56
|
// check if the user is authenticated
|
|
61
|
-
let session;
|
|
62
57
|
try {
|
|
63
|
-
|
|
58
|
+
await getGlobalSdk({
|
|
64
59
|
projectId: options.projectId,
|
|
65
60
|
baseUrl: options.baseUrl
|
|
66
61
|
}).validateJwt(jwt);
|
|
@@ -82,8 +77,7 @@ const createAuthMiddleware = (options = {}) => async (req) => {
|
|
|
82
77
|
}
|
|
83
78
|
}
|
|
84
79
|
logger.debug('Auth middleware finishes');
|
|
85
|
-
|
|
86
|
-
const headers = addSessionToHeadersIfExists(req.headers, session);
|
|
80
|
+
const headers = removeSessionHeader(req.headers);
|
|
87
81
|
return NextResponse.next({
|
|
88
82
|
request: {
|
|
89
83
|
headers
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport
|
|
1
|
+
{"version":3,"file":"authMiddleware.js","sources":["../../../src/server/authMiddleware.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server';\nimport descopeSdk from '@descope/node-sdk';\nimport { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER } from './constants';\nimport { getGlobalSdk } from './sdk';\nimport { mergeSearchParams } from './utils';\nimport { LogLevel } from '../types';\nimport { logger, setLogger } from './logger';\n\ntype MiddlewareOptions = {\n\t// The Descope project ID to use for authentication\n\t// Defaults to process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID\n\tprojectId?: string;\n\n\t// The base URL to use for authentication\n\t// Defaults to process.env.NEXT_PUBLIC_DESCOPE_BASE_URL\n\tbaseUrl?: string;\n\n\t// The URL to redirect to if the user is not authenticated\n\t// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided\n\t// NOTE: In case it contains query parameters that exist in the original URL, they will override the original query parameters. e.g. if the original URL is /page?param1=1¶m2=2 and the redirect URL is /sign-in?param1=3, the final redirect URL will be /sign-in?param1=3¶m2=2\n\tredirectUrl?: string;\n\n\t// An array of public routes that do not require authentication\n\t// In addition to the default public routes:\n\t// - process.env.SIGN_IN_ROUTE or /sign-in if not provided\n\t// - process.env.SIGN_UP_ROUTE or /sign-up if not provided\n\tpublicRoutes?: string[];\n\n\t// An array of private routes that require authentication\n\t// If privateRoutes is defined, routes not listed in this array will default to public routes\n\tprivateRoutes?: string[];\n\n\t// The log level to use for the middleware\n\t// Defaults to 'info'\n\tlogLevel?: LogLevel;\n\n\t// The name of the session cookie to look for the JWT\n\t// Defaults to 'DS'\n\t// Note: The middleware will also look for the JWT in the Authorization header\n\tsessionCookieName?: string;\n};\n\nconst getSessionJwt = (\n\treq: NextRequest,\n\toptions: MiddlewareOptions\n): string | undefined => {\n\tlet jwt = req.headers?.get('Authorization')?.split(' ')[1];\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\n\tjwt = req.cookies?.get(\n\t\toptions?.sessionCookieName || descopeSdk.SessionTokenCookieName\n\t)?.value;\n\tif (jwt) {\n\t\treturn jwt;\n\t}\n\treturn undefined;\n};\n\nconst matchWildcardRoute = (route: string, path: string) => {\n\tlet regexPattern = route.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n\t// Convert wildcard (*) to match path segments only\n\tregexPattern = regexPattern.replace(/\\*/g, '[^/]*');\n\tconst regex = new RegExp(`^${regexPattern}$`);\n\n\treturn regex.test(path);\n};\n\nconst isPublicRoute = (req: NextRequest, options: MiddlewareOptions) => {\n\t// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined\n\tconst { publicRoutes = [], privateRoutes = [] } = options;\n\tconst { pathname } = req.nextUrl;\n\n\tconst isDefaultPublicRoute = Object.values(DEFAULT_PUBLIC_ROUTES).includes(\n\t\tpathname\n\t);\n\n\tif (publicRoutes.length > 0) {\n\t\tif (privateRoutes.length > 0) {\n\t\t\tlogger.warn(\n\t\t\t\t'Both publicRoutes and privateRoutes are defined. Ignoring privateRoutes.'\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\tisDefaultPublicRoute ||\n\t\t\tpublicRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t\t);\n\t}\n\n\tif (privateRoutes.length > 0) {\n\t\treturn (\n\t\t\tisDefaultPublicRoute ||\n\t\t\t!privateRoutes.some((route) => matchWildcardRoute(route, pathname))\n\t\t);\n\t}\n\n\t// If no routes are provided, all routes are private\n\treturn isDefaultPublicRoute;\n};\n\nconst removeSessionHeader = (headers: Headers): Headers => {\n\tconst requestHeaders = new Headers(headers);\n\trequestHeaders.delete(DESCOPE_SESSION_HEADER);\n\treturn requestHeaders;\n};\n\n// returns a Middleware that checks if the user is authenticated\n// if the user is not authenticated, it redirects to the redirectUrl\nconst createAuthMiddleware =\n\t(options: MiddlewareOptions = {}) =>\n\tasync (req: NextRequest) => {\n\t\tsetLogger(options.logLevel);\n\t\tlogger.debug('Auth middleware starts');\n\n\t\tconst jwt = getSessionJwt(req, options);\n\n\t\t// check if the user is authenticated\n\t\ttry {\n\t\t\tawait getGlobalSdk({\n\t\t\t\tprojectId: options.projectId,\n\t\t\t\tbaseUrl: options.baseUrl\n\t\t\t}).validateJwt(jwt);\n\t\t} catch (err) {\n\t\t\tlogger.debug('Auth middleware, Failed to validate JWT', err);\n\t\t\tif (!isPublicRoute(req, options)) {\n\t\t\t\tconst redirectUrl = options.redirectUrl || DEFAULT_PUBLIC_ROUTES.signIn;\n\t\t\t\tconst url = req.nextUrl.clone();\n\t\t\t\t// Create a URL object for redirectUrl. 'http://example.com' is just a placeholder.\n\t\t\t\tconst parsedRedirectUrl = new URL(redirectUrl, 'http://example.com');\n\t\t\t\turl.pathname = parsedRedirectUrl.pathname;\n\n\t\t\t\tconst searchParams = mergeSearchParams(\n\t\t\t\t\turl.search,\n\t\t\t\t\tparsedRedirectUrl.search\n\t\t\t\t);\n\t\t\t\tif (searchParams) {\n\t\t\t\t\turl.search = searchParams;\n\t\t\t\t}\n\t\t\t\tlogger.debug(`Auth middleware, Redirecting to ${redirectUrl}`);\n\t\t\t\treturn NextResponse.redirect(url);\n\t\t\t}\n\t\t}\n\n\t\tlogger.debug('Auth middleware finishes');\n\t\tconst headers = removeSessionHeader(req.headers);\n\t\treturn NextResponse.next({\n\t\t\trequest: {\n\t\t\t\theaders\n\t\t\t}\n\t\t});\n\t};\n\nexport default createAuthMiddleware;\n"],"names":[],"mappings":";;;;;;;AA0CA,MAAM,aAAa,GAAG,CACrB,GAAgB,EAChB,OAA0B,KACH;AACvB,IAAA,IAAI,GAAG,GAAG,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,eAAe,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3D,IAAI,GAAG,EAAE;AACR,QAAA,OAAO,GAAG,CAAC;KACX;AAED,IAAA,GAAG,GAAG,GAAG,CAAC,OAAO,EAAE,GAAG,CACrB,OAAO,EAAE,iBAAiB,IAAI,UAAU,CAAC,sBAAsB,CAC/D,EAAE,KAAK,CAAC;IACT,IAAI,GAAG,EAAE;AACR,QAAA,OAAO,GAAG,CAAC;KACX;AACD,IAAA,OAAO,SAAS,CAAC;AAClB,CAAC,CAAC;AAEF,MAAM,kBAAkB,GAAG,CAAC,KAAa,EAAE,IAAY,KAAI;IAC1D,IAAI,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC;;IAG/D,YAAY,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACpD,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,CAAI,CAAA,EAAA,YAAY,CAAG,CAAA,CAAA,CAAC,CAAC;AAE9C,IAAA,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC,CAAC;AAEF,MAA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ACxB,QAAA,OAAO,EAAE;YACR,OAAO;AACP,SAAA;AACD,KAAA,CAAC,CAAC;AACJ;;;;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const DESCOPE_SESSION_HEADER = 'x-descope-session';
|
|
2
2
|
const baseHeaders = {
|
|
3
3
|
'x-descope-sdk-name': 'nextjs',
|
|
4
|
-
'x-descope-sdk-version': "0.14.
|
|
4
|
+
'x-descope-sdk-version': "0.14.51"
|
|
5
5
|
};
|
|
6
6
|
const DEFAULT_PUBLIC_ROUTES = {
|
|
7
7
|
signIn: process.env.SIGN_IN_ROUTE || '/sign-in',
|
|
@@ -1,21 +1,8 @@
|
|
|
1
1
|
import descopeSdk from '@descope/node-sdk';
|
|
2
2
|
import { headers, cookies } from 'next/headers.js';
|
|
3
|
-
import { DESCOPE_SESSION_HEADER } from './constants.js';
|
|
4
3
|
import { getGlobalSdk } from './sdk.js';
|
|
5
4
|
import { setLogger, logger } from './logger.js';
|
|
6
5
|
|
|
7
|
-
const extractSession = (descopeSession) => {
|
|
8
|
-
if (!descopeSession) {
|
|
9
|
-
return undefined;
|
|
10
|
-
}
|
|
11
|
-
try {
|
|
12
|
-
const authInfo = JSON.parse(Buffer.from(descopeSession, 'base64').toString());
|
|
13
|
-
return authInfo;
|
|
14
|
-
}
|
|
15
|
-
catch (err) {
|
|
16
|
-
return undefined;
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
6
|
const getSessionFromCookie = async (config) => {
|
|
20
7
|
logger.debug('attempting to get session from cookie');
|
|
21
8
|
try {
|
|
@@ -32,27 +19,32 @@ const getSessionFromCookie = async (config) => {
|
|
|
32
19
|
return undefined;
|
|
33
20
|
}
|
|
34
21
|
};
|
|
35
|
-
// tries to
|
|
36
|
-
// if it doesn't exist, it will attempt to get the session from the cookie
|
|
37
|
-
const
|
|
38
|
-
const
|
|
39
|
-
if (
|
|
40
|
-
|
|
22
|
+
// tries to validate the Authorization header,
|
|
23
|
+
// if it doesn't exist or is invalid, it will attempt to get the session from the cookie
|
|
24
|
+
const getSessionFromAuthorizationOrCookie = async (authorization, config) => {
|
|
25
|
+
const sessionJwt = authorization?.split(' ')[1];
|
|
26
|
+
if (sessionJwt) {
|
|
27
|
+
try {
|
|
28
|
+
const sdk = getGlobalSdk(config);
|
|
29
|
+
return await sdk.validateJwt(sessionJwt);
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
logger.debug('Error validating session from Authorization header', err);
|
|
33
|
+
}
|
|
41
34
|
}
|
|
42
35
|
return getSessionFromCookie(config);
|
|
43
36
|
};
|
|
44
|
-
// returns the session token if it exists in the
|
|
37
|
+
// returns the session token if it exists in the Authorization header or cookie
|
|
45
38
|
const session = async (config) => {
|
|
46
39
|
setLogger(config?.logLevel);
|
|
47
|
-
// first attempt to get the session from the headers
|
|
48
40
|
const reqHeaders = await headers();
|
|
49
|
-
|
|
50
|
-
return extractOrGetSession(sessionHeader, config);
|
|
41
|
+
return getSessionFromAuthorizationOrCookie(reqHeaders.get('Authorization'), config);
|
|
51
42
|
};
|
|
52
|
-
// returns the session token if it exists in the request
|
|
43
|
+
// returns the session token if it exists in the request Authorization header or cookie
|
|
53
44
|
const getSession = async (req, config) => {
|
|
54
45
|
setLogger(config?.logLevel);
|
|
55
|
-
|
|
46
|
+
const { authorization } = req.headers;
|
|
47
|
+
return getSessionFromAuthorizationOrCookie(typeof authorization === 'string' ? authorization : undefined, config);
|
|
56
48
|
};
|
|
57
49
|
|
|
58
50
|
export { getSession, session };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sources":["../../../src/server/session.ts"],"sourcesContent":["import descopeSdk, { AuthenticationInfo } from '@descope/node-sdk';\nimport { NextApiRequest } from 'next';\nimport { cookies, headers } from 'next/headers';\nimport {
|
|
1
|
+
{"version":3,"file":"session.js","sources":["../../../src/server/session.ts"],"sourcesContent":["import descopeSdk, { AuthenticationInfo } from '@descope/node-sdk';\nimport { NextApiRequest } from 'next';\nimport { cookies, headers } from 'next/headers';\nimport { getGlobalSdk, CreateSdkParams } from './sdk';\nimport { LogLevel } from '../types';\nimport { logger, setLogger } from './logger';\n\ntype SessionConfig = CreateSdkParams & {\n\t// The log level to use for the middleware\n\t// Defaults to 'info'\n\tlogLevel?: LogLevel;\n\n\t// The name of the session cookie to look for the JWT\n\t// Defaults to 'DS'\n\t// Note: The middleware will also look for the JWT in the Authorization header\n\tsessionCookieName?: string;\n};\nconst getSessionFromCookie = async (\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tlogger.debug('attempting to get session from cookie');\n\ttry {\n\t\tconst sessionCookie = (await cookies()).get(\n\t\t\tconfig?.sessionCookieName || descopeSdk.SessionTokenCookieName\n\t\t);\n\t\tif (!sessionCookie?.value) {\n\t\t\tlogger.debug('Session cookie not found');\n\t\t\treturn undefined;\n\t\t}\n\t\tconst sdk = getGlobalSdk(config);\n\t\treturn await sdk.validateJwt(sessionCookie.value);\n\t} catch (err) {\n\t\tlogger.debug('Error getting session from cookie', err);\n\t\treturn undefined;\n\t}\n};\n\n// tries to validate the Authorization header,\n// if it doesn't exist or is invalid, it will attempt to get the session from the cookie\nconst getSessionFromAuthorizationOrCookie = async (\n\tauthorization?: string | null,\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tconst sessionJwt = authorization?.split(' ')[1];\n\tif (sessionJwt) {\n\t\ttry {\n\t\t\tconst sdk = getGlobalSdk(config);\n\t\t\treturn await sdk.validateJwt(sessionJwt);\n\t\t} catch (err) {\n\t\t\tlogger.debug('Error validating session from Authorization header', err);\n\t\t}\n\t}\n\n\treturn getSessionFromCookie(config);\n};\n\n// returns the session token if it exists in the Authorization header or cookie\nexport const session = async (\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tsetLogger(config?.logLevel);\n\tconst reqHeaders = await headers();\n\treturn getSessionFromAuthorizationOrCookie(\n\t\treqHeaders.get('Authorization'),\n\t\tconfig\n\t);\n};\n\n// returns the session token if it exists in the request Authorization header or cookie\nexport const getSession = async (\n\treq: NextApiRequest,\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tsetLogger(config?.logLevel);\n\tconst { authorization } = req.headers;\n\treturn getSessionFromAuthorizationOrCookie(\n\t\ttypeof authorization === 'string' ? authorization : undefined,\n\t\tconfig\n\t);\n};\n"],"names":[],"mappings":";;;;;AAiBA,MAAM,oBAAoB,GAAG,OAC5B,MAAsB,KACsB;AAC5C,IAAA,MAAM,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACtD,IAAA,IAAI;AACH,QAAA,MAAM,aAAa,GAAG,CAAC,MAAM,OAAO,EAAE,EAAE,GAAG,CAC1C,MAAM,EAAE,iBAAiB,IAAI,UAAU,CAAC,sBAAsB,CAC9D,CAAC;AACF,QAAA,IAAI,CAAC,aAAa,EAAE,KAAK,EAAE;AAC1B,YAAA,MAAM,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;AACzC,YAAA,OAAO,SAAS,CAAC;SACjB;AACD,QAAA,MAAM,GAAG,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;QACjC,OAAO,MAAM,GAAG,CAAC,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;KAClD;IAAC,OAAO,GAAG,EAAE;AACb,QAAA,MAAM,CAAC,KAAK,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAC;AACvD,QAAA,OAAO,SAAS,CAAC;KACjB;AACF,CAAC,CAAC;AAEF;AACA;AACA,MAAM,mCAAmC,GAAG,OAC3C,aAA6B,EAC7B,MAAsB,KACsB;IAC5C,MAAM,UAAU,GAAG,aAAa,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,IAAI,UAAU,EAAE;AACf,QAAA,IAAI;AACH,YAAA,MAAM,GAAG,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;AACjC,YAAA,OAAO,MAAM,GAAG,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;SACzC;QAAC,OAAO,GAAG,EAAE;AACb,YAAA,MAAM,CAAC,KAAK,CAAC,oDAAoD,EAAE,GAAG,CAAC,CAAC;SACxE;KACD;AAED,IAAA,OAAO,oBAAoB,CAAC,MAAM,CAAC,CAAC;AACrC,CAAC,CAAC;AAEF;MACa,OAAO,GAAG,OACtB,MAAsB,KACsB;AAC5C,IAAA,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC5B,IAAA,MAAM,UAAU,GAAG,MAAM,OAAO,EAAE,CAAC;IACnC,OAAO,mCAAmC,CACzC,UAAU,CAAC,GAAG,CAAC,eAAe,CAAC,EAC/B,MAAM,CACN,CAAC;AACH,EAAE;AAEF;AACa,MAAA,UAAU,GAAG,OACzB,GAAmB,EACnB,MAAsB,KACsB;AAC5C,IAAA,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC5B,IAAA,MAAM,EAAE,aAAa,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC;AACtC,IAAA,OAAO,mCAAmC,CACzC,OAAO,aAAa,KAAK,QAAQ,GAAG,aAAa,GAAG,SAAS,EAC7D,MAAM,CACN,CAAC;AACH;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@descope/nextjs-sdk",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.51",
|
|
4
4
|
"description": "Descope NextJS SDK",
|
|
5
5
|
"author": "Descope Team <info@descope.com>",
|
|
6
6
|
"homepage": "https://github.com/descope/descope-js",
|
|
@@ -65,8 +65,8 @@
|
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@descope/node-sdk": "1.7.19",
|
|
67
67
|
"@descope/react-sdk": "2.24.3",
|
|
68
|
-
"@descope/
|
|
69
|
-
"@descope/
|
|
68
|
+
"@descope/web-component": "3.52.2",
|
|
69
|
+
"@descope/core-js-sdk": "2.53.1"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@babel/core": "7.26.0",
|