@descope/nextjs-sdk 0.0.0-alpha.1
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/LICENSE +21 -0
- package/README.md +493 -0
- package/dist/cjs/client/index.js +52 -0
- package/dist/cjs/client/index.js.map +1 -0
- package/dist/cjs/index.js +20 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/server/authMiddleware.js +97 -0
- package/dist/cjs/server/authMiddleware.js.map +1 -0
- package/dist/cjs/server/constants.js +16 -0
- package/dist/cjs/server/constants.js.map +1 -0
- package/dist/cjs/server/index.js +13 -0
- package/dist/cjs/server/index.js.map +1 -0
- package/dist/cjs/server/logger.js +28 -0
- package/dist/cjs/server/logger.js.map +1 -0
- package/dist/cjs/server/sdk.js +29 -0
- package/dist/cjs/server/sdk.js.map +1 -0
- package/dist/cjs/server/session.js +62 -0
- package/dist/cjs/server/session.js.map +1 -0
- package/dist/cjs/server/utils.js +24 -0
- package/dist/cjs/server/utils.js.map +1 -0
- package/dist/cjs/shared/AuthProvider.js +15 -0
- package/dist/cjs/shared/AuthProvider.js.map +1 -0
- package/dist/cjs/shared/DescopeFlows.js +50 -0
- package/dist/cjs/shared/DescopeFlows.js.map +1 -0
- package/dist/cjs/shared/DescopeWidgets.js +27 -0
- package/dist/cjs/shared/DescopeWidgets.js.map +1 -0
- package/dist/cjs/shared/constants.js +10 -0
- package/dist/cjs/shared/constants.js.map +1 -0
- package/dist/client/dts/src/client/index.d.ts +12 -0
- package/dist/client/dts/src/index.d.ts +1 -0
- package/dist/client/dts/src/server/authMiddleware.d.ts +12 -0
- package/dist/client/dts/src/server/constants.d.ts +9 -0
- package/dist/client/dts/src/server/index.d.ts +3 -0
- package/dist/client/dts/src/server/sdk.d.ts +10 -0
- package/dist/client/dts/src/server/session.d.ts +6 -0
- package/dist/client/dts/src/server/utils.d.ts +1 -0
- package/dist/client/dts/src/shared/AuthProvider.d.ts +3 -0
- package/dist/client/dts/src/shared/DescopeFlows.d.ts +130 -0
- package/dist/client/dts/src/shared/DescopeWidgets.d.ts +72 -0
- package/dist/client/dts/src/shared/constants.d.ts +4 -0
- package/dist/client/dts/src/shared/index.d.ts +3 -0
- package/dist/client/dts/src/types.d.ts +1 -0
- package/dist/client/index.d.ts +12 -0
- package/dist/client/index.js +14 -0
- package/dist/client/index.js.map +1 -0
- package/dist/dts/src/client/index.d.ts +12 -0
- package/dist/dts/src/index.d.ts +1 -0
- package/dist/dts/src/server/authMiddleware.d.ts +12 -0
- package/dist/dts/src/server/constants.d.ts +9 -0
- package/dist/dts/src/server/index.d.ts +3 -0
- package/dist/dts/src/server/sdk.d.ts +10 -0
- package/dist/dts/src/server/session.d.ts +6 -0
- package/dist/dts/src/server/utils.d.ts +1 -0
- package/dist/dts/src/shared/AuthProvider.d.ts +3 -0
- package/dist/dts/src/shared/DescopeFlows.d.ts +130 -0
- package/dist/dts/src/shared/DescopeWidgets.d.ts +72 -0
- package/dist/dts/src/shared/constants.d.ts +4 -0
- package/dist/dts/src/shared/index.d.ts +3 -0
- package/dist/dts/src/types.d.ts +1 -0
- package/dist/esm/client/index.js +3 -0
- package/dist/esm/client/index.js.map +1 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/server/authMiddleware.js +95 -0
- package/dist/esm/server/authMiddleware.js.map +1 -0
- package/dist/esm/server/constants.js +12 -0
- package/dist/esm/server/constants.js.map +1 -0
- package/dist/esm/server/index.js +4 -0
- package/dist/esm/server/index.js.map +1 -0
- package/dist/esm/server/logger.js +25 -0
- package/dist/esm/server/logger.js.map +1 -0
- package/dist/esm/server/sdk.js +26 -0
- package/dist/esm/server/sdk.js.map +1 -0
- package/dist/esm/server/session.js +59 -0
- package/dist/esm/server/session.js.map +1 -0
- package/dist/esm/server/utils.js +22 -0
- package/dist/esm/server/utils.js.map +1 -0
- package/dist/esm/shared/AuthProvider.js +13 -0
- package/dist/esm/shared/AuthProvider.js.map +1 -0
- package/dist/esm/shared/DescopeFlows.js +45 -0
- package/dist/esm/shared/DescopeFlows.js.map +1 -0
- package/dist/esm/shared/DescopeWidgets.js +20 -0
- package/dist/esm/shared/DescopeWidgets.js.map +1 -0
- package/dist/esm/shared/constants.js +8 -0
- package/dist/esm/shared/constants.js.map +1 -0
- package/dist/index.d.ts +212 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/server/authMiddleware.js +98 -0
- package/dist/server/authMiddleware.js.map +1 -0
- package/dist/server/constants.js +12 -0
- package/dist/server/constants.js.map +1 -0
- package/dist/server/dts/src/client/index.d.ts +12 -0
- package/dist/server/dts/src/index.d.ts +1 -0
- package/dist/server/dts/src/server/authMiddleware.d.ts +12 -0
- package/dist/server/dts/src/server/constants.d.ts +9 -0
- package/dist/server/dts/src/server/index.d.ts +3 -0
- package/dist/server/dts/src/server/sdk.d.ts +10 -0
- package/dist/server/dts/src/server/session.d.ts +6 -0
- package/dist/server/dts/src/server/utils.d.ts +1 -0
- package/dist/server/dts/src/shared/AuthProvider.d.ts +3 -0
- package/dist/server/dts/src/shared/DescopeFlows.d.ts +130 -0
- package/dist/server/dts/src/shared/DescopeWidgets.d.ts +72 -0
- package/dist/server/dts/src/shared/constants.d.ts +4 -0
- package/dist/server/dts/src/shared/index.d.ts +3 -0
- package/dist/server/dts/src/types.d.ts +1 -0
- package/dist/server/index.d.ts +32 -0
- package/dist/server/index.js +4 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/sdk.js +27 -0
- package/dist/server/sdk.js.map +1 -0
- package/dist/server/session.js +32 -0
- package/dist/server/session.js.map +1 -0
- package/dist/server/utils.js +22 -0
- package/dist/server/utils.js.map +1 -0
- package/dist/shared/AuthProvider.js +19 -0
- package/dist/shared/AuthProvider.js.map +1 -0
- package/dist/shared/DescopeFlows.js +53 -0
- package/dist/shared/DescopeFlows.js.map +1 -0
- package/dist/shared/DescopeWidgets.js +35 -0
- package/dist/shared/DescopeWidgets.js.map +1 -0
- package/dist/shared/constants.js +8 -0
- package/dist/shared/constants.js.map +1 -0
- package/dist/types/client/index.d.ts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/server/authMiddleware.d.ts +12 -0
- package/dist/types/server/constants.d.ts +9 -0
- package/dist/types/server/index.d.ts +3 -0
- package/dist/types/server/logger.d.ts +25 -0
- package/dist/types/server/sdk.d.ts +9 -0
- package/dist/types/server/session.d.ts +10 -0
- package/dist/types/server/utils.d.ts +1 -0
- package/dist/types/shared/AuthProvider.d.ts +3 -0
- package/dist/types/shared/DescopeFlows.d.ts +141 -0
- package/dist/types/shared/DescopeWidgets.d.ts +54 -0
- package/dist/types/shared/constants.d.ts +4 -0
- package/dist/types/shared/index.d.ts +3 -0
- package/dist/types/types.d.ts +1 -0
- package/package.json +152 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type TempType = {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
export {
|
|
3
|
+
getJwtPermissions,
|
|
4
|
+
getJwtRoles,
|
|
5
|
+
getRefreshToken,
|
|
6
|
+
getSessionToken,
|
|
7
|
+
isRefreshTokenExpired,
|
|
8
|
+
isSessionTokenExpired,
|
|
9
|
+
refresh,
|
|
10
|
+
useDescope,
|
|
11
|
+
useSession,
|
|
12
|
+
useUser
|
|
13
|
+
} from '@descope/react-sdk';
|
|
14
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './shared';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
type MiddlewareOptions = {
|
|
3
|
+
projectId?: string;
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
redirectUrl?: string;
|
|
6
|
+
publicRoutes?: string[];
|
|
7
|
+
privateRoutes?: string[];
|
|
8
|
+
};
|
|
9
|
+
declare const createAuthMiddleware: (
|
|
10
|
+
options?: MiddlewareOptions
|
|
11
|
+
) => (req: NextRequest) => Promise<NextResponse<unknown>>;
|
|
12
|
+
export default createAuthMiddleware;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const DESCOPE_SESSION_HEADER = 'x-descope-session';
|
|
2
|
+
export declare const baseHeaders: {
|
|
3
|
+
'x-descope-sdk-name': string;
|
|
4
|
+
'x-descope-sdk-version': string;
|
|
5
|
+
};
|
|
6
|
+
export declare const DEFAULT_PUBLIC_ROUTES: {
|
|
7
|
+
signIn: string;
|
|
8
|
+
signUp: string;
|
|
9
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import descopeSdk from '@descope/node-sdk';
|
|
2
|
+
type Sdk = ReturnType<typeof descopeSdk>;
|
|
3
|
+
type CreateSdkParams = Omit<Parameters<typeof descopeSdk>[0], 'projectId'> & {
|
|
4
|
+
projectId?: string | undefined;
|
|
5
|
+
};
|
|
6
|
+
export declare const createSdk: (config?: CreateSdkParams) => Sdk;
|
|
7
|
+
export declare const getGlobalSdk: (
|
|
8
|
+
config?: Pick<CreateSdkParams, 'projectId' | 'baseUrl'>
|
|
9
|
+
) => Sdk;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const mergeSearchParams: (...searchParams: string[]) => string;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import type * as _1 from '@descope/react-sdk/node_modules/@types/react';
|
|
3
|
+
import type * as _2 from '@descope/react-sdk/node_modules/@descope/web-component/dist';
|
|
4
|
+
type AdditionalProps = {
|
|
5
|
+
redirectAfterSuccess?: string;
|
|
6
|
+
redirectAfterError?: string;
|
|
7
|
+
};
|
|
8
|
+
export declare const Descope: _1.ComponentType<
|
|
9
|
+
{
|
|
10
|
+
flowId: string;
|
|
11
|
+
onSuccess?: (
|
|
12
|
+
e: CustomEvent<import('@descope/core-js-sdk').JWTResponse>
|
|
13
|
+
) => void;
|
|
14
|
+
onError?: (
|
|
15
|
+
e: CustomEvent<{
|
|
16
|
+
errorCode: string;
|
|
17
|
+
errorDescription: string;
|
|
18
|
+
errorMessage?: string;
|
|
19
|
+
retryAfter?: string;
|
|
20
|
+
}>
|
|
21
|
+
) => void;
|
|
22
|
+
onReady?: (e: CustomEvent<{}>) => void;
|
|
23
|
+
logger?: Partial<any>;
|
|
24
|
+
tenant?: string;
|
|
25
|
+
theme?: _2.ThemeOptions;
|
|
26
|
+
locale?: string;
|
|
27
|
+
autoFocus?: _2.AutoFocusOptions;
|
|
28
|
+
validateOnBlur?: boolean;
|
|
29
|
+
restartOnError?: boolean;
|
|
30
|
+
debug?: boolean;
|
|
31
|
+
telemetryKey?: string;
|
|
32
|
+
redirectUrl?: string;
|
|
33
|
+
errorTransformer?: (error: { text: string; type: string }) => string;
|
|
34
|
+
form?: Record<string, any>;
|
|
35
|
+
client?: Record<string, any>;
|
|
36
|
+
styleId?: string;
|
|
37
|
+
} & _1.RefAttributes<HTMLElement> &
|
|
38
|
+
AdditionalProps
|
|
39
|
+
>;
|
|
40
|
+
export declare const SignInFlow: _1.ComponentType<
|
|
41
|
+
{
|
|
42
|
+
form?: Record<string, any>;
|
|
43
|
+
onSuccess?: (
|
|
44
|
+
e: CustomEvent<import('@descope/core-js-sdk').JWTResponse>
|
|
45
|
+
) => void;
|
|
46
|
+
onError?: (
|
|
47
|
+
e: CustomEvent<{
|
|
48
|
+
errorCode: string;
|
|
49
|
+
errorDescription: string;
|
|
50
|
+
errorMessage?: string;
|
|
51
|
+
retryAfter?: string;
|
|
52
|
+
}>
|
|
53
|
+
) => void;
|
|
54
|
+
onReady?: (e: CustomEvent<{}>) => void;
|
|
55
|
+
logger?: Partial<any>;
|
|
56
|
+
tenant?: string;
|
|
57
|
+
theme?: _2.ThemeOptions;
|
|
58
|
+
locale?: string;
|
|
59
|
+
autoFocus?: _2.AutoFocusOptions;
|
|
60
|
+
validateOnBlur?: boolean;
|
|
61
|
+
restartOnError?: boolean;
|
|
62
|
+
debug?: boolean;
|
|
63
|
+
telemetryKey?: string;
|
|
64
|
+
redirectUrl?: string;
|
|
65
|
+
errorTransformer?: (error: { text: string; type: string }) => string;
|
|
66
|
+
client?: Record<string, any>;
|
|
67
|
+
styleId?: string;
|
|
68
|
+
} & AdditionalProps
|
|
69
|
+
>;
|
|
70
|
+
export declare const SignUpFlow: _1.ComponentType<
|
|
71
|
+
{
|
|
72
|
+
form?: Record<string, any>;
|
|
73
|
+
onSuccess?: (
|
|
74
|
+
e: CustomEvent<import('@descope/core-js-sdk').JWTResponse>
|
|
75
|
+
) => void;
|
|
76
|
+
onError?: (
|
|
77
|
+
e: CustomEvent<{
|
|
78
|
+
errorCode: string;
|
|
79
|
+
errorDescription: string;
|
|
80
|
+
errorMessage?: string;
|
|
81
|
+
retryAfter?: string;
|
|
82
|
+
}>
|
|
83
|
+
) => void;
|
|
84
|
+
onReady?: (e: CustomEvent<{}>) => void;
|
|
85
|
+
logger?: Partial<any>;
|
|
86
|
+
tenant?: string;
|
|
87
|
+
theme?: _2.ThemeOptions;
|
|
88
|
+
locale?: string;
|
|
89
|
+
autoFocus?: _2.AutoFocusOptions;
|
|
90
|
+
validateOnBlur?: boolean;
|
|
91
|
+
restartOnError?: boolean;
|
|
92
|
+
debug?: boolean;
|
|
93
|
+
telemetryKey?: string;
|
|
94
|
+
redirectUrl?: string;
|
|
95
|
+
errorTransformer?: (error: { text: string; type: string }) => string;
|
|
96
|
+
client?: Record<string, any>;
|
|
97
|
+
styleId?: string;
|
|
98
|
+
} & AdditionalProps
|
|
99
|
+
>;
|
|
100
|
+
export declare const SignUpOrInFlow: _1.ComponentType<
|
|
101
|
+
{
|
|
102
|
+
form?: Record<string, any>;
|
|
103
|
+
onSuccess?: (
|
|
104
|
+
e: CustomEvent<import('@descope/core-js-sdk').JWTResponse>
|
|
105
|
+
) => void;
|
|
106
|
+
onError?: (
|
|
107
|
+
e: CustomEvent<{
|
|
108
|
+
errorCode: string;
|
|
109
|
+
errorDescription: string;
|
|
110
|
+
errorMessage?: string;
|
|
111
|
+
retryAfter?: string;
|
|
112
|
+
}>
|
|
113
|
+
) => void;
|
|
114
|
+
onReady?: (e: CustomEvent<{}>) => void;
|
|
115
|
+
logger?: Partial<any>;
|
|
116
|
+
tenant?: string;
|
|
117
|
+
theme?: _2.ThemeOptions;
|
|
118
|
+
locale?: string;
|
|
119
|
+
autoFocus?: _2.AutoFocusOptions;
|
|
120
|
+
validateOnBlur?: boolean;
|
|
121
|
+
restartOnError?: boolean;
|
|
122
|
+
debug?: boolean;
|
|
123
|
+
telemetryKey?: string;
|
|
124
|
+
redirectUrl?: string;
|
|
125
|
+
errorTransformer?: (error: { text: string; type: string }) => string;
|
|
126
|
+
client?: Record<string, any>;
|
|
127
|
+
styleId?: string;
|
|
128
|
+
} & AdditionalProps
|
|
129
|
+
>;
|
|
130
|
+
export {};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import type * as _1 from '@descope/react-sdk/node_modules/@types/react';
|
|
3
|
+
export declare const UserManagement: _1.ComponentType<
|
|
4
|
+
{
|
|
5
|
+
logger?: Partial<any>;
|
|
6
|
+
tenant: string;
|
|
7
|
+
widgetId: string;
|
|
8
|
+
theme?: import('@descope/web-component').ThemeOptions;
|
|
9
|
+
debug?: boolean;
|
|
10
|
+
styleId?: string;
|
|
11
|
+
} & _1.RefAttributes<HTMLElement>
|
|
12
|
+
>;
|
|
13
|
+
export declare const RoleManagement: _1.ComponentType<
|
|
14
|
+
{
|
|
15
|
+
logger?: Partial<any>;
|
|
16
|
+
tenant: string;
|
|
17
|
+
widgetId: string;
|
|
18
|
+
theme?: import('@descope/web-component').ThemeOptions;
|
|
19
|
+
debug?: boolean;
|
|
20
|
+
styleId?: string;
|
|
21
|
+
} & _1.RefAttributes<HTMLElement>
|
|
22
|
+
>;
|
|
23
|
+
export declare const AccessKeyManagement: _1.ComponentType<
|
|
24
|
+
{
|
|
25
|
+
logger?: Partial<any>;
|
|
26
|
+
tenant: string;
|
|
27
|
+
widgetId: string;
|
|
28
|
+
theme?: import('@descope/web-component').ThemeOptions;
|
|
29
|
+
debug?: boolean;
|
|
30
|
+
styleId?: string;
|
|
31
|
+
} & _1.RefAttributes<HTMLElement>
|
|
32
|
+
>;
|
|
33
|
+
export declare const AuditManagement: _1.ComponentType<
|
|
34
|
+
{
|
|
35
|
+
logger?: Partial<any>;
|
|
36
|
+
tenant: string;
|
|
37
|
+
widgetId: string;
|
|
38
|
+
theme?: import('@descope/web-component').ThemeOptions;
|
|
39
|
+
debug?: boolean;
|
|
40
|
+
styleId?: string;
|
|
41
|
+
} & _1.RefAttributes<HTMLElement>
|
|
42
|
+
>;
|
|
43
|
+
export declare const UserProfile: _1.ComponentType<
|
|
44
|
+
Omit<
|
|
45
|
+
{
|
|
46
|
+
logger?: Partial<any>;
|
|
47
|
+
tenant: string;
|
|
48
|
+
widgetId: string;
|
|
49
|
+
theme?: import('@descope/web-component').ThemeOptions;
|
|
50
|
+
debug?: boolean;
|
|
51
|
+
styleId?: string;
|
|
52
|
+
},
|
|
53
|
+
'tenant'
|
|
54
|
+
> & {
|
|
55
|
+
onLogout?: (e: CustomEvent<any>) => void;
|
|
56
|
+
} & _1.RefAttributes<HTMLElement>
|
|
57
|
+
>;
|
|
58
|
+
export declare const ApplicationsPortal: _1.ComponentType<
|
|
59
|
+
Omit<
|
|
60
|
+
{
|
|
61
|
+
logger?: Partial<any>;
|
|
62
|
+
tenant: string;
|
|
63
|
+
widgetId: string;
|
|
64
|
+
theme?: import('@descope/web-component').ThemeOptions;
|
|
65
|
+
debug?: boolean;
|
|
66
|
+
styleId?: string;
|
|
67
|
+
},
|
|
68
|
+
'tenant'
|
|
69
|
+
> & {
|
|
70
|
+
onLogout?: (e: CustomEvent<any>) => void;
|
|
71
|
+
} & _1.RefAttributes<HTMLElement>
|
|
72
|
+
>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type TempType = {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { default as AuthProvider } from './shared/AuthProvider.js';
|
|
2
|
+
export { Descope, SignInFlow, SignUpFlow, SignUpOrInFlow } from './shared/DescopeFlows.js';
|
|
3
|
+
export { AccessKeyManagement, ApplicationsPortal, AuditManagement, RoleManagement, UserManagement, UserProfile } from './shared/DescopeWidgets.js';
|
|
4
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server.js';
|
|
2
|
+
import descopeSdk from '@descope/node-sdk';
|
|
3
|
+
import { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER } from './constants.js';
|
|
4
|
+
import { getGlobalSdk } from './sdk.js';
|
|
5
|
+
import { mergeSearchParams } from './utils.js';
|
|
6
|
+
import { setLogger, logger } from './logger.js';
|
|
7
|
+
|
|
8
|
+
const getSessionJwt = (req) => {
|
|
9
|
+
let jwt = req.headers?.get('Authorization')?.split(' ')[1];
|
|
10
|
+
if (jwt) {
|
|
11
|
+
return jwt;
|
|
12
|
+
}
|
|
13
|
+
jwt = req.cookies?.get(descopeSdk.SessionTokenCookieName)?.value;
|
|
14
|
+
if (jwt) {
|
|
15
|
+
return jwt;
|
|
16
|
+
}
|
|
17
|
+
return undefined;
|
|
18
|
+
};
|
|
19
|
+
const matchWildcardRoute = (route, path) => {
|
|
20
|
+
let regexPattern = route.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
|
|
21
|
+
// Convert wildcard (*) to match path segments only
|
|
22
|
+
regexPattern = regexPattern.replace(/\*/g, '[^/]*');
|
|
23
|
+
const regex = new RegExp(`^${regexPattern}$`);
|
|
24
|
+
return regex.test(path);
|
|
25
|
+
};
|
|
26
|
+
const isPublicRoute = (req, options) => {
|
|
27
|
+
// Ensure publicRoutes and privateRoutes are arrays, defaulting to empty arrays if not defined
|
|
28
|
+
const { publicRoutes = [], privateRoutes = [] } = options;
|
|
29
|
+
const { pathname } = req.nextUrl;
|
|
30
|
+
const isDefaultPublicRoute = Object.values(DEFAULT_PUBLIC_ROUTES).includes(pathname);
|
|
31
|
+
if (publicRoutes.length > 0) {
|
|
32
|
+
if (privateRoutes.length > 0) {
|
|
33
|
+
logger.warn('Both publicRoutes and privateRoutes are defined. Ignoring privateRoutes.');
|
|
34
|
+
}
|
|
35
|
+
return (isDefaultPublicRoute ||
|
|
36
|
+
publicRoutes.some((route) => matchWildcardRoute(route, pathname)));
|
|
37
|
+
}
|
|
38
|
+
if (privateRoutes.length > 0) {
|
|
39
|
+
return (isDefaultPublicRoute ||
|
|
40
|
+
!privateRoutes.some((route) => matchWildcardRoute(route, pathname)));
|
|
41
|
+
}
|
|
42
|
+
// If no routes are provided, all routes are private
|
|
43
|
+
return isDefaultPublicRoute;
|
|
44
|
+
};
|
|
45
|
+
const addSessionToHeadersIfExists = (headers, session) => {
|
|
46
|
+
if (session) {
|
|
47
|
+
const requestHeaders = new Headers(headers);
|
|
48
|
+
requestHeaders.set(DESCOPE_SESSION_HEADER, Buffer.from(JSON.stringify(session)).toString('base64'));
|
|
49
|
+
return requestHeaders;
|
|
50
|
+
}
|
|
51
|
+
return headers;
|
|
52
|
+
};
|
|
53
|
+
// returns a Middleware that checks if the user is authenticated
|
|
54
|
+
// 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
|
+
const createAuthMiddleware = (options = {}) => async (req) => {
|
|
57
|
+
setLogger(options.logLevel);
|
|
58
|
+
logger.debug('Auth middleware starts');
|
|
59
|
+
const jwt = getSessionJwt(req);
|
|
60
|
+
// check if the user is authenticated
|
|
61
|
+
let session;
|
|
62
|
+
try {
|
|
63
|
+
session = await getGlobalSdk({
|
|
64
|
+
projectId: options.projectId,
|
|
65
|
+
baseUrl: options.baseUrl
|
|
66
|
+
}).validateJwt(jwt);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
logger.debug('Auth middleware, Failed to validate JWT', err);
|
|
70
|
+
if (!isPublicRoute(req, options)) {
|
|
71
|
+
const redirectUrl = options.redirectUrl || DEFAULT_PUBLIC_ROUTES.signIn;
|
|
72
|
+
const url = req.nextUrl.clone();
|
|
73
|
+
// Create a URL object for redirectUrl. 'http://example.com' is just a placeholder.
|
|
74
|
+
const parsedRedirectUrl = new URL(redirectUrl, 'http://example.com');
|
|
75
|
+
url.pathname = parsedRedirectUrl.pathname;
|
|
76
|
+
const searchParams = mergeSearchParams(url.search, parsedRedirectUrl.search);
|
|
77
|
+
if (searchParams) {
|
|
78
|
+
url.search = searchParams;
|
|
79
|
+
}
|
|
80
|
+
logger.debug(`Auth middleware, Redirecting to ${redirectUrl}`);
|
|
81
|
+
return NextResponse.redirect(url);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
logger.debug('Auth middleware finishes');
|
|
85
|
+
// add the session to the request, if it exists
|
|
86
|
+
const headers = addSessionToHeadersIfExists(req.headers, session);
|
|
87
|
+
return NextResponse.next({
|
|
88
|
+
request: {
|
|
89
|
+
headers
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export { createAuthMiddleware as default };
|
|
95
|
+
//# sourceMappingURL=authMiddleware.js.map
|
|
@@ -0,0 +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 type { AuthenticationInfo } 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.DESCOPE_PROJECT_ID\n\tprojectId?: string;\n\n\t// The base URL to use for authentication\n\t// Defaults to process.env.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\nconst getSessionJwt = (req: NextRequest): 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(descopeSdk.SessionTokenCookieName)?.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 addSessionToHeadersIfExists = (\n\theaders: Headers,\n\tsession: AuthenticationInfo | undefined\n): Headers => {\n\tif (session) {\n\t\tconst requestHeaders = new Headers(headers);\n\t\trequestHeaders.set(\n\t\t\tDESCOPE_SESSION_HEADER,\n\t\t\tBuffer.from(JSON.stringify(session)).toString('base64')\n\t\t);\n\t\treturn requestHeaders;\n\t}\n\treturn headers;\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\n// if the user is authenticated, it adds the session to the headers\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);\n\n\t\t// check if the user is authenticated\n\t\tlet session: AuthenticationInfo | undefined;\n\t\ttry {\n\t\t\tsession = await 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\t// add the session to the request, if it exists\n\t\tconst headers = addSessionToHeadersIfExists(req.headers, session);\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":";;;;;;;AAsCA,MAAM,aAAa,GAAG,CAAC,GAAgB,KAAwB;AAC9D,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,CAAC,UAAU,CAAC,sBAAsB,CAAC,EAAE,KAAK,CAAC;IACjE,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;IAC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AAA,GAAG,CAAC,QAAQ,GAAG,iBAAiB,CAAC,QAAQ,CAAC;AAE1C,YAAA,MAAM,YAAY,GAAG,iBAAiB,CACrC,GAAG,CAAC,MAAM,EACV,iBAAiB,CAAC,MAAM,CACxB,CAAC;YACF,IAAI,YAAY,EAAE;AACjB,gBAAA,GAAG,CAAC,MAAM,GAAG,YAAY,CAAC;aAC1B;AACD,YAAA,MAAM,CAAC,KAAK,CAAC,mCAAmC,WAAW,CAAA,CAAE,CAAC,CAAC;AAC/D,YAAA,OAAO,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;SAClC;KACD;AAED,IAAA,MAAM,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;;IAEzC,MAAM,OAAO,GAAG,2BAA2B,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAClE,OAAO,YAAY,CAAC,IAAI,CAAC;AACxB,QAAA,OAAO,EAAE;YACR,OAAO;AACP,SAAA;AACD,KAAA,CAAC,CAAC;AACJ;;;;"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const DESCOPE_SESSION_HEADER = 'x-descope-session';
|
|
2
|
+
const baseHeaders = {
|
|
3
|
+
'x-descope-sdk-name': 'nextjs',
|
|
4
|
+
'x-descope-sdk-version': "0.0.0-alpha.1"
|
|
5
|
+
};
|
|
6
|
+
const DEFAULT_PUBLIC_ROUTES = {
|
|
7
|
+
signIn: process.env.SIGN_IN_ROUTE || '/sign-in',
|
|
8
|
+
signUp: process.env.SIGN_UP_ROUTE || '/sign-up'
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export { DEFAULT_PUBLIC_ROUTES, DESCOPE_SESSION_HEADER, baseHeaders };
|
|
12
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sources":["../../../src/server/constants.ts"],"sourcesContent":["// Replaced in build time\ndeclare const BUILD_VERSION: string;\n\nexport const DESCOPE_SESSION_HEADER = 'x-descope-session';\n\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'nextjs',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\nexport const DEFAULT_PUBLIC_ROUTES = {\n\tsignIn: process.env.SIGN_IN_ROUTE || '/sign-in',\n\tsignUp: process.env.SIGN_UP_ROUTE || '/sign-up'\n};\n"],"names":[],"mappings":"AAGO,MAAM,sBAAsB,GAAG,oBAAoB;AAE7C,MAAA,WAAW,GAAG;AAC1B,IAAA,oBAAoB,EAAE,QAAQ;AAC9B,IAAA,uBAAuB,EAAE,eAAa;EACrC;AAEW,MAAA,qBAAqB,GAAG;AACpC,IAAA,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,UAAU;AAC/C,IAAA,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,UAAU;;;;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// order of levels is important
|
|
2
|
+
const levels = ['debug', 'info', 'warn', 'error'];
|
|
3
|
+
const logger = {
|
|
4
|
+
debug: console.debug,
|
|
5
|
+
info: console.info,
|
|
6
|
+
log: console.log,
|
|
7
|
+
warn: console.warn,
|
|
8
|
+
error: console.error
|
|
9
|
+
};
|
|
10
|
+
const noop = () => { };
|
|
11
|
+
// override global logger according to the level
|
|
12
|
+
const setLogger = (level = 'info') => {
|
|
13
|
+
Object.keys(logger).forEach((key) => {
|
|
14
|
+
const keyToCompare = key === 'log' ? 'info' : key; // log is an alias for info
|
|
15
|
+
if (levels.indexOf(keyToCompare) < levels.indexOf(level)) {
|
|
16
|
+
logger[key] = noop;
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
logger[key] = console[key];
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export { logger, setLogger };
|
|
25
|
+
//# sourceMappingURL=logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.js","sources":["../../../src/server/logger.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { LogLevel } from '../types';\n\n// order of levels is important\nconst levels = ['debug', 'info', 'warn', 'error'];\n\nconst logger = {\n\tdebug: console.debug,\n\tinfo: console.info,\n\tlog: console.log,\n\twarn: console.warn,\n\terror: console.error\n};\n\nconst noop = () => {};\n\n// override global logger according to the level\nexport const setLogger = (level: LogLevel = 'info') => {\n\tObject.keys(logger).forEach((key) => {\n\t\tconst keyToCompare = key === 'log' ? 'info' : key; // log is an alias for info\n\t\tif (levels.indexOf(keyToCompare) < levels.indexOf(level)) {\n\t\t\tlogger[key] = noop;\n\t\t} else {\n\t\t\tlogger[key] = console[key];\n\t\t}\n\t});\n};\n\nexport { logger };\n"],"names":[],"mappings":"AAGA;AACA,MAAM,MAAM,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAElD,MAAM,MAAM,GAAG;IACd,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,IAAI,EAAE,OAAO,CAAC,IAAI;IAClB,GAAG,EAAE,OAAO,CAAC,GAAG;IAChB,IAAI,EAAE,OAAO,CAAC,IAAI;IAClB,KAAK,EAAE,OAAO,CAAC,KAAK;EACnB;AAEF,MAAM,IAAI,GAAG,MAAK,GAAG,CAAC;AAEtB;MACa,SAAS,GAAG,CAAC,KAAkB,GAAA,MAAM,KAAI;IACrD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,KAAI;AACnC,QAAA,MAAM,YAAY,GAAG,GAAG,KAAK,KAAK,GAAG,MAAM,GAAG,GAAG,CAAC;AAClD,QAAA,IAAI,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACzD,YAAA,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;SACnB;aAAM;YACN,MAAM,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;SAC3B;AACF,KAAC,CAAC,CAAC;AACJ;;;;"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import descopeSdk from '@descope/node-sdk';
|
|
2
|
+
import { baseHeaders } from './constants.js';
|
|
3
|
+
|
|
4
|
+
let globalSdk;
|
|
5
|
+
const createSdk = (config) => descopeSdk({
|
|
6
|
+
...config,
|
|
7
|
+
projectId: config?.projectId || process.env.DESCOPE_PROJECT_ID,
|
|
8
|
+
managementKey: config?.managementKey || process.env.DESCOPE_MANAGEMENT_KEY,
|
|
9
|
+
baseUrl: config?.baseUrl || process.env.DESCOPE_BASE_URL,
|
|
10
|
+
baseHeaders: {
|
|
11
|
+
...config?.baseHeaders,
|
|
12
|
+
...baseHeaders
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
const getGlobalSdk = (config) => {
|
|
16
|
+
if (!globalSdk) {
|
|
17
|
+
if (!config?.projectId && !process.env.DESCOPE_PROJECT_ID) {
|
|
18
|
+
throw new Error('Descope project ID is required to create the SDK');
|
|
19
|
+
}
|
|
20
|
+
globalSdk = createSdk(config);
|
|
21
|
+
}
|
|
22
|
+
return globalSdk;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export { createSdk, getGlobalSdk };
|
|
26
|
+
//# sourceMappingURL=sdk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sdk.js","sources":["../../../src/server/sdk.ts"],"sourcesContent":["import descopeSdk from '@descope/node-sdk';\nimport { baseHeaders } from './constants';\n\ntype Sdk = ReturnType<typeof descopeSdk>;\ntype CreateServerSdkParams = Omit<\n\tParameters<typeof descopeSdk>[0],\n\t'projectId'\n> & {\n\tprojectId?: string | undefined;\n};\n\ntype CreateSdkParams = Pick<CreateServerSdkParams, 'projectId' | 'baseUrl'>;\n\nlet globalSdk: Sdk;\n\nexport const createSdk = (config?: CreateServerSdkParams): Sdk =>\n\tdescopeSdk({\n\t\t...config,\n\t\tprojectId: config?.projectId || process.env.DESCOPE_PROJECT_ID,\n\t\tmanagementKey: config?.managementKey || process.env.DESCOPE_MANAGEMENT_KEY,\n\t\tbaseUrl: config?.baseUrl || process.env.DESCOPE_BASE_URL,\n\t\tbaseHeaders: {\n\t\t\t...config?.baseHeaders,\n\t\t\t...baseHeaders\n\t\t}\n\t});\n\nexport const getGlobalSdk = (config?: CreateSdkParams): Sdk => {\n\tif (!globalSdk) {\n\t\tif (!config?.projectId && !process.env.DESCOPE_PROJECT_ID) {\n\t\t\tthrow new Error('Descope project ID is required to create the SDK');\n\t\t}\n\t\tglobalSdk = createSdk(config);\n\t}\n\n\treturn globalSdk;\n};\n\nexport type { CreateSdkParams };\n"],"names":[],"mappings":";;;AAaA,IAAI,SAAc,CAAC;AAEN,MAAA,SAAS,GAAG,CAAC,MAA8B,KACvD,UAAU,CAAC;AACV,IAAA,GAAG,MAAM;IACT,SAAS,EAAE,MAAM,EAAE,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,kBAAkB;IAC9D,aAAa,EAAE,MAAM,EAAE,aAAa,IAAI,OAAO,CAAC,GAAG,CAAC,sBAAsB;IAC1E,OAAO,EAAE,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB;AACxD,IAAA,WAAW,EAAE;QACZ,GAAG,MAAM,EAAE,WAAW;AACtB,QAAA,GAAG,WAAW;AACd,KAAA;AACD,CAAA,EAAE;AAES,MAAA,YAAY,GAAG,CAAC,MAAwB,KAAS;IAC7D,IAAI,CAAC,SAAS,EAAE;AACf,QAAA,IAAI,CAAC,MAAM,EAAE,SAAS,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE;AAC1D,YAAA,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;SACpE;AACD,QAAA,SAAS,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;KAC9B;AAED,IAAA,OAAO,SAAS,CAAC;AAClB;;;;"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import descopeSdk from '@descope/node-sdk';
|
|
2
|
+
import { headers, cookies } from 'next/headers.js';
|
|
3
|
+
import { DESCOPE_SESSION_HEADER } from './constants.js';
|
|
4
|
+
import { getGlobalSdk } from './sdk.js';
|
|
5
|
+
import { setLogger, logger } from './logger.js';
|
|
6
|
+
|
|
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
|
+
const getSessionFromCookie = async (config) => {
|
|
20
|
+
logger.debug('attempting to get session from cookie');
|
|
21
|
+
try {
|
|
22
|
+
const sessionCookie = (await cookies()).get(descopeSdk.SessionTokenCookieName);
|
|
23
|
+
if (!sessionCookie?.value) {
|
|
24
|
+
logger.debug('Session cookie not found');
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
const sdk = getGlobalSdk(config);
|
|
28
|
+
return await sdk.validateJwt(sessionCookie.value);
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
logger.debug('Error getting session from cookie', err);
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
// tries to extract the session header,
|
|
36
|
+
// if it doesn't exist, it will attempt to get the session from the cookie
|
|
37
|
+
const extractOrGetSession = async (sessionHeader, config) => {
|
|
38
|
+
const session = extractSession(sessionHeader);
|
|
39
|
+
if (session) {
|
|
40
|
+
return session;
|
|
41
|
+
}
|
|
42
|
+
return getSessionFromCookie(config);
|
|
43
|
+
};
|
|
44
|
+
// returns the session token if it exists in the headers
|
|
45
|
+
const session = async (config) => {
|
|
46
|
+
setLogger(config?.logLevel);
|
|
47
|
+
// first attempt to get the session from the headers
|
|
48
|
+
const reqHeaders = await headers();
|
|
49
|
+
const sessionHeader = reqHeaders.get(DESCOPE_SESSION_HEADER);
|
|
50
|
+
return extractOrGetSession(sessionHeader, config);
|
|
51
|
+
};
|
|
52
|
+
// returns the session token if it exists in the request headers
|
|
53
|
+
const getSession = async (req, config) => {
|
|
54
|
+
setLogger(config?.logLevel);
|
|
55
|
+
return extractOrGetSession(req.headers[DESCOPE_SESSION_HEADER.toLowerCase()], config);
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export { getSession, session };
|
|
59
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +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 { DESCOPE_SESSION_HEADER } from './constants';\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\nconst extractSession = (\n\tdescopeSession?: string\n): AuthenticationInfo | undefined => {\n\tif (!descopeSession) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\tconst authInfo = JSON.parse(\n\t\t\tBuffer.from(descopeSession, 'base64').toString()\n\t\t) as AuthenticationInfo;\n\t\treturn authInfo;\n\t} catch (err) {\n\t\treturn undefined;\n\t}\n};\n\nconst getSessionFromCookie = async (\n\tconfig?: CreateSdkParams\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\tdescopeSdk.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 extract the session header,\n// if it doesn't exist, it will attempt to get the session from the cookie\nconst extractOrGetSession = async (\n\tsessionHeader?: string,\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tconst session = extractSession(sessionHeader);\n\tif (session) {\n\t\treturn session;\n\t}\n\n\treturn getSessionFromCookie(config);\n};\n\n// returns the session token if it exists in the headers\nexport const session = async (\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tsetLogger(config?.logLevel);\n\t// first attempt to get the session from the headers\n\tconst reqHeaders = await headers();\n\tconst sessionHeader = reqHeaders.get(DESCOPE_SESSION_HEADER);\n\treturn extractOrGetSession(sessionHeader, config);\n};\n\n// returns the session token if it exists in the request headers\nexport const getSession = async (\n\treq: NextApiRequest,\n\tconfig?: SessionConfig\n): Promise<AuthenticationInfo | undefined> => {\n\tsetLogger(config?.logLevel);\n\treturn extractOrGetSession(\n\t\treq.headers[DESCOPE_SESSION_HEADER.toLowerCase()] as string,\n\t\tconfig\n\t);\n};\n"],"names":[],"mappings":";;;;;;AAcA,MAAM,cAAc,GAAG,CACtB,cAAuB,KACY;IACnC,IAAI,CAAC,cAAc,EAAE;AACpB,QAAA,OAAO,SAAS,CAAC;KACjB;AACD,IAAA,IAAI;AACH,QAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAC1B,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAC1B,CAAC;AACxB,QAAA,OAAO,QAAQ,CAAC;KAChB;IAAC,OAAO,GAAG,EAAE;AACb,QAAA,OAAO,SAAS,CAAC;KACjB;AACF,CA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