@descope/node-sdk 1.0.4-alpha.5 → 1.0.4-alpha.7

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/index.d.ts CHANGED
@@ -1,18 +1,43 @@
1
1
  import * as _descope_core_js_sdk from '@descope/core-js-sdk';
2
- import _descope_core_js_sdk__default from '@descope/core-js-sdk';
2
+ import _descope_core_js_sdk__default, { RequestConfig, SdkResponse, ExchangeAccessKeyResponse } from '@descope/core-js-sdk';
3
3
  export { DeliveryMethod, OAuthProvider } from '@descope/core-js-sdk';
4
4
  import { JWTHeaderParameters, KeyLike } from 'jose';
5
5
 
6
+ /** Parsed JWT token */
6
7
  interface Token {
7
8
  sub?: string;
8
9
  exp?: number;
9
10
  iss?: string;
11
+ [claim: string]: unknown;
10
12
  }
13
+ /** All information regarding token including the raw JWT, parsed JWT and cookies */
11
14
  interface AuthenticationInfo {
12
- token?: Token;
15
+ jwt: string;
16
+ token: Token;
13
17
  cookies?: string[];
14
18
  }
15
19
 
20
+ /** Refresh JWT cookie name */
21
+ declare const refreshTokenCookieName = "DSR";
22
+ /** Session JWT cookie name */
23
+ declare const sessionTokenCookieName = "DS";
24
+
25
+ /** Descope SDK client with delivery methods enum.
26
+ *
27
+ * Please see full documentation at {@link https://docs.descope.com/guides Descope Docs}
28
+ * @example Usage
29
+ *
30
+ * ```js
31
+ * import descopeSdk from '@descope/node-sdk';
32
+ *
33
+ * const myProjectId = 'xxx';
34
+ * const sdk = descopeSdk({ projectId: myProjectId });
35
+ *
36
+ * const userIdentifier = 'identifier';
37
+ * sdk.otp.signIn.email(userIdentifier);
38
+ * const jwtResponse = sdk.otp.verify.email(userIdentifier, codeFromEmail);
39
+ * ```
40
+ */
16
41
  declare const sdkWithAttributes: ((args_0: {
17
42
  projectId: string;
18
43
  logger?: {
@@ -30,205 +55,284 @@ declare const sdkWithAttributes: ((args_0: {
30
55
  };
31
56
  };
32
57
  baseUrl?: string;
58
+ hooks?: {
59
+ beforeRequest?: (config: RequestConfig) => RequestConfig;
60
+ afterRequest?: (req: RequestConfig, res: globalThis.Response) => void;
61
+ };
62
+ cookiePolicy?: RequestCredentials;
33
63
  }) => {
64
+ /** Get the key that can validate the given JWT KID in the header. Can retrieve the public key from local cache or from Descope. */
34
65
  getKey(header: JWTHeaderParameters): Promise<KeyLike | Uint8Array>;
35
- validateToken(token: string): Promise<AuthenticationInfo>;
36
- validateSession(sessionToken: string, refreshToken: string): Promise<AuthenticationInfo | undefined>;
66
+ /**
67
+ * Validate the given JWT with the right key and make sure the issuer is correct
68
+ * @param jwt the JWT string to parse and validate
69
+ * @returns AuthenticationInfo with the parsed token and JWT. Will throw an error if validation fails.
70
+ */
71
+ validateJwt(jwt: string): Promise<AuthenticationInfo>;
72
+ /**
73
+ * Validate session based on at least one of session and refresh JWTs. You must provide at least one of them.
74
+ *
75
+ * @param sessionToken session JWT
76
+ * @param refreshToken refresh JWT
77
+ * @returns AuthenticationInfo promise or throws Error if there is an issue with JWTs
78
+ */
79
+ validateSession(sessionToken?: string, refreshToken?: string): Promise<AuthenticationInfo>;
80
+ /**
81
+ * Exchange API key (access key) for a session key
82
+ * @param accessKey access key to exchange for a session JWT
83
+ * @returns AuthneticationInfo with session JWT data
84
+ */
85
+ exchangeAccessKey(accessKey: string): Promise<AuthenticationInfo>;
86
+ /**
87
+ * Make sure that all given permissions exist on the parsed JWT top level claims
88
+ * @param authInfo JWT parsed info
89
+ * @param permissions list of permissions to make sure they exist on te JWT claims
90
+ * @returns true if all permissions exist, false otherwise
91
+ */
92
+ validatePermissions(authInfo: AuthenticationInfo, permissions: string[]): boolean;
93
+ /**
94
+ * Make sure that all given permissions exist on the parsed JWT tenant claims
95
+ * @param authInfo JWT parsed info
96
+ * @param permissions list of permissions to make sure they exist on te JWT claims
97
+ * @returns true if all permissions exist, false otherwise
98
+ */
99
+ validateTenantPermissions(authInfo: AuthenticationInfo, tenant: string, permissions: string[]): boolean;
100
+ /**
101
+ * Make sure that all given roles exist on the parsed JWT top level claims
102
+ * @param authInfo JWT parsed info
103
+ * @param roles list of roles to make sure they exist on te JWT claims
104
+ * @returns true if all roles exist, false otherwise
105
+ */
106
+ validateRoles(authInfo: AuthenticationInfo, roles: string[]): boolean;
107
+ /**
108
+ * Make sure that all given roles exist on the parsed JWT tenant claims
109
+ * @param authInfo JWT parsed info
110
+ * @param roles list of roles to make sure they exist on te JWT claims
111
+ * @returns true if all roles exist, false otherwise
112
+ */
113
+ validateTenantRoles(authInfo: AuthenticationInfo, tenant: string, roles: string[]): boolean;
114
+ accessKey: {
115
+ exchange: (accessKey: string) => Promise<SdkResponse<ExchangeAccessKeyResponse>>;
116
+ };
37
117
  otp: {
38
118
  verify: {
39
- email: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
40
- sms: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
41
- whatsapp: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
119
+ email: (identifier: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
120
+ sms: (identifier: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
121
+ whatsapp: (identifier: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
42
122
  };
43
123
  signIn: {
44
- email: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
45
- sms: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
46
- whatsapp: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
124
+ email: (identifier: string) => Promise<SdkResponse<never>>;
125
+ sms: (identifier: string) => Promise<SdkResponse<never>>;
126
+ whatsapp: (identifier: string) => Promise<SdkResponse<never>>;
47
127
  };
48
128
  signUp: {
49
129
  email: (identifier: string, user?: {
50
130
  email?: string;
51
131
  name?: string;
52
132
  phone?: string;
53
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
133
+ }) => Promise<SdkResponse<never>>;
54
134
  sms: (identifier: string, user?: {
55
135
  email?: string;
56
136
  name?: string;
57
137
  phone?: string;
58
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
138
+ }) => Promise<SdkResponse<never>>;
59
139
  whatsapp: (identifier: string, user?: {
60
140
  email?: string;
61
141
  name?: string;
62
142
  phone?: string;
63
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
143
+ }) => Promise<SdkResponse<never>>;
64
144
  };
65
145
  signUpOrIn: {
66
- email: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
67
- sms: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
68
- whatsapp: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
146
+ email: (identifier: string) => Promise<SdkResponse<never>>;
147
+ sms: (identifier: string) => Promise<SdkResponse<never>>;
148
+ whatsapp: (identifier: string) => Promise<SdkResponse<never>>;
69
149
  };
70
150
  update: {
71
- email: (identifier: string, email: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
151
+ email: (identifier: string, email: string, token?: string) => Promise<SdkResponse<never>>;
72
152
  phone: {
73
- email: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
74
- sms: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
75
- whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
153
+ email: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
154
+ sms: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
155
+ whatsapp: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
76
156
  };
77
157
  };
78
158
  };
79
159
  magicLink: {
80
- verify: (token: string) => Promise<_descope_core_js_sdk.SdkResponse>;
160
+ verify: (token: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
81
161
  signIn: {
82
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
83
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
84
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
162
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
163
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
164
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
85
165
  };
86
166
  signUp: {
87
167
  email: (identifier: string, uri: string, user?: {
88
168
  email?: string;
89
169
  name?: string;
90
170
  phone?: string;
91
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
171
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
92
172
  sms: (identifier: string, uri: string, user?: {
93
173
  email?: string;
94
174
  name?: string;
95
175
  phone?: string;
96
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
176
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
97
177
  whatsapp: (identifier: string, uri: string, user?: {
98
178
  email?: string;
99
179
  name?: string;
100
180
  phone?: string;
101
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
181
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
102
182
  };
103
183
  signUpOrIn: {
104
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
105
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
106
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
184
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
185
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
186
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
107
187
  };
108
188
  update: {
109
- email: (identifier: string, email: string, uri: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
189
+ email: (identifier: string, email: string, uri: string, token?: string) => Promise<SdkResponse<never>>;
110
190
  phone: {
111
- email: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
112
- sms: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
113
- whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
191
+ email: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
192
+ sms: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
193
+ whatsapp: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
114
194
  };
115
195
  };
116
196
  crossDevice: {
117
- verify: (token: string) => Promise<_descope_core_js_sdk.SdkResponse>;
197
+ verify: (token: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
118
198
  signIn: {
119
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
120
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
121
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
199
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
200
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
201
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
122
202
  };
123
203
  signUpOrIn: {
124
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
125
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
126
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
204
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
205
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
206
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
127
207
  };
128
208
  signUp: {
129
209
  email: (identifier: string, uri: string, user?: {
130
210
  email?: string;
131
211
  name?: string;
132
212
  phone?: string;
133
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
213
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
134
214
  sms: (identifier: string, uri: string, user?: {
135
215
  email?: string;
136
216
  name?: string;
137
217
  phone?: string;
138
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
218
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
139
219
  whatsapp: (identifier: string, uri: string, user?: {
140
220
  email?: string;
141
221
  name?: string;
142
222
  phone?: string;
143
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
223
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
144
224
  };
145
225
  waitForSession: (pendingRef: string, config?: {
146
226
  pollingIntervalMs: number;
147
227
  timeoutMs: number;
148
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
228
+ }) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>; /**
229
+ * Make sure that all given roles exist on the parsed JWT tenant claims
230
+ * @param authInfo JWT parsed info
231
+ * @param roles list of roles to make sure they exist on te JWT claims
232
+ * @returns true if all roles exist, false otherwise
233
+ */
149
234
  update: {
150
- email: (identifier: string, email: string, uri: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
235
+ email: (identifier: string, email: string, uri: string, token?: string) => Promise<SdkResponse<never>>;
151
236
  phone: {
152
- email: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
153
- sms: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
154
- whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
237
+ email: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
238
+ sms: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
239
+ whatsapp: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
155
240
  };
156
241
  };
157
242
  };
158
243
  };
159
244
  oauth: {
160
- exchange: (code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
161
245
  start: {
162
246
  facebook: <B extends {
163
247
  redirect: boolean;
164
248
  }>(redirectURL?: string, config?: B) => Promise<B extends {
165
249
  redirect: true;
166
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
250
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
167
251
  github: <B_1 extends {
168
252
  redirect: boolean;
169
253
  }>(redirectURL?: string, config?: B_1) => Promise<B_1 extends {
170
254
  redirect: true;
171
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
255
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
172
256
  google: <B_2 extends {
173
257
  redirect: boolean;
174
258
  }>(redirectURL?: string, config?: B_2) => Promise<B_2 extends {
175
259
  redirect: true;
176
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
260
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
177
261
  microsoft: <B_3 extends {
178
262
  redirect: boolean;
179
263
  }>(redirectURL?: string, config?: B_3) => Promise<B_3 extends {
180
264
  redirect: true;
181
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
265
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
182
266
  gitlab: <B_4 extends {
183
267
  redirect: boolean;
184
268
  }>(redirectURL?: string, config?: B_4) => Promise<B_4 extends {
185
269
  redirect: true;
186
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
270
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
187
271
  apple: <B_5 extends {
188
272
  redirect: boolean;
189
273
  }>(redirectURL?: string, config?: B_5) => Promise<B_5 extends {
190
274
  redirect: true;
191
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
275
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
192
276
  };
277
+ exchange: (code: string, loginOptions?: {
278
+ stepup: boolean;
279
+ customClaims: Map<string, any>;
280
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
193
281
  };
194
282
  saml: {
195
- exchange: (code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
196
283
  start: <B_1 extends {
197
284
  redirect: boolean;
198
285
  }>(tenantNameOrEmail: string, config?: B_1) => Promise<B_1 extends {
199
286
  redirect: true;
200
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
287
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
288
+ exchange: (code: string, loginOptions?: {
289
+ stepup: boolean;
290
+ customClaims: Map<string, any>;
291
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
201
292
  };
202
293
  totp: {
203
294
  signUp: (identifier: string, user?: {
204
295
  email?: string;
205
296
  name?: string;
206
297
  phone?: string;
207
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
208
- verify: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
209
- update: (identifier: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
298
+ }) => Promise<SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
299
+ verify: (identifier: string, code: string, loginOptions?: {
300
+ stepup: boolean;
301
+ customClaims: Map<string, any>;
302
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
303
+ update: (identifier: string, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
210
304
  };
211
305
  webauthn: {
212
306
  signUp: {
213
- start: (identifier: string, origin: string, name: string) => Promise<_descope_core_js_sdk.SdkResponse>;
214
- finish: (transactionId: string, response: string) => Promise<_descope_core_js_sdk.SdkResponse>;
307
+ start: (identifier: string, origin: string, name: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
308
+ finish: (transactionId: string, response: string, loginOptions?: {
309
+ stepup: boolean;
310
+ customClaims: Map<string, any>;
311
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
215
312
  };
216
313
  signIn: {
217
- start: (identifier: string, origin: string) => Promise<_descope_core_js_sdk.SdkResponse>;
218
- finish: (transactionId: string, response: string) => Promise<_descope_core_js_sdk.SdkResponse>;
314
+ start: (identifier: string, origin: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
315
+ finish: (transactionId: string, response: string, loginOptions?: {
316
+ stepup: boolean;
317
+ customClaims: Map<string, any>;
318
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
219
319
  };
220
- add: {
221
- start: (identifier: string, origin: string, token: string) => Promise<_descope_core_js_sdk.SdkResponse>;
222
- finish: (transactionId: string, response: string) => Promise<_descope_core_js_sdk.SdkResponse>;
320
+ update: {
321
+ start: (identifier: string, origin: string, token: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
322
+ finish: (transactionId: string, response: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
223
323
  };
224
324
  };
225
325
  flow: {
226
- start: (flowId: string) => Promise<_descope_core_js_sdk.SdkResponse>;
227
- next: (executionId: string, stepId: string, actionId: string, input?: Record<string, FormDataEntryValue>) => Promise<_descope_core_js_sdk.SdkResponse>;
326
+ start: (flowId: string) => Promise<SdkResponse<_descope_core_js_sdk.FlowResponse>>;
327
+ next: (executionId: string, stepId: string, interactionId: string, input?: Record<string, FormDataEntryValue>) => Promise<SdkResponse<_descope_core_js_sdk.FlowResponse>>;
228
328
  };
229
- refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
230
- logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
329
+ refresh: (token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
330
+ logout: (token?: string) => Promise<SdkResponse<never>>;
331
+ deleteCookies: (token?: string) => Promise<SdkResponse<never>>;
332
+ me: (token?: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
231
333
  isJwtExpired: (token: string) => boolean;
334
+ getJwtPermissions: (token: string, tenant?: string) => string[];
335
+ getJwtRoles: (token: string, tenant?: string) => string[];
232
336
  httpClient: {
233
337
  get: (path: string, config?: {
234
338
  headers?: HeadersInit;
@@ -261,6 +365,8 @@ declare const sdkWithAttributes: ((args_0: {
261
365
  };
262
366
  }) & {
263
367
  DeliveryMethods: typeof _descope_core_js_sdk__default.DeliveryMethods;
368
+ RefreshTokenCookieName: typeof refreshTokenCookieName;
369
+ SessionTokenCookieName: typeof sessionTokenCookieName;
264
370
  };
265
371
 
266
372
  export { sdkWithAttributes as default };
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__awaiter as e}from"tslib";import t from"@descope/core-js-sdk";import{jwtVerify as i,importJWK as o}from"jose";import r,{Headers as n,Request as s,Response as a}from"node-fetch";const d=(e,t)=>`${e}=${t};`,c=t=>(...i)=>e(void 0,void 0,void 0,(function*(){var e;const o=yield t(...i);if(!o.data)return o;let{sessionJwt:r,refreshJwt:n}=o.data,s=d("DS",r);return n?s+=d("DSR",n):(s+=(null===(e=o.response)||void 0===e?void 0:e.headers.get("set-cookie"))||"",n=((e,t)=>{const i=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return i?i[1]:null})(s,"DSR")),Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{refreshJwt:n,cookies:s})})})),l=(e,t,i)=>{if(!e)return;const o="string"==typeof t?t.split("."):t,r=o.shift()||"";if(0===o.length||"*"===r){const t=t=>{if(!t||"function"!=typeof e[t])throw Error(`cannot wrap value at key "${t.toString()}"`);e[t]=i(e[t])};"*"===r?Object.keys(e).forEach(t):t(r)}else l(e[r],o,i)};globalThis.fetch||(globalThis.fetch=r,globalThis.Headers=n,globalThis.Request=s,globalThis.Response=a);const h=(...r)=>{const n=t(...r);var s,a;s=n,a=c,["otp.verify.*","magicLink.verify","magicLink.crossDevice.signUp.*","magicLink.crossDevice.signIn.*","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"].forEach((e=>l(s,e,a)));const{projectId:d,logger:h}=r[0],f={};return Object.assign(Object.assign({},n),{getKey(t){return e(this,void 0,void 0,(function*(){if(!(null==t?void 0:t.kid))throw Error("header.kid must not be empty");if(f[t.kid])return f[t.kid];if(Object.assign(f,yield e(void 0,void 0,void 0,(function*(){const t=(yield n.httpClient.get(`keys/${d}`).then((e=>e.json())))||[];return(yield Promise.all(t.map((t=>e(void 0,void 0,void 0,(function*(){return[t.kid,yield o(t)]})))))).reduce(((e,[t,i])=>t?Object.assign(Object.assign({},e),{[t.toString()]:i}):e),{})}))),!f[t.kid])throw Error("failed to fetch matching key");return f[t.kid]}))},validateToken(t){return e(this,void 0,void 0,(function*(){return{token:(yield i(t,this.getKey,{algorithms:["ES384"]})).payload}}))},validateSession(t,i){return e(this,void 0,void 0,(function*(){if(!t)throw Error("session token must not be empty");try{return yield this.validateToken(t)}catch(e){try{return yield this.validateToken(i),(yield this.refresh(i)).data}catch(e){throw null==h||h.error("failed to validate refresh token",e),Error("could not validate tokens")}}}))}})};h.DeliveryMethods=t.DeliveryMethods;export{h as default};
1
+ import e from"@descope/core-js-sdk";import{jwtVerify as o,importJWK as t}from"jose";import s,{Headers as r,Request as a,Response as n}from"node-fetch";import{__rest as i}from"tslib";const c=(e,o,t)=>`${e}=${o}; Domain=${(null==t?void 0:t.cookieDomain)||""}; Max-Age=${(null==t?void 0:t.cookieMaxAge)||""}; Path=${(null==t?void 0:t.cookiePath)||"/"}; HttpOnly; SameSite=Strict`,l=e=>async(...o)=>{var t,s,r;const a=await e(...o);if(!a.data)return a;let n=a.data,{sessionJwt:l,refreshJwt:d}=n,h=i(n,["sessionJwt","refreshJwt"]);const u=[c("DS",l,h)];return d?u.push(c("DSR",d,h)):(null===(t=a.response)||void 0===t?void 0:t.headers.get("set-cookie"))&&(d=((e,o)=>{const t=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${o}=([^;]*)`));return t?t[1]:null})(null===(s=a.response)||void 0===s?void 0:s.headers.get("set-cookie"),"DSR"),u.push(null===(r=a.response)||void 0===r?void 0:r.headers.get("set-cookie"))),Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{refreshJwt:d,cookies:u})})},d=(e,o,t)=>{if(!e)return;const s="string"==typeof o?o.split("."):o,r=s.shift()||"";if(0===s.length||"*"===r){const o=o=>{if(!o||"function"!=typeof e[o])throw Error(`cannot wrap value at key "${o.toString()}"`);e[o]=t(e[o])};"*"===r?Object.keys(e).forEach(o):o(r)}else d(e[r],s,t)};function h(e,o,t){var s,r;const a=t?null===(r=null===(s=e.token.tenants)||void 0===s?void 0:s[t])||void 0===r?void 0:r[o]:e.token[o];return Array.isArray(a)?a:[]}globalThis.fetch||(globalThis.fetch=s,globalThis.Headers=r,globalThis.Request=a,globalThis.Response=n);const u=(...s)=>{const r=[...s];r[0].hooks=r[0].hooks||{};const a=r[0].hooks.beforeRequest;r[0].hooks.beforeRequest=e=>{var o;const t=e;return t.headers=Object.assign(Object.assign({},t.headers),{"x-descope-sdk-name":"nodejs","x-descope-sdk-node-version":(null===(o=null===process||void 0===process?void 0:process.versions)||void 0===o?void 0:o.node)||"","x-descope-sdk-version":"1.0.4-alpha.7"}),(null==a?void 0:a(t))||t};const n=e(...r);var i,c;i=n,c=l,["otp.verify.*","magicLink.verify","magicLink.crossDevice.signUp.*","magicLink.crossDevice.signIn.*","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"].forEach((e=>d(i,e,c)));const{projectId:u,logger:v}=s[0],f={},k=Object.assign(Object.assign({},n),{async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(f[e.kid])return f[e.kid];if(Object.assign(f,await(async()=>{const e=await n.httpClient.get(`v1/keys/${u}`).then((e=>e.json()));return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await t(e)])))).reduce(((e,[o,t])=>o?Object.assign(Object.assign({},e),{[o.toString()]:t}):e),{}):{}})()),!f[e.kid])throw Error("failed to fetch matching key");return f[e.kid]},validateJwt:async e=>({jwt:e,token:(await o(e,k.getKey,{issuer:u,clockTolerance:5})).payload}),async validateSession(e,o){var t,s;if(!e&&!o)throw Error("both refresh token and session token are empty");if(e)try{return await k.validateJwt(e)}catch(e){if(!o)throw null==v||v.error("failed to validate session token and no refresh token provided",e),Error("could not validate tokens")}if(o)try{await k.validateJwt(o);const e=await k.refresh(o);if(e.ok){return await k.validateJwt(null===(t=e.data)||void 0===t?void 0:t.sessionJwt)}throw Error(null===(s=e.error)||void 0===s?void 0:s.message)}catch(e){throw null==v||v.error("failed to validate refresh token",e),Error("could not validate tokens")}throw Error("could not validate token")},async exchangeAccessKey(e){if(!e)throw Error("access key must not be empty");let o;try{o=await k.accessKey.exchange(e)}catch(e){throw null==v||v.error("failed to exchange access key",e),Error("could not exchange access key")}const{sessionJwt:t}=o.data;if(!t)throw null==v||v.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await k.validateJwt(t)}catch(e){throw null==v||v.error("failed to parse jwt from access key",e),Error("could not exchange access key")}},validatePermissions:(e,o)=>k.validateTenantPermissions(e,null,o),validateTenantPermissions(e,o,t){const s=h(e,"permissions",o);return t.every((e=>s.includes(e)))},validateRoles:(e,o)=>k.validateTenantRoles(e,null,o),validateTenantRoles(e,o,t){const s=h(e,"roles",o);return t.every((e=>s.includes(e)))}});return k};u.DeliveryMethods=e.DeliveryMethods,u.RefreshTokenCookieName="DSR",u.SessionTokenCookieName="DS";export{u as default};
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../lib/constants.ts","../lib/helpers.ts","../lib/index.ts"],"sourcesContent":["// eslint-disable-next-line import/prefer-default-export\nexport const refreshTokenCookieName = 'DSR'\nexport const sessionTokenCookieName = 'DS'\n","import type { SdkResponse } from '@descope/core-js-sdk'\nimport { refreshTokenCookieName, sessionTokenCookieName } from './constants'\n\nconst generateCookie = (name: string, value: string) => `${name}=${value};`\n\nconst getCookieValue = (cookie: string | null | undefined, name: string) => {\n const match = cookie?.match(RegExp(`(?:^|;\\\\s*)${name}=([^;]*)`))\n return match ? match[1] : null\n}\n\n// eslint-disable-next-line import/prefer-default-export\nexport const withCookie =\n <T extends Array<any>, U extends Promise<SdkResponse>>(fn: (...args: T) => U) =>\n async (...args: T): Promise<SdkResponse> => {\n const resp = await fn(...args)\n\n if (!resp.data) {\n return resp\n }\n\n // eslint-disable-next-line prefer-const\n let { sessionJwt, refreshJwt } = resp.data\n let cookies = generateCookie(sessionTokenCookieName, sessionJwt)\n\n if (!refreshJwt) {\n cookies += resp.response?.headers.get('set-cookie') || ''\n refreshJwt = getCookieValue(cookies, refreshTokenCookieName)\n } else {\n cookies += generateCookie(refreshTokenCookieName, refreshJwt)\n }\n\n return { ...resp, data: { ...resp.data, refreshJwt, cookies } }\n }\n\nexport const wrapWith = <T extends Record<string, any>>(\n obj: T,\n path: string | string[],\n wrappingFn: Function,\n // eslint-disable-next-line consistent-return\n): void => {\n if (!obj) return\n\n const pathSections = typeof path === 'string' ? path.split('.') : path\n const section = pathSections.shift() || ('' as keyof T)\n\n if (pathSections.length === 0 || section === '*') {\n const wrap = (key: keyof T) => {\n if (key && typeof obj[key] === 'function') {\n // eslint-disable-next-line no-param-reassign\n obj[key] = wrappingFn(obj[key])\n } else {\n throw Error(`cannot wrap value at key \"${key.toString()}\"`)\n }\n }\n if (section === '*') {\n Object.keys(obj).forEach(wrap)\n } else {\n wrap(section)\n }\n } else {\n wrapWith(obj[section], pathSections, wrappingFn)\n }\n}\n\nexport const bulkWrapWith = (\n obj: Parameters<typeof wrapWith>[0],\n paths: string[],\n wrappingFn: Parameters<typeof wrapWith>[2],\n) => paths.forEach((path: string) => wrapWith(obj, path, wrappingFn))\n","import createSdk from '@descope/core-js-sdk'\nimport { KeyLike, jwtVerify, JWK, JWTHeaderParameters, importJWK } from 'jose'\nimport fetch, { Headers, Response, Request } from 'node-fetch'\nimport { bulkWrapWith, withCookie } from './helpers'\nimport { AuthenticationInfo } from './types'\n\nif (!globalThis.fetch) {\n // @ts-ignore\n globalThis.fetch = fetch\n // @ts-ignore\n globalThis.Headers = Headers\n // @ts-ignore\n globalThis.Request = Request\n // @ts-ignore\n globalThis.Response = Response\n}\n\nconst sdk = (...args: Parameters<typeof createSdk>) => {\n const coreSdk = createSdk(...args)\n\n bulkWrapWith(\n coreSdk,\n [\n 'otp.verify.*',\n 'magicLink.verify',\n 'magicLink.crossDevice.signUp.*',\n 'magicLink.crossDevice.signIn.*',\n 'oauth.exchange',\n 'saml.exchange',\n 'totp.verify',\n 'webauthn.signIn.finish',\n 'webauthn.signUp.finish',\n 'refresh',\n ],\n withCookie,\n )\n\n const { projectId, logger } = args[0]\n\n const keys: Record<string, KeyLike | Uint8Array> = {}\n\n const fetchKeys = async () => {\n const publicKeys: JWK[] =\n (await coreSdk.httpClient.get(`keys/${projectId}`).then((resp) => resp.json())) || []\n const kidJwksPairs = await Promise.all(\n publicKeys.map(async (key) => [key.kid, await importJWK(key)]),\n )\n\n return kidJwksPairs.reduce(\n (acc, [kid, jwk]) => (kid ? { ...acc, [kid.toString()]: jwk } : acc),\n {},\n )\n }\n\n return {\n ...coreSdk,\n\n async getKey(header: JWTHeaderParameters): Promise<KeyLike | Uint8Array> {\n if (!header?.kid) throw Error('header.kid must not be empty')\n\n if (keys[header.kid]) return keys[header.kid]\n\n // do we need to fetch once or every time?\n Object.assign(keys, await fetchKeys())\n\n if (!keys[header.kid]) throw Error('failed to fetch matching key')\n\n return keys[header.kid]\n },\n\n async validateToken(token: string): Promise<AuthenticationInfo> {\n const res = await jwtVerify(token, this.getKey, { algorithms: ['ES384'] })\n\n return { token: res.payload }\n },\n\n async validateSession(\n sessionToken: string,\n refreshToken: string,\n ): Promise<AuthenticationInfo | undefined> {\n if (!sessionToken) throw Error('session token must not be empty')\n\n try {\n const token = await this.validateToken(sessionToken)\n return token\n } catch (error) {\n try {\n await this.validateToken(refreshToken)\n\n return (await this.refresh(refreshToken)).data\n } catch (refreshTokenErr) {\n logger?.error('failed to validate refresh token', refreshTokenErr)\n\n throw Error('could not validate tokens')\n }\n }\n },\n }\n}\n\nconst sdkWithAttributes = sdk as typeof sdk & { DeliveryMethods: typeof createSdk.DeliveryMethods }\n\nsdkWithAttributes.DeliveryMethods = createSdk.DeliveryMethods\n\nexport default sdkWithAttributes\n\nexport type { DeliveryMethod, OAuthProvider } from '@descope/core-js-sdk'\n"],"names":["generateCookie","name","value","withCookie","fn","args","__awaiter","resp","data","sessionJwt","refreshJwt","cookies","_a","response","headers","get","cookie","match","RegExp","getCookieValue","Object","assign","wrapWith","obj","path","wrappingFn","pathSections","split","section","shift","length","wrap","key","Error","toString","keys","forEach","globalThis","fetch","Headers","Request","Response","sdkWithAttributes","coreSdk","createSdk","projectId","logger","getKey","header","kid","publicKeys","httpClient","then","json","Promise","all","map","importJWK","reduce","acc","jwk","validateToken","token","jwtVerify","this","algorithms","payload","validateSession","sessionToken","refreshToken","error","refresh","refreshTokenErr","DeliveryMethods"],"mappings":"yLACO,MCEDA,EAAiB,CAACC,EAAcC,IAAkB,GAAGD,KAAQC,KAQtDC,EAC4CC,GACvD,IAAUC,IAAiCC,OAAA,OAAA,OAAA,GAAA,kBACzC,MAAMC,QAAaH,KAAMC,GAEzB,IAAKE,EAAKC,KACR,OAAOD,EAIT,IAAIE,WAAEA,EAAUC,WAAEA,GAAeH,EAAKC,KAClCG,EAAUX,EDpBoB,KCoBmBS,GASrD,OAPKC,EAIHC,GAAWX,ED3BqB,MC2BkBU,IAHlDC,IAAwB,QAAbC,EAAAL,EAAKM,gBAAQ,IAAAD,OAAA,EAAAA,EAAEE,QAAQC,IAAI,gBAAiB,GACvDL,EArBiB,EAACM,EAAmCf,KACzD,MAAMgB,EAAQD,eAAAA,EAAQC,MAAMC,OAAO,cAAcjB,cACjD,OAAOgB,EAAQA,EAAM,GAAK,IAAI,EAmBbE,CAAeR,EDzBI,QC8BtBS,OAAAC,OAAAD,OAAA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,WAAWpC,IAAI,QAAQ8B,KAAaO,MAAM7C,GAASA,EAAK8C,WAAY,GAKrF,aAJ2BC,QAAQC,IACjCL,EAAWM,KAAWxB,GAAO1B,OAAA,OAAA,OAAA,GAAA,YAAC,MAAA,CAAC0B,EAAIiB,UAAWQ,EAAUzB,GAAK,QAG3C0B,QAClB,CAACC,GAAMV,EAAKW,KAAUX,EAAW7B,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAsC,IAAK,CAACV,EAAIf,YAAa0B,IAAQD,GAChE,CAAE,EAEN,MAaSxB,EAAKa,EAAOC,KAAM,MAAMhB,MAAM,gCAEnC,OAAOE,EAAKa,EAAOC,OACpB,EAEKY,cAAcC,4CAGlB,MAAO,CAAEA,aAFSC,EAAUD,EAAOE,KAAKjB,OAAQ,CAAEkB,WAAY,CAAC,YAE3CC,WACrB,EAEKC,gBACJC,EACAC,4CAEA,IAAKD,EAAc,MAAMnC,MAAM,mCAE/B,IAEE,aADoB+B,KAAKH,cAAcO,EAYxC,CAVC,MAAOE,GACP,IAGE,aAFMN,KAAKH,cAAcQ,UAEXL,KAAKO,QAAQF,IAAe7D,IAK3C,CAJC,MAAOgE,GAGP,MAFA1B,SAAAA,EAAQwB,MAAM,mCAAoCE,GAE5CvC,MAAM,4BACb,CACF,IACF,GACF,EAKHS,EAAkB+B,gBAAkB7B,EAAU6B"}
1
+ {"version":3,"file":"index.esm.js","sources":["../lib/constants.ts","../lib/helpers.ts","../lib/index.ts"],"sourcesContent":["// eslint-disable-next-line import/prefer-default-export\n/** Refresh JWT cookie name */\nexport const refreshTokenCookieName = 'DSR';\n/** Session JWT cookie name */\nexport const sessionTokenCookieName = 'DS';\n/** The key of the tenants claims in the claims map */\nexport const authorizedTenantsClaimName = 'tenants';\n/** The key of the permissions claims in the claims map either under tenant or top level */\nexport const permissionsClaimName = 'permissions';\n/** The key of the roles claims in the claims map either under tenant or top level */\nexport const rolesClaimName = 'roles';\n","import type { ResponseData, SdkResponse } from '@descope/core-js-sdk';\nimport { AuthenticationInfo } from './types';\nimport {\n refreshTokenCookieName,\n sessionTokenCookieName,\n authorizedTenantsClaimName,\n} from './constants';\n\n/**\n * Generate a cookie string from given parameters\n * @param name name of the cookie\n * @param value value of cookie that must be already encoded\n * @param options any options to put on the cookie like cookieDomain, cookieMaxAge, cookiePath\n * @returns Cookie string with all options on the string\n */\nconst generateCookie = (name: string, value: string, options?: Record<string, string | number>) =>\n `${name}=${value}; Domain=${options?.cookieDomain || ''}; Max-Age=${\n options?.cookieMaxAge || ''\n }; Path=${options?.cookiePath || '/'}; HttpOnly; SameSite=Strict`;\n\n/**\n * Parse the cookie string and return the value of the cookie\n * @param cookie the raw cookie string\n * @param name the name of the cookie to get value for\n * @returns the value of the given cookie\n */\nconst getCookieValue = (cookie: string | null | undefined, name: string) => {\n const match = cookie?.match(RegExp(`(?:^|;\\\\s*)${name}=([^;]*)`));\n return match ? match[1] : null;\n};\n\n// eslint-disable-next-line import/prefer-default-export\n/**\n * Add cookie generation to core-js functions.\n * @param fn the function we are wrapping\n * @returns Wrapped function with cookie generation\n */\nexport const withCookie =\n <T extends Array<any>, U extends Promise<SdkResponse<ResponseData>>>(fn: (...args: T) => U) =>\n async (...args: T): Promise<SdkResponse<ResponseData>> => {\n const resp = await fn(...args);\n\n // istanbul ignore next\n if (!resp.data) {\n return resp;\n }\n\n // eslint-disable-next-line prefer-const\n let { sessionJwt, refreshJwt, ...rest } = resp.data;\n const cookies = [generateCookie(sessionTokenCookieName, sessionJwt, rest)];\n\n if (!refreshJwt) {\n if (resp.response?.headers.get('set-cookie')) {\n refreshJwt = getCookieValue(\n resp.response?.headers.get('set-cookie'),\n refreshTokenCookieName,\n );\n cookies.push(resp.response?.headers.get('set-cookie')!);\n }\n } else {\n cookies.push(generateCookie(refreshTokenCookieName, refreshJwt, rest));\n }\n\n return { ...resp, data: { ...resp.data, refreshJwt, cookies } };\n };\n\n/**\n * Wrap given object internal functions (can be deep inside the object) with the given wrapping function\n * @param obj we will deep wrap functions inside this object based on the given path\n * @param path the path of internal objects to walk before wrapping the final result. Path is collection of parts separated by '.' that support '*' to say all of the keys for the part.\n * @param wrappingFn function to wrap with\n * @returns void, we update the functions in place\n */\nexport const wrapWith = <T extends Record<string, any>>(\n obj: T,\n path: string | string[],\n wrappingFn: Function,\n // eslint-disable-next-line consistent-return\n): void => {\n if (!obj) return;\n\n const pathSections = typeof path === 'string' ? path.split('.') : path;\n const section = pathSections.shift() || ('' as keyof T);\n\n if (pathSections.length === 0 || section === '*') {\n const wrap = (key: keyof T) => {\n if (key && typeof obj[key] === 'function') {\n // eslint-disable-next-line no-param-reassign\n obj[key] = wrappingFn(obj[key]);\n } else {\n // istanbul ignore next\n throw Error(`cannot wrap value at key \"${key.toString()}\"`);\n }\n };\n if (section === '*') {\n Object.keys(obj).forEach(wrap);\n } else {\n wrap(section);\n }\n } else {\n wrapWith(obj[section], pathSections, wrappingFn);\n }\n};\n\n/**\n * Wrap given object internal functions (can be deep inside the object) with the given wrapping function based on multiple paths.\n * @param obj we will deep wrap functions inside this object based on the given paths\n * @param paths multiple paths of internal objects to walk before wrapping the final result. Path is collection of parts separated by '.' that support '*' to say all of the keys for the part.\n * @param wrappingFn function to wrap with\n * @returns void, we update the functions in place\n */\nexport const bulkWrapWith = (\n obj: Parameters<typeof wrapWith>[0],\n paths: string[],\n wrappingFn: Parameters<typeof wrapWith>[2],\n) => paths.forEach((path: string) => wrapWith(obj, path, wrappingFn));\n\n/**\n * Get the claim (used for permissions or roles) for a given tenant or top level if tenant is empty\n * @param authInfo The parsed authentication info from the JWT\n * @param claim name of the claim\n * @param tenant tenant to retrieve the claim for\n * @returns\n */\nexport function getAuthorizationClaimItems(\n authInfo: AuthenticationInfo,\n claim: string,\n tenant?: string,\n): string[] {\n const value = tenant\n ? authInfo.token[authorizedTenantsClaimName]?.[tenant]?.[claim]\n : authInfo.token[claim];\n return Array.isArray(value) ? value : [];\n}\n","import createSdk, {\n SdkResponse,\n ExchangeAccessKeyResponse,\n RequestConfig,\n} from '@descope/core-js-sdk';\nimport { KeyLike, jwtVerify, JWK, JWTHeaderParameters, importJWK } from 'jose';\nimport fetch, { Headers, Response, Request } from 'node-fetch';\nimport { bulkWrapWith, withCookie, getAuthorizationClaimItems } from './helpers';\nimport { AuthenticationInfo } from './types';\nimport {\n refreshTokenCookieName,\n sessionTokenCookieName,\n permissionsClaimName,\n rolesClaimName,\n} from './constants';\n\ndeclare const BUILD_VERSION: string;\n\n/* istanbul ignore next */\nif (!globalThis.fetch) {\n // @ts-ignore\n globalThis.fetch = fetch;\n // @ts-ignore\n globalThis.Headers = Headers;\n // @ts-ignore\n globalThis.Request = Request;\n // @ts-ignore\n globalThis.Response = Response;\n}\n\nconst nodeSdk = (...args: Parameters<typeof createSdk>) => {\n const funcArgs: typeof args = [...args];\n funcArgs[0].hooks = funcArgs[0].hooks || {};\n const origBeforeRequest = funcArgs[0].hooks.beforeRequest;\n funcArgs[0].hooks.beforeRequest = (config: RequestConfig) => {\n const conf = config;\n conf.headers = {\n ...conf.headers,\n 'x-descope-sdk-name': 'nodejs',\n 'x-descope-sdk-node-version': process?.versions?.node || '',\n 'x-descope-sdk-version': BUILD_VERSION,\n };\n return origBeforeRequest?.(conf) || conf;\n };\n const coreSdk = createSdk(...funcArgs);\n\n bulkWrapWith(\n coreSdk,\n [\n 'otp.verify.*',\n 'magicLink.verify',\n 'magicLink.crossDevice.signUp.*',\n 'magicLink.crossDevice.signIn.*',\n 'oauth.exchange',\n 'saml.exchange',\n 'totp.verify',\n 'webauthn.signIn.finish',\n 'webauthn.signUp.finish',\n 'refresh',\n ],\n withCookie,\n );\n\n const { projectId, logger } = args[0];\n\n const keys: Record<string, KeyLike | Uint8Array> = {};\n\n /** Fetch the public keys (JWKs) from Descope for the configured project */\n const fetchKeys = async () => {\n const publicKeys: JWK[] = await coreSdk.httpClient\n .get(`v1/keys/${projectId}`)\n .then((resp) => resp.json());\n if (!Array.isArray(publicKeys)) return {};\n const kidJwksPairs = await Promise.all(\n publicKeys.map(async (key) => [key.kid, await importJWK(key)]),\n );\n\n return kidJwksPairs.reduce(\n (acc, [kid, jwk]) => (kid ? { ...acc, [kid.toString()]: jwk } : acc),\n {},\n );\n };\n\n const sdk = {\n ...coreSdk,\n\n /** Get the key that can validate the given JWT KID in the header. Can retrieve the public key from local cache or from Descope. */\n async getKey(header: JWTHeaderParameters): Promise<KeyLike | Uint8Array> {\n if (!header?.kid) throw Error('header.kid must not be empty');\n\n if (keys[header.kid]) return keys[header.kid];\n\n // do we need to fetch once or every time?\n Object.assign(keys, await fetchKeys());\n\n if (!keys[header.kid]) throw Error('failed to fetch matching key');\n\n return keys[header.kid];\n },\n\n /**\n * Validate the given JWT with the right key and make sure the issuer is correct\n * @param jwt the JWT string to parse and validate\n * @returns AuthenticationInfo with the parsed token and JWT. Will throw an error if validation fails.\n */\n async validateJwt(jwt: string): Promise<AuthenticationInfo> {\n // Do not hard-code the algo because library does not support `None` so all are valid\n const res = await jwtVerify(jwt, sdk.getKey, { issuer: projectId, clockTolerance: 5 });\n\n return { jwt, token: res.payload };\n },\n\n /**\n * Validate session based on at least one of session and refresh JWTs. You must provide at least one of them.\n *\n * @param sessionToken session JWT\n * @param refreshToken refresh JWT\n * @returns AuthenticationInfo promise or throws Error if there is an issue with JWTs\n */\n async validateSession(\n sessionToken?: string,\n refreshToken?: string,\n ): Promise<AuthenticationInfo> {\n if (!sessionToken && !refreshToken)\n throw Error('both refresh token and session token are empty');\n\n if (sessionToken) {\n try {\n const token = await sdk.validateJwt(sessionToken);\n return token;\n } catch (error) {\n if (!refreshToken) {\n logger?.error('failed to validate session token and no refresh token provided', error);\n throw Error('could not validate tokens');\n }\n }\n }\n if (refreshToken) {\n try {\n await sdk.validateJwt(refreshToken);\n const jwtResp = await sdk.refresh(refreshToken);\n if (jwtResp.ok) {\n const token = await sdk.validateJwt(jwtResp.data?.sessionJwt);\n return token;\n }\n throw Error(jwtResp.error?.message);\n } catch (refreshTokenErr) {\n logger?.error('failed to validate refresh token', refreshTokenErr);\n throw Error('could not validate tokens');\n }\n }\n /* istanbul ignore next */\n throw Error('could not validate token');\n },\n\n /**\n * Exchange API key (access key) for a session key\n * @param accessKey access key to exchange for a session JWT\n * @returns AuthneticationInfo with session JWT data\n */\n async exchangeAccessKey(accessKey: string): Promise<AuthenticationInfo> {\n if (!accessKey) throw Error('access key must not be empty');\n\n let resp: SdkResponse<ExchangeAccessKeyResponse>;\n try {\n resp = await sdk.accessKey.exchange(accessKey);\n } catch (error) {\n logger?.error('failed to exchange access key', error);\n throw Error('could not exchange access key');\n }\n\n const { sessionJwt } = resp.data;\n if (!sessionJwt) {\n logger?.error('failed to parse exchange access key response');\n throw Error('could not exchange access key');\n }\n\n try {\n const token = await sdk.validateJwt(sessionJwt);\n return token;\n } catch (error) {\n logger?.error('failed to parse jwt from access key', error);\n throw Error('could not exchange access key');\n }\n },\n\n /**\n * Make sure that all given permissions exist on the parsed JWT top level claims\n * @param authInfo JWT parsed info\n * @param permissions list of permissions to make sure they exist on te JWT claims\n * @returns true if all permissions exist, false otherwise\n */\n validatePermissions(authInfo: AuthenticationInfo, permissions: string[]): boolean {\n return sdk.validateTenantPermissions(authInfo, null, permissions);\n },\n\n /**\n * Make sure that all given permissions exist on the parsed JWT tenant claims\n * @param authInfo JWT parsed info\n * @param permissions list of permissions to make sure they exist on te JWT claims\n * @returns true if all permissions exist, false otherwise\n */\n validateTenantPermissions(\n authInfo: AuthenticationInfo,\n tenant: string,\n permissions: string[],\n ): boolean {\n const granted = getAuthorizationClaimItems(authInfo, permissionsClaimName, tenant);\n return permissions.every((perm) => granted.includes(perm));\n },\n\n /**\n * Make sure that all given roles exist on the parsed JWT top level claims\n * @param authInfo JWT parsed info\n * @param roles list of roles to make sure they exist on te JWT claims\n * @returns true if all roles exist, false otherwise\n */\n validateRoles(authInfo: AuthenticationInfo, roles: string[]): boolean {\n return sdk.validateTenantRoles(authInfo, null, roles);\n },\n\n /**\n * Make sure that all given roles exist on the parsed JWT tenant claims\n * @param authInfo JWT parsed info\n * @param roles list of roles to make sure they exist on te JWT claims\n * @returns true if all roles exist, false otherwise\n */\n validateTenantRoles(authInfo: AuthenticationInfo, tenant: string, roles: string[]): boolean {\n const membership = getAuthorizationClaimItems(authInfo, rolesClaimName, tenant);\n return roles.every((role) => membership.includes(role));\n },\n };\n\n return sdk;\n};\n\n/** Descope SDK client with delivery methods enum.\n *\n * Please see full documentation at {@link https://docs.descope.com/guides Descope Docs}\n * @example Usage\n *\n * ```js\n * import descopeSdk from '@descope/node-sdk';\n *\n * const myProjectId = 'xxx';\n * const sdk = descopeSdk({ projectId: myProjectId });\n *\n * const userIdentifier = 'identifier';\n * sdk.otp.signIn.email(userIdentifier);\n * const jwtResponse = sdk.otp.verify.email(userIdentifier, codeFromEmail);\n * ```\n */\nconst sdkWithAttributes = nodeSdk as typeof nodeSdk & {\n DeliveryMethods: typeof createSdk.DeliveryMethods;\n RefreshTokenCookieName: typeof refreshTokenCookieName;\n SessionTokenCookieName: typeof sessionTokenCookieName;\n};\n\nsdkWithAttributes.DeliveryMethods = createSdk.DeliveryMethods;\nsdkWithAttributes.RefreshTokenCookieName = refreshTokenCookieName;\nsdkWithAttributes.SessionTokenCookieName = sessionTokenCookieName;\n\nexport default sdkWithAttributes;\n\nexport type { DeliveryMethod, OAuthProvider } from '@descope/core-js-sdk';\n"],"names":["generateCookie","name","value","options","cookieDomain","cookieMaxAge","cookiePath","withCookie","fn","async","args","resp","data","_d","sessionJwt","refreshJwt","rest","__rest","cookies","push","_a","response","headers","get","cookie","match","RegExp","getCookieValue","_b","_c","Object","assign","wrapWith","obj","path","wrappingFn","pathSections","split","section","shift","length","wrap","key","Error","toString","keys","forEach","getAuthorizationClaimItems","authInfo","claim","tenant","token","Array","isArray","globalThis","fetch","Headers","Request","Response","sdkWithAttributes","funcArgs","hooks","origBeforeRequest","beforeRequest","config","conf","process","versions","node","coreSdk","createSdk","projectId","logger","sdk","header","kid","publicKeys","httpClient","then","json","Promise","all","map","importJWK","reduce","acc","jwk","fetchKeys","jwt","jwtVerify","getKey","issuer","clockTolerance","payload","sessionToken","refreshToken","validateJwt","error","jwtResp","refresh","ok","message","refreshTokenErr","accessKey","exchange","validatePermissions","permissions","validateTenantPermissions","granted","every","perm","includes","validateRoles","roles","validateTenantRoles","membership","role","DeliveryMethods","RefreshTokenCookieName","SessionTokenCookieName"],"mappings":"sLAEO,MCaDA,EAAiB,CAACC,EAAcC,EAAeC,IACnD,GAAGF,KAAQC,cAAiBC,aAAA,EAAAA,EAASC,eAAgB,gBACnDD,aAAA,EAAAA,EAASE,eAAgB,aACjBF,aAAA,EAAAA,EAASG,aAAc,iCAmBtBC,EAC0DC,GACrEC,SAAUC,eACR,MAAMC,QAAaH,KAAME,GAGzB,IAAKC,EAAKC,KACR,OAAOD,EAIT,IAAIE,EAAsCF,EAAKC,MAA3CE,WAAEA,EAAUC,WAAEA,KAAeC,EAA7BC,EAAAJ,EAAA,CAAA,aAAA,eACJ,MAAMK,EAAU,CAAClB,ED7CiB,KC6CsBc,EAAYE,IAcpE,OAZKD,EASHG,EAAQC,KAAKnB,ED1DmB,MC0DoBe,EAAYC,KAR/C,QAAbI,EAAAT,EAAKU,gBAAQ,IAAAD,OAAA,EAAAA,EAAEE,QAAQC,IAAI,iBAC7BR,EA3Be,EAACS,EAAmCvB,KACzD,MAAMwB,EAAQD,eAAAA,EAAQC,MAAMC,OAAO,cAAczB,cACjD,OAAOwB,EAAQA,EAAM,GAAK,IAAI,EAyBXE,CACE,QAAbC,EAAAjB,EAAKU,gBAAQ,IAAAO,OAAA,EAAAA,EAAEN,QAAQC,IAAI,cDpDC,OCuD9BL,EAAQC,KAAoB,QAAfU,EAAAlB,EAAKU,gBAAU,IAAAQ,OAAA,EAAAA,EAAAP,QAAQC,IAAI,gBAMhCO,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAApB,GAAM,CAAAC,KAAWkB,OAAAC,OAAAD,OAAAC,OAAA,GAAApB,EAAKC,MAAM,CAAAG,a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