@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/README.md +29 -231
- package/dist/cjs/examples/es6/src/index.d.ts +1 -0
- package/dist/cjs/index.cjs.js +1 -1
- package/dist/cjs/index.cjs.js.map +1 -1
- package/dist/examples/es6/src/index.d.ts +1 -0
- package/dist/index.d.ts +178 -72
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +1 -16
- package/dist/index.umd.js.map +1 -1
- package/package.json +20 -16
package/README.md
CHANGED
|
@@ -2,228 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
Use the Descope NodeJS SDK for NodeJS/Express to quickly and easily add user authentication to your application or website.
|
|
4
4
|
|
|
5
|
+
## Installing the SDK
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](https://app.descope.com).
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
Run the following code in your project. These commands will add the Descope SDK for Node as a project dependency, and set the `DESCOPE_PROJECT_ID` variable to a valid \<ProjectID\>.
|
|
9
10
|
|
|
10
|
-
```
|
|
11
|
-
|
|
12
|
-
signup[1. customer sign-up]-- customer gets OTP -->verify[3. customer verification]
|
|
13
|
-
signin[2. customer sign-in]-- customer gets OTP -->verify
|
|
14
|
-
verify-- access private API -->validate[4. session validation]
|
|
11
|
+
```bash
|
|
12
|
+
npm i --save @descope/node-sdk
|
|
15
13
|
```
|
|
16
14
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](https://app.descope.com).
|
|
20
|
-
|
|
21
|
-
* Run the following commands in your project
|
|
22
|
-
|
|
23
|
-
These commands will add the Descope NodeJS SDK as a project dependency.
|
|
24
|
-
|
|
25
|
-
```bash
|
|
26
|
-
npm i --save @descope/node-sdk
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
* Import and initialize the ExpresSDK for NodeJS client in your source code
|
|
30
|
-
|
|
31
|
-
```javascript
|
|
32
|
-
import DescopeClient from '@descope/node-sdk';
|
|
33
|
-
const descopeClient = DescopeClient({ projectId: <ProjectID> });
|
|
34
|
-
```
|
|
35
|
-
or
|
|
36
|
-
|
|
37
|
-
```javascript
|
|
38
|
-
const sdk = require('@descope/node-sdk');
|
|
39
|
-
const descopeClient = sdk({ projectId: <ProjectID> });
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
### 1. Customer Sign-up
|
|
43
|
-
|
|
44
|
-
In your sign-up route for OTP (for example, `myapp.com/signup`) generate a sign-up request and send the OTP verification code via the selected delivery method. In the example below an email is sent to "mytestmail@test.com". In additon, optional user data (for exmaple, a custom username in the code sample below) can be gathered during the sign-up process.
|
|
45
|
-
|
|
46
|
-
```javascript
|
|
47
|
-
await descopeClient.otp.signUp.email("mytestmail@test.com");
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
### 2. Customer Sign-in
|
|
51
|
-
In your sign-in route for OTP (for exmaple, `myapp.com/login`) generate a sign-in request send the OTP verification code via the selected delivery method. In the example below an email is sent to "mytestmail@test.com".
|
|
52
|
-
|
|
53
|
-
```javascript
|
|
54
|
-
await descopeClient.otp.signIn.email("mytestmail@test.com");
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
### 3. Customer Verification
|
|
58
|
-
|
|
59
|
-
In your verify customer route for OTP (for example, `myapp.com/verify`) verify the OTP from either a customer sign-up or sign-in. The VerifyCode function call will write the necessary tokens and cookies to the response writer (`w`), which will be used by the NodeJS client to validate each session interaction.
|
|
60
|
-
|
|
61
|
-
```javascript
|
|
62
|
-
const out = await descopeClient.otp.verify.email(identifier, code);
|
|
63
|
-
if (out.data.cookies) {
|
|
64
|
-
res.set('Set-Cookie', out.data.cookies);
|
|
65
|
-
}
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
### 4. Session Validation
|
|
69
|
-
|
|
70
|
-
Session validation checks to see that the visitor to your website or application is who they say they are, by comparing the value in the validation variables against the session data that is already stored.
|
|
71
|
-
|
|
72
|
-
```javascript
|
|
73
|
-
const out = await descopeClient.validateSession(session_jwt, refresh_jwt);
|
|
74
|
-
if (out?.cookies) {
|
|
75
|
-
res.set('Set-Cookie', out.cookies);
|
|
76
|
-
}
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
## ExpressStart with MagicLink Authentication
|
|
80
|
-
|
|
81
|
-
This section will help you implement user authentication using Magiclinks. A typical four step flow for OTP authentictaion is shown below.
|
|
82
|
-
|
|
83
|
-
```mermaid
|
|
84
|
-
flowchart LR
|
|
85
|
-
signup[1. customer sign-up]-- customer gets MagicLink -->verify[3. MagicLink verification]
|
|
86
|
-
signin[2. customer sign-in]-- customer gets MagicLink -->verify
|
|
87
|
-
verify-- access private API -->validate[4. session validation]
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
### Prerequisites
|
|
91
|
-
|
|
92
|
-
Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](https://app.descope.com).
|
|
93
|
-
|
|
94
|
-
* Run the following commands in your project
|
|
95
|
-
|
|
96
|
-
These commands will add the Descope NodeJS SDK as a project dependency.
|
|
97
|
-
|
|
98
|
-
```bash
|
|
99
|
-
npm i --save @descope/node-sdk
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
* Import and initialize the ExpresSDK for NodeJS client in your source code
|
|
103
|
-
|
|
104
|
-
```javascript
|
|
105
|
-
import DescopeClient from '@descope/node-sdk';
|
|
106
|
-
const descopeClient = DescopeClient({ projectId: <ProjectID> });
|
|
107
|
-
```
|
|
108
|
-
or
|
|
109
|
-
|
|
110
|
-
```javascript
|
|
111
|
-
const sdk = require('@descope/node-sdk');
|
|
112
|
-
const descopeClient = sdk({ projectId: <ProjectID> });
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
### 1. Customer Sign-up
|
|
116
|
-
|
|
117
|
-
In your sign-up route using magic link (for example, `myapp.com/signup`) generate a sign-up request and send the magic link via the selected delivery method. In the example below an email is sent to "mytestmail@test.com" containing the magic link and the link will automatically return back to the provided URL ("https://mydomain.com/verify"). In additon, optional user data (for exmaple, a custom username in the code sample below) can be gathered during the sign-up process.
|
|
118
|
-
|
|
119
|
-
```javascript
|
|
120
|
-
await descopeClient.magiclink.signUp.email("mytestmail@test.com", { name: "custom name" })
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
### 2. Customer Sign-in
|
|
124
|
-
In your sign-in route using magic link (for exmaple, `myapp.com/login`) generate a sign-in request send the magic link via the selected delivery method. In the example below an email is sent to "mytestmail@test.com" containing the magic link and the link will automatically return back to the provided URL ("https://mydomain.com/verify").
|
|
125
|
-
|
|
126
|
-
```javascript
|
|
127
|
-
await descopeClient.magiclink.signIn.email("mytestmail@test.com")
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
### 3. Customer Verification
|
|
131
|
-
|
|
132
|
-
In your verify customer route for magic link (for example, `mydomain.com/verify`) verify the token from either a customer sign-up or sign-in.
|
|
133
|
-
|
|
134
|
-
```javascript
|
|
135
|
-
const out = await descopeClient.magiclink.verify(token)
|
|
136
|
-
if (out.data.cookies) {
|
|
137
|
-
res.set('Set-Cookie', out.data.cookies)
|
|
138
|
-
}
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
### 4. Session Validation
|
|
142
|
-
|
|
143
|
-
Session validation checks to see that the visitor to your website or application is who they say they are, by comparing the value in the validation variables against the session data that is already stored.
|
|
144
|
-
|
|
145
|
-
```javascript
|
|
146
|
-
const out = await descopeClient.validateSession(session_jwt, refresh_jwt)
|
|
147
|
-
if (out?.cookies) {
|
|
148
|
-
res.set('Set-Cookie', out.cookies)
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
## ExpressStart with OAuth Authentication
|
|
153
|
-
|
|
154
|
-
In the example below, we assume using the Descope builtin oauth provider, in that case, we dont need to define any specific application details.
|
|
155
|
-
|
|
156
|
-
### Prerequisites
|
|
157
|
-
|
|
158
|
-
Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](https://app.descope.com).
|
|
159
|
-
|
|
160
|
-
* Run the following commands in your project
|
|
161
|
-
|
|
162
|
-
These commands will add the Descope NodeJS SDK as a project dependency.
|
|
163
|
-
|
|
164
|
-
```bash
|
|
165
|
-
npm i --save @descope/node-sdk
|
|
166
|
-
```
|
|
15
|
+
## What do you want to implement?
|
|
167
16
|
|
|
168
|
-
|
|
17
|
+
Click one of the following links to open the documentation for that specific functionality.
|
|
169
18
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
```
|
|
174
|
-
or
|
|
175
|
-
|
|
176
|
-
```javascript
|
|
177
|
-
const sdk = require('@descope/node-sdk');
|
|
178
|
-
const descopeClient = sdk({ projectId: <ProjectID> });
|
|
179
|
-
```
|
|
180
|
-
|
|
181
|
-
* Make sure to set the return url to exchange in the Descope Oauth authentication methods settings or use the start first argument.
|
|
182
|
-
|
|
183
|
-
### 1. Customer Sign-up/Sign-In
|
|
184
|
-
|
|
185
|
-
In your OAuth start flow (for example, `myapp.com/login-with-facebook`) generate a url to redirect the user to. In the example below the login
|
|
186
|
-
|
|
187
|
-
```javascript
|
|
188
|
-
const out = await descopeClient.oauth.start.facebook();
|
|
189
|
-
return out.data.url;
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
### 2. Customer Exchange
|
|
193
|
-
|
|
194
|
-
In your exchange for any of the oauth provider (for example, `mydomain.com/exchange`) verify the code from the provider by using the exchange method.
|
|
195
|
-
|
|
196
|
-
```javascript
|
|
197
|
-
const code = req.query.code
|
|
198
|
-
const out = await descopeClient.oauth.exchnage(code);
|
|
199
|
-
if (out.data.cookies) {
|
|
200
|
-
res.set('Set-Cookie', out.data.cookies);
|
|
201
|
-
}
|
|
202
|
-
```
|
|
203
|
-
|
|
204
|
-
### 3. Session Validation
|
|
205
|
-
|
|
206
|
-
Session validation checks to see that the visitor to your website or application is who they say they are, by comparing the value in the validation variables against the session data that is already stored.
|
|
207
|
-
|
|
208
|
-
```javascript
|
|
209
|
-
const out = await descopeClient.validateSession(session_jwt, refresh_jwt);
|
|
210
|
-
if (out.cookies) {
|
|
211
|
-
res.set('Set-Cookie', out.cookies);
|
|
212
|
-
}
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
### 4. Error handling
|
|
216
|
-
|
|
217
|
-
Each authentication function may return an error upon authentication failure or bad request. In case of an error, you will recieve an sdk response with `ok` equal to false and the error details are also included, such as the `errorCode` and the `errorDescription`. Needless to say, the `data` will be empty whenever an error occur.
|
|
218
|
-
|
|
219
|
-
```javascript
|
|
220
|
-
const out = await descopeClient.oauth.start.facebook();
|
|
221
|
-
if (!out.ok) {
|
|
222
|
-
console.log(`an error has occured [code: ${out.errorCode}] with message: "${out.errorDescription}"`)
|
|
223
|
-
} else {
|
|
224
|
-
...
|
|
225
|
-
}
|
|
226
|
-
```
|
|
19
|
+
- [x] [One time passwords (OTP)](./docs/otp.md)
|
|
20
|
+
- [x] [Magic Links](./docs/magiclink.md)
|
|
21
|
+
- [x] [OAuth/Social](./docs/oauth.md)
|
|
227
22
|
|
|
228
23
|
## Run the Examples
|
|
229
24
|
|
|
@@ -231,7 +26,7 @@ Instantly run the end-to-end ExpresSDK for NodeJS examples, as shown below. The
|
|
|
231
26
|
|
|
232
27
|
### Prerequisites
|
|
233
28
|
|
|
234
|
-
Run the following commands in your project. Replace any instance of
|
|
29
|
+
Run the following commands in your project. Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](https://app.descope.com).
|
|
235
30
|
|
|
236
31
|
This commands will add the Descope NodeJS SDK as a project dependency, clone the SDK repository locally, and set the `DESCOPE_PROJECT_ID`.
|
|
237
32
|
|
|
@@ -245,26 +40,29 @@ export DESCOPE_PROJECT_ID=<ProjectID>
|
|
|
245
40
|
**TL;DR**: Run `npm run quick`
|
|
246
41
|
|
|
247
42
|
Run the following commands in the root of the project to build and run the examples.
|
|
43
|
+
|
|
248
44
|
1. Run this to start the ES6 typescript module example
|
|
249
45
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
46
|
+
```code bash
|
|
47
|
+
npm i && \
|
|
48
|
+
npm run build && \
|
|
49
|
+
cd examples/es6 && \
|
|
50
|
+
npm i && \
|
|
51
|
+
npm run generateCerts && \
|
|
52
|
+
npm start
|
|
53
|
+
```
|
|
257
54
|
|
|
258
55
|
2. Run this to start the commonjs example
|
|
259
56
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
57
|
+
```code bash
|
|
58
|
+
npm i && \
|
|
59
|
+
npm run build && \
|
|
60
|
+
cd examples/commonjs && \
|
|
61
|
+
npm i && \
|
|
62
|
+
npm run generateCerts && \
|
|
63
|
+
npm start
|
|
64
|
+
```
|
|
267
65
|
|
|
268
66
|
## License
|
|
269
67
|
|
|
270
|
-
The Descope ExpresSDK for
|
|
68
|
+
The Descope ExpresSDK for Node is licensed for use under the terms and conditions of the [MIT license Agreement](https://github.com/descope/node-sdk/blob/main/LICENSE).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/cjs/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("
|
|
1
|
+
"use strict";var e=require("@descope/core-js-sdk"),t=require("jose"),s=require("node-fetch"),o=require("tslib");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=r(e),n=r(s);const i=(e,t,s)=>`${e}=${t}; Domain=${(null==s?void 0:s.cookieDomain)||""}; Max-Age=${(null==s?void 0:s.cookieMaxAge)||""}; Path=${(null==s?void 0:s.cookiePath)||"/"}; HttpOnly; SameSite=Strict`,c=e=>async(...t)=>{var s,r,a;const n=await e(...t);if(!n.data)return n;let c=n.data,{sessionJwt:l,refreshJwt:d}=c,u=o.__rest(c,["sessionJwt","refreshJwt"]);const h=[i("DS",l,u)];return d?h.push(i("DSR",d,u)):(null===(s=n.response)||void 0===s?void 0:s.headers.get("set-cookie"))&&(d=((e,t)=>{const s=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return s?s[1]:null})(null===(r=n.response)||void 0===r?void 0:r.headers.get("set-cookie"),"DSR"),h.push(null===(a=n.response)||void 0===a?void 0:a.headers.get("set-cookie"))),Object.assign(Object.assign({},n),{data:Object.assign(Object.assign({},n.data),{refreshJwt:d,cookies:h})})},l=(e,t,s)=>{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]=s(e[t])};"*"===r?Object.keys(e).forEach(t):t(r)}else l(e[r],o,s)};function d(e,t,s){var o,r;const a=s?null===(r=null===(o=e.token.tenants)||void 0===o?void 0:o[s])||void 0===r?void 0:r[t]:e.token[t];return Array.isArray(a)?a:[]}globalThis.fetch||(globalThis.fetch=n.default,globalThis.Headers=s.Headers,globalThis.Request=s.Request,globalThis.Response=s.Response);const u=(...e)=>{const s=[...e];s[0].hooks=s[0].hooks||{};const o=s[0].hooks.beforeRequest;s[0].hooks.beforeRequest=e=>{var t;const s=e;return s.headers=Object.assign(Object.assign({},s.headers),{"x-descope-sdk-name":"nodejs","x-descope-sdk-node-version":(null===(t=null===process||void 0===process?void 0:process.versions)||void 0===t?void 0:t.node)||"","x-descope-sdk-version":"1.0.4-alpha.7"}),(null==o?void 0:o(s))||s};const r=a.default(...s);var n,i;n=r,i=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(n,e,i)));const{projectId:u,logger:h}=e[0],v={},f=Object.assign(Object.assign({},r),{async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(v[e.kid])return v[e.kid];if(Object.assign(v,await(async()=>{const e=await r.httpClient.get(`v1/keys/${u}`).then((e=>e.json()));return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await t.importJWK(e)])))).reduce(((e,[t,s])=>t?Object.assign(Object.assign({},e),{[t.toString()]:s}):e),{}):{}})()),!v[e.kid])throw Error("failed to fetch matching key");return v[e.kid]},validateJwt:async e=>({jwt:e,token:(await t.jwtVerify(e,f.getKey,{issuer:u,clockTolerance:5})).payload}),async validateSession(e,t){var s,o;if(!e&&!t)throw Error("both refresh token and session token are empty");if(e)try{return await f.validateJwt(e)}catch(e){if(!t)throw null==h||h.error("failed to validate session token and no refresh token provided",e),Error("could not validate tokens")}if(t)try{await f.validateJwt(t);const e=await f.refresh(t);if(e.ok){return await f.validateJwt(null===(s=e.data)||void 0===s?void 0:s.sessionJwt)}throw Error(null===(o=e.error)||void 0===o?void 0:o.message)}catch(e){throw null==h||h.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 t;try{t=await f.accessKey.exchange(e)}catch(e){throw null==h||h.error("failed to exchange access key",e),Error("could not exchange access key")}const{sessionJwt:s}=t.data;if(!s)throw null==h||h.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await f.validateJwt(s)}catch(e){throw null==h||h.error("failed to parse jwt from access key",e),Error("could not exchange access key")}},validatePermissions:(e,t)=>f.validateTenantPermissions(e,null,t),validateTenantPermissions(e,t,s){const o=d(e,"permissions",t);return s.every((e=>o.includes(e)))},validateRoles:(e,t)=>f.validateTenantRoles(e,null,t),validateTenantRoles(e,t,s){const o=d(e,"roles",t);return s.every((e=>o.includes(e)))}});return f};u.DeliveryMethods=a.default.DeliveryMethods,u.RefreshTokenCookieName="DSR",u.SessionTokenCookieName="DS",module.exports=u;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.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":"0MACO,MCEDA,EAAiB,CAACC,EAAcC,IAAkB,GAAGD,KAAQC,KAQtDC,EAC4CC,GACvD,IAAUC,IAAiCC,EAAAA,eAAA,OAAA,OAAA,GAAA,kBACzC,MAAMC,QAAaH,KAAMC,GAEzB,IAAKE,EAAKC,KACR,OAAOD,EAIT,IAAIE,WAAEA,EAAUC,WAAEA,GAAeH,EAAKC,KAClCG,EAAUX,EDpB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.cjs.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":"0MAEO,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,EAAAA,OAAAJ,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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