Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@descope/node-sdk

Package Overview
Dependencies
Maintainers
0
Versions
316
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@descope/node-sdk - npm Package Compare versions

Comparing version 0.0.0-next-c074bc45-20230308 to 0.0.0-next-c1eb2147-20240627

2

dist/cjs/index.cjs.js

@@ -1,2 +0,2 @@

"use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("jose"),a=require("node-fetch-commonjs");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(t),r=n(a);const i=t=>async(...s)=>{var a,n,o;const r=await t(...s);if(!r.data)return r;let i=r.data,{refreshJwt:l}=i,d=e.__rest(i,["refreshJwt"]);const p=[];var m;return l?p.push(`${"DSR"}=${l}; Domain=${(null==(m=d)?void 0:m.cookieDomain)||""}; Max-Age=${(null==m?void 0:m.cookieMaxAge)||""}; Path=${(null==m?void 0:m.cookiePath)||"/"}; HttpOnly; SameSite=Strict`):(null===(a=r.response)||void 0===a?void 0:a.headers.get("set-cookie"))&&(l=((e,t)=>{const s=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return s?s[1]:null})(null===(n=r.response)||void 0===n?void 0:n.headers.get("set-cookie"),"DSR"),p.push(null===(o=r.response)||void 0===o?void 0:o.headers.get("set-cookie"))),Object.assign(Object.assign({},r),{data:Object.assign(Object.assign({},r.data),{refreshJwt:l,cookies:p})})};function l(e,t,s){var a,n;const o=s?null===(n=null===(a=e.token.tenants)||void 0===a?void 0:a[s])||void 0===n?void 0:n[t]:e.token[t];return Array.isArray(o)?o:[]}var d={create:"/v1/mgmt/user/create",update:"/v1/mgmt/user/update",delete:"/v1/mgmt/user/delete",load:"/v1/mgmt/user",search:"/v1/mgmt/user/search",updateStatus:"/v1/mgmt/user/update/status",updateEmail:"/v1/mgmt/user/update/email",updatePhone:"/v1/mgmt/user/update/phone",updateDisplayName:"/v1/mgmt/user/update/name",addRole:"/v1/mgmt/user/update/role/add",removeRole:"/v1/mgmt/user/update/role/remove",addTenant:"/v1/mgmt/user/update/tenant/add",removeTenant:"/v1/mgmt/user/update/tenant/remove"},p={create:"/v1/mgmt/accesskey/create",load:"/v1/mgmt/accesskey",search:"/v1/mgmt/accesskey/search",update:"/v1/mgmt/accesskey/update",deactivate:"/v1/mgmt/accesskey/deactivate",activate:"/v1/mgmt/accesskey/activate",delete:"/v1/mgmt/accesskey/delete"},m={create:"/v1/mgmt/tenant/create",update:"/v1/mgmt/tenant/update",delete:"/v1/mgmt/tenant/delete",loadAll:"/v1/mgmt/tenant/all"},c={configure:"/v1/mgmt/sso/settings",metadata:"/v1/mgmt/sso/metadata",mapping:"/v1/mgmt/sso/mapping"},u={update:"/v1/mgmt/jwt/update"},h={create:"/v1/mgmt/permission/create",update:"/v1/mgmt/permission/update",delete:"/v1/mgmt/permission/delete",loadAll:"/v1/mgmt/permission/all"},v={create:"/v1/mgmt/role/create",update:"/v1/mgmt/role/update",delete:"/v1/mgmt/role/delete",loadAll:"/v1/mgmt/role/all"},g={loadAllGroups:"/v1/mgmt/group/all",loadAllGroupsForMember:"/v1/mgmt/group/member/all",loadAllGroupMembers:"/v1/mgmt/group/members"};const f=(e,s)=>({create:(a,n,o,r,i,l)=>t.transformResponse(e.httpClient.post(d.create,{loginId:a,email:n,phone:o,displayName:r,roleNames:i,userTenants:l},{token:s}),(e=>e.user)),invite:(a,n,o,r,i,l)=>t.transformResponse(e.httpClient.post(d.create,{loginId:a,email:n,phone:o,displayName:r,roleNames:i,userTenants:l,invite:!0},{token:s}),(e=>e.user)),update:(a,n,o,r,i,l)=>t.transformResponse(e.httpClient.post(d.update,{loginId:a,email:n,phone:o,displayName:r,roleNames:i,userTenants:l},{token:s}),(e=>e.user)),delete:a=>t.transformResponse(e.httpClient.post(d.delete,{loginId:a},{token:s})),load:a=>t.transformResponse(e.httpClient.get(d.load,{queryParams:{loginId:a},token:s}),(e=>e.user)),loadByUserId:a=>t.transformResponse(e.httpClient.get(d.load,{queryParams:{userId:a},token:s}),(e=>e.user)),searchAll:(a,n,o,r)=>t.transformResponse(e.httpClient.post(d.search,{tenantIds:a,roleNames:n,limit:o,page:r},{token:s}),(e=>e.users)),activate:a=>t.transformResponse(e.httpClient.post(d.updateStatus,{loginId:a,status:"enabled"},{token:s}),(e=>e.user)),deactivate:a=>t.transformResponse(e.httpClient.post(d.updateStatus,{loginId:a,status:"disabled"},{token:s}),(e=>e.user)),updateEmail:(a,n,o)=>t.transformResponse(e.httpClient.post(d.updateEmail,{loginId:a,email:n,verified:o},{token:s}),(e=>e.user)),updatePhone:(a,n,o)=>t.transformResponse(e.httpClient.post(d.updatePhone,{loginId:a,phone:n,verified:o},{token:s}),(e=>e.user)),updateDisplayName:(a,n)=>t.transformResponse(e.httpClient.post(d.updateDisplayName,{loginId:a,displayName:n},{token:s}),(e=>e.user)),addRoles:(a,n)=>t.transformResponse(e.httpClient.post(d.addRole,{loginId:a,roleNames:n},{token:s}),(e=>e.user)),removeRoles:(a,n)=>t.transformResponse(e.httpClient.post(d.removeRole,{loginId:a,roleNames:n},{token:s}),(e=>e.user)),addTenant:(a,n)=>t.transformResponse(e.httpClient.post(d.addTenant,{loginId:a,tenantId:n},{token:s}),(e=>e.user)),removeTenant:(a,n)=>t.transformResponse(e.httpClient.post(d.removeTenant,{loginId:a,tenantId:n},{token:s}),(e=>e.user)),addTenantRoles:(a,n,o)=>t.transformResponse(e.httpClient.post(d.addRole,{loginId:a,tenantId:n,roleNames:o},{token:s}),(e=>e.user)),removeTenantRoles:(a,n,o)=>t.transformResponse(e.httpClient.post(d.removeRole,{loginId:a,tenantId:n,roleNames:o},{token:s}),(e=>e.user))}),k=(e,s)=>({create:(a,n)=>t.transformResponse(e.httpClient.post(m.create,{name:a,selfProvisioningDomains:n},{token:s})),createWithId:(a,n,o)=>t.transformResponse(e.httpClient.post(m.create,{id:a,name:n,selfProvisioningDomains:o},{token:s})),update:(a,n,o)=>t.transformResponse(e.httpClient.post(m.update,{id:a,name:n,selfProvisioningDomains:o},{token:s})),delete:a=>t.transformResponse(e.httpClient.post(m.delete,{id:a},{token:s})),loadAll:()=>t.transformResponse(e.httpClient.get(m.loadAll,{token:s}),(e=>e.tenants))}),y=(e,s)=>({update:(a,n)=>t.transformResponse(e.httpClient.post(u.update,{jwt:a,customClaims:n},{token:s}))}),R=(e,s)=>({create:(a,n)=>t.transformResponse(e.httpClient.post(h.create,{name:a,description:n},{token:s})),update:(a,n,o)=>t.transformResponse(e.httpClient.post(h.update,{name:a,newName:n,description:o},{token:s})),delete:a=>t.transformResponse(e.httpClient.post(h.delete,{name:a},{token:s})),loadAll:()=>t.transformResponse(e.httpClient.get(h.loadAll,{token:s}),(e=>e.permissions))}),C=(e,s)=>({create:(a,n,o)=>t.transformResponse(e.httpClient.post(v.create,{name:a,description:n,permissionNames:o},{token:s})),update:(a,n,o,r)=>t.transformResponse(e.httpClient.post(v.update,{name:a,newName:n,description:o,permissionNames:r},{token:s})),delete:a=>t.transformResponse(e.httpClient.post(v.delete,{name:a},{token:s})),loadAll:()=>t.transformResponse(e.httpClient.get(v.loadAll,{token:s}),(e=>e.roles))}),w=(e,s)=>({loadAllGroups:a=>t.transformResponse(e.httpClient.post(g.loadAllGroups,{tenantId:a},{token:s})),loadAllGroupsForMember:(a,n,o)=>t.transformResponse(e.httpClient.post(g.loadAllGroupsForMember,{tenantId:a,loginIds:o,userIds:n},{token:s})),loadAllGroupMembers:(a,n)=>t.transformResponse(e.httpClient.post(g.loadAllGroupMembers,{tenantId:a,groupId:n},{token:s}))}),I=(e,s)=>({configureSettings:(a,n,o,r,i,l)=>t.transformResponse(e.httpClient.post(c.configure,{tenantId:a,idpURL:n,entityId:r,idpCert:o,redirectURL:i,domain:l},{token:s})),configureMetadata:(a,n)=>t.transformResponse(e.httpClient.post(c.metadata,{tenantId:a,idpMetadataURL:n},{token:s})),configureMapping:(a,n,o)=>t.transformResponse(e.httpClient.post(c.mapping,{tenantId:a,roleMapping:n,attributeMapping:o},{token:s}))}),b=(e,s)=>({create:(a,n,o,r)=>t.transformResponse(e.httpClient.post(p.create,{name:a,expireTime:n,roleNames:o,keyTenants:r},{token:s})),load:a=>t.transformResponse(e.httpClient.get(p.load,{queryParams:{id:a},token:s}),(e=>e.key)),searchAll:a=>t.transformResponse(e.httpClient.post(p.search,{tenantIds:a},{token:s}),(e=>e.keys)),update:(a,n)=>t.transformResponse(e.httpClient.post(p.update,{id:a,name:n},{token:s}),(e=>e.key)),deactivate:a=>t.transformResponse(e.httpClient.post(p.deactivate,{id:a},{token:s})),activate:a=>t.transformResponse(e.httpClient.post(p.activate,{id:a},{token:s})),delete:a=>t.transformResponse(e.httpClient.post(p.delete,{id:a},{token:s}))});var A;null!==(A=globalThis.Headers)&&void 0!==A||(globalThis.Headers=a.Headers);const j=(...e)=>(e.forEach((e=>{var t,s;e&&(null!==(t=(s=e).highWaterMark)&&void 0!==t||(s.highWaterMark=32212254720))})),r.default(...e)),T=a=>{var n,{managementKey:r}=a,d=e.__rest(a,["managementKey"]);const p=o.default(Object.assign(Object.assign({},d),{fetch:j,baseHeaders:Object.assign(Object.assign({},d.baseHeaders),{"x-descope-sdk-name":"nodejs","x-descope-sdk-node-version":(null===(n=null===process||void 0===process?void 0:process.versions)||void 0===n?void 0:n.node)||"","x-descope-sdk-version":"0.0.0-next-c074bc45-20230308"})})),{projectId:m,logger:c}=d,u={},h=((e,t)=>({user:f(e,t),accessKey:b(e,t),tenant:k(e,t),sso:I(e,t),jwt:y(e,t),permission:R(e,t),role:C(e,t),group:w(e,t)}))(p,r),v=Object.assign(Object.assign({},p),{management:h,async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(u[e.kid])return u[e.kid];if(Object.assign(u,await(async()=>{const e=(await p.httpClient.get(`v2/keys/${m}`).then((e=>e.json()))).keys;return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await s.importJWK(e)])))).reduce(((e,[t,s])=>t?Object.assign(Object.assign({},e),{[t.toString()]:s}):e),{}):{}})()),!u[e.kid])throw Error("failed to fetch matching key");return u[e.kid]},async validateJwt(e){var t;const a=(await s.jwtVerify(e,v.getKey,{clockTolerance:5})).payload;if(a&&(a.iss=null===(t=a.iss)||void 0===t?void 0:t.split("/").pop(),a.iss!==m))throw new s.errors.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");return{jwt:e,token:a}},async validateSession(e){if(!e)throw Error("session token is required for validation");try{return await v.validateJwt(e)}catch(e){throw null==c||c.error("session validation failed",e),Error("session validation failed")}},async refreshSession(e){var t,s;if(!e)throw Error("refresh token is required to refresh a session");try{await v.validateJwt(e);const a=await v.refresh(e);if(a.ok){return await v.validateJwt(null===(t=a.data)||void 0===t?void 0:t.sessionJwt)}throw Error(null===(s=a.error)||void 0===s?void 0:s.errorMessage)}catch(e){throw null==c||c.error("refresh token validation failed",e),Error("refresh token validation failed")}},async validateAndRefreshSession(e,t){if(!e&&!t)throw Error("both session and refresh tokens are empty");try{return await v.validateSession(e)}catch(e){null==c||c.log("session validation failed - trying to refresh it")}return v.refreshSession(t)},async exchangeAccessKey(e){if(!e)throw Error("access key must not be empty");let t;try{t=await v.accessKey.exchange(e)}catch(e){throw null==c||c.error("failed to exchange access key",e),Error("could not exchange access key")}const{sessionJwt:s}=t.data;if(!s)throw null==c||c.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await v.validateJwt(s)}catch(e){throw null==c||c.error("failed to parse jwt from access key",e),Error("could not exchange access key")}},validatePermissions:(e,t)=>v.validateTenantPermissions(e,null,t),validateTenantPermissions(e,t,s){const a=l(e,"permissions",t);return s.every((e=>a.includes(e)))},validateRoles:(e,t)=>v.validateTenantRoles(e,null,t),validateTenantRoles(e,t,s){const a=l(e,"roles",t);return s.every((e=>a.includes(e)))}});return t.wrapWith(v,["otp.verify.email","otp.verify.sms","otp.verify.whatsapp","magicLink.verify","enchantedLink.signUp","enchantedLink.signIn","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"],i)};T.RefreshTokenCookieName="DSR",T.SessionTokenCookieName="DS",module.exports=T;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("jose"),n=require("cross-fetch");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=o(t);const r=t=>async(...s)=>{var n,o,a;const r=await t(...s);if(!r.data)return r;let i=r.data,{refreshJwt:l}=i,p=e.__rest(i,["refreshJwt"]);const d=[];var m;return l?d.push(`${"DSR"}=${l}; Domain=${(null==(m=p)?void 0:m.cookieDomain)||""}; Max-Age=${(null==m?void 0:m.cookieMaxAge)||""}; Path=${(null==m?void 0:m.cookiePath)||"/"}; HttpOnly; SameSite=Strict`):(null===(n=r.response)||void 0===n?void 0:n.headers.get("set-cookie"))&&(l=((e,t)=>{const s=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return s?s[1]:null})(null===(o=r.response)||void 0===o?void 0:o.headers.get("set-cookie"),"DSR"),d.push(null===(a=r.response)||void 0===a?void 0:a.headers.get("set-cookie"))),Object.assign(Object.assign({},r),{data:Object.assign(Object.assign({},r.data),{refreshJwt:l,cookies:d})})};function i(e,t,s){var n,o;const a=s?null===(o=null===(n=e.token.tenants)||void 0===n?void 0:n[s])||void 0===o?void 0:o[t]:e.token[t];return Array.isArray(a)?a:[]}function l(e,t){var s;return!!(null===(s=e.token.tenants)||void 0===s?void 0:s[t])}var p={create:"/v1/mgmt/user/create",createBatch:"/v1/mgmt/user/create/batch",update:"/v1/mgmt/user/update",delete:"/v1/mgmt/user/delete",deleteAllTestUsers:"/v1/mgmt/user/test/delete/all",load:"/v1/mgmt/user",logout:"/v1/mgmt/user/logout",search:"/v1/mgmt/user/search",getProviderToken:"/v1/mgmt/user/provider/token",updateStatus:"/v1/mgmt/user/update/status",updateLoginId:"/v1/mgmt/user/update/loginid",updateEmail:"/v1/mgmt/user/update/email",updatePhone:"/v1/mgmt/user/update/phone",updateDisplayName:"/v1/mgmt/user/update/name",updatePicture:"/v1/mgmt/user/update/picture",updateCustomAttribute:"/v1/mgmt/user/update/customAttribute",setRole:"/v1/mgmt/user/update/role/set",addRole:"/v1/mgmt/user/update/role/add",removeRole:"/v1/mgmt/user/update/role/remove",setSSOApps:"/v1/mgmt/user/update/ssoapp/set",addSSOApps:"/v1/mgmt/user/update/ssoapp/add",removeSSOApps:"/v1/mgmt/user/update/ssoapp/remove",addTenant:"/v1/mgmt/user/update/tenant/add",removeTenant:"/v1/mgmt/user/update/tenant/remove",setPassword:"/v1/mgmt/user/password/set",setTemporaryPassword:"/v1/mgmt/user/password/set/temporary",setActivePassword:"/v1/mgmt/user/password/set/active",expirePassword:"/v1/mgmt/user/password/expire",removeAllPasskeys:"/v1/mgmt/user/passkeys/delete",generateOTPForTest:"/v1/mgmt/tests/generate/otp",generateMagicLinkForTest:"/v1/mgmt/tests/generate/magiclink",generateEnchantedLinkForTest:"/v1/mgmt/tests/generate/enchantedlink",generateEmbeddedLink:"/v1/mgmt/user/signin/embeddedlink",history:"/v1/mgmt/user/history"},d={updateName:"/v1/mgmt/project/update/name",clone:"/v1/mgmt/project/clone",export:"/v1/mgmt/project/export",import:"/v1/mgmt/project/import"},m={create:"/v1/mgmt/accesskey/create",load:"/v1/mgmt/accesskey",search:"/v1/mgmt/accesskey/search",update:"/v1/mgmt/accesskey/update",deactivate:"/v1/mgmt/accesskey/deactivate",activate:"/v1/mgmt/accesskey/activate",delete:"/v1/mgmt/accesskey/delete"},c={create:"/v1/mgmt/tenant/create",update:"/v1/mgmt/tenant/update",delete:"/v1/mgmt/tenant/delete",load:"/v1/mgmt/tenant",settings:"/v1/mgmt/tenant/settings",loadAll:"/v1/mgmt/tenant/all",searchAll:"/v1/mgmt/tenant/search"},g={oidcCreate:"/v1/mgmt/sso/idp/app/oidc/create",samlCreate:"/v1/mgmt/sso/idp/app/saml/create",oidcUpdate:"/v1/mgmt/sso/idp/app/oidc/update",samlUpdate:"/v1/mgmt/sso/idp/app/saml/update",delete:"/v1/mgmt/sso/idp/app/delete",load:"/v1/mgmt/sso/idp/app/load",loadAll:"/v1/mgmt/sso/idp/apps/load"},u={settings:"/v1/mgmt/sso/settings",metadata:"/v1/mgmt/sso/metadata",mapping:"/v1/mgmt/sso/mapping",settingsv2:"/v2/mgmt/sso/settings",oidc:{configure:"/v1/mgmt/sso/oidc"},saml:{configure:"/v1/mgmt/sso/saml",metadata:"/v1/mgmt/sso/saml/metadata"}},h={update:"/v1/mgmt/jwt/update",impersonate:"/v1/mgmt/impersonate"},v={settings:"/v1/mgmt/password/settings"},f={create:"/v1/mgmt/permission/create",update:"/v1/mgmt/permission/update",delete:"/v1/mgmt/permission/delete",loadAll:"/v1/mgmt/permission/all"},k={create:"/v1/mgmt/role/create",update:"/v1/mgmt/role/update",delete:"/v1/mgmt/role/delete",loadAll:"/v1/mgmt/role/all",search:"/v1/mgmt/role/search"},R={list:"/v1/mgmt/flow/list",delete:"/v1/mgmt/flow/delete",export:"/v1/mgmt/flow/export",import:"/v1/mgmt/flow/import"},C={export:"/v1/mgmt/theme/export",import:"/v1/mgmt/theme/import"},y={loadAllGroups:"/v1/mgmt/group/all",loadAllGroupsForMember:"/v1/mgmt/group/member/all",loadAllGroupMembers:"/v1/mgmt/group/members"},I={search:"/v1/mgmt/audit/search",createEvent:"/v1/mgmt/audit/event"},b={schemaSave:"/v1/mgmt/authz/schema/save",schemaDelete:"/v1/mgmt/authz/schema/delete",schemaLoad:"/v1/mgmt/authz/schema/load",nsSave:"/v1/mgmt/authz/ns/save",nsDelete:"/v1/mgmt/authz/ns/delete",rdSave:"/v1/mgmt/authz/rd/save",rdDelete:"/v1/mgmt/authz/rd/delete",reCreate:"/v1/mgmt/authz/re/create",reDelete:"/v1/mgmt/authz/re/delete",reDeleteResources:"/v1/mgmt/authz/re/deleteresources",hasRelations:"/v1/mgmt/authz/re/has",who:"/v1/mgmt/authz/re/who",resource:"/v1/mgmt/authz/re/resource",targets:"/v1/mgmt/authz/re/targets",targetAll:"/v1/mgmt/authz/re/targetall",getModified:"/v1/mgmt/authz/getmodified"};const w=(e,s)=>({create:function(n,o,a,r,i,l,d,m,c,g,u,h,v,f){const k="string"==typeof o?{loginId:n,email:o,phone:a,displayName:r,givenName:u,middleName:h,familyName:v,roleNames:i,userTenants:l,customAttributes:d,picture:m,verifiedEmail:c,verifiedPhone:g,additionalLoginIds:f}:Object.assign(Object.assign({loginId:n},o),{roleNames:null==o?void 0:o.roles,roles:void 0});return t.transformResponse(e.httpClient.post(p.create,k,{token:s}),(e=>e.user))},createTestUser:function(n,o,a,r,i,l,d,m,c,g,u,h,v,f){const k="string"==typeof o?{loginId:n,email:o,phone:a,displayName:r,givenName:u,middleName:h,familyName:v,roleNames:i,userTenants:l,customAttributes:d,picture:m,verifiedEmail:c,verifiedPhone:g,additionalLoginIds:f,test:!0}:Object.assign(Object.assign({loginId:n},o),{roleNames:null==o?void 0:o.roles,roles:void 0,test:!0});return t.transformResponse(e.httpClient.post(p.create,k,{token:s}),(e=>e.user))},invite:function(n,o,a,r,i,l,d,m,c,g,u,h,v,f,k,R,C){const y="string"==typeof o?{loginId:n,email:o,phone:a,displayName:r,givenName:f,middleName:k,familyName:R,roleNames:i,userTenants:l,invite:!0,customAttributes:d,picture:m,verifiedEmail:c,verifiedPhone:g,inviteUrl:u,sendMail:h,sendSMS:v,additionalLoginIds:C}:Object.assign(Object.assign({loginId:n},o),{roleNames:null==o?void 0:o.roles,roles:void 0,invite:!0});return t.transformResponse(e.httpClient.post(p.create,y,{token:s}),(e=>e.user))},inviteBatch:(n,o,a,r,i)=>t.transformResponse(e.httpClient.post(p.createBatch,{users:n,invite:!0,inviteUrl:o,sendMail:a,sendSMS:r,templateOptions:i},{token:s}),(e=>e)),update:function(n,o,a,r,i,l,d,m,c,g,u,h,v,f){const k="string"==typeof o?{loginId:n,email:o,phone:a,displayName:r,givenName:u,middleName:h,familyName:v,roleNames:i,userTenants:l,customAttributes:d,picture:m,verifiedEmail:c,verifiedPhone:g,additionalLoginIds:f}:Object.assign(Object.assign({loginId:n},o),{roleNames:null==o?void 0:o.roles,roles:void 0});return t.transformResponse(e.httpClient.post(p.update,k,{token:s}),(e=>e.user))},delete:n=>t.transformResponse(e.httpClient.post(p.delete,{loginId:n},{token:s})),deleteByUserId:n=>t.transformResponse(e.httpClient.post(p.delete,{userId:n},{token:s})),deleteAllTestUsers:()=>t.transformResponse(e.httpClient.delete(p.deleteAllTestUsers,{token:s})),load:n=>t.transformResponse(e.httpClient.get(p.load,{queryParams:{loginId:n},token:s}),(e=>e.user)),loadByUserId:n=>t.transformResponse(e.httpClient.get(p.load,{queryParams:{userId:n},token:s}),(e=>e.user)),logoutUser:n=>t.transformResponse(e.httpClient.post(p.logout,{loginId:n},{token:s})),logoutUserByUserId:n=>t.transformResponse(e.httpClient.post(p.logout,{userId:n},{token:s})),searchAll:(n,o,a,r,i,l,d,m,c,g)=>t.transformResponse(e.httpClient.post(p.search,{tenantIds:n,roleNames:o,limit:a,page:r,testUsersOnly:i,withTestUser:l,customAttributes:d,statuses:m,emails:c,phones:g},{token:s}),(e=>e.users)),search:n=>t.transformResponse(e.httpClient.post(p.search,Object.assign(Object.assign({},n),{roleNames:n.roles,roles:void 0}),{token:s}),(e=>e.users)),getProviderToken:(n,o)=>t.transformResponse(e.httpClient.get(p.getProviderToken,{queryParams:{loginId:n,provider:o},token:s}),(e=>e)),activate:n=>t.transformResponse(e.httpClient.post(p.updateStatus,{loginId:n,status:"enabled"},{token:s}),(e=>e.user)),deactivate:n=>t.transformResponse(e.httpClient.post(p.updateStatus,{loginId:n,status:"disabled"},{token:s}),(e=>e.user)),updateLoginId:(n,o)=>t.transformResponse(e.httpClient.post(p.updateLoginId,{loginId:n,newLoginId:o},{token:s}),(e=>e.user)),updateEmail:(n,o,a)=>t.transformResponse(e.httpClient.post(p.updateEmail,{loginId:n,email:o,verified:a},{token:s}),(e=>e.user)),updatePhone:(n,o,a)=>t.transformResponse(e.httpClient.post(p.updatePhone,{loginId:n,phone:o,verified:a},{token:s}),(e=>e.user)),updateDisplayName:(n,o,a,r,i)=>t.transformResponse(e.httpClient.post(p.updateDisplayName,{loginId:n,displayName:o,givenName:a,middleName:r,familyName:i},{token:s}),(e=>e.user)),updatePicture:(n,o)=>t.transformResponse(e.httpClient.post(p.updatePicture,{loginId:n,picture:o},{token:s}),(e=>e.user)),updateCustomAttribute:(n,o,a)=>t.transformResponse(e.httpClient.post(p.updateCustomAttribute,{loginId:n,attributeKey:o,attributeValue:a},{token:s}),(e=>e.user)),setRoles:(n,o)=>t.transformResponse(e.httpClient.post(p.setRole,{loginId:n,roleNames:o},{token:s}),(e=>e.user)),addRoles:(n,o)=>t.transformResponse(e.httpClient.post(p.addRole,{loginId:n,roleNames:o},{token:s}),(e=>e.user)),removeRoles:(n,o)=>t.transformResponse(e.httpClient.post(p.removeRole,{loginId:n,roleNames:o},{token:s}),(e=>e.user)),addTenant:(n,o)=>t.transformResponse(e.httpClient.post(p.addTenant,{loginId:n,tenantId:o},{token:s}),(e=>e.user)),removeTenant:(n,o)=>t.transformResponse(e.httpClient.post(p.removeTenant,{loginId:n,tenantId:o},{token:s}),(e=>e.user)),setTenantRoles:(n,o,a)=>t.transformResponse(e.httpClient.post(p.setRole,{loginId:n,tenantId:o,roleNames:a},{token:s}),(e=>e.user)),addTenantRoles:(n,o,a)=>t.transformResponse(e.httpClient.post(p.addRole,{loginId:n,tenantId:o,roleNames:a},{token:s}),(e=>e.user)),removeTenantRoles:(n,o,a)=>t.transformResponse(e.httpClient.post(p.removeRole,{loginId:n,tenantId:o,roleNames:a},{token:s}),(e=>e.user)),addSSOapps:(n,o)=>t.transformResponse(e.httpClient.post(p.addSSOApps,{loginId:n,ssoAppIds:o},{token:s}),(e=>e.user)),setSSOapps:(n,o)=>t.transformResponse(e.httpClient.post(p.setSSOApps,{loginId:n,ssoAppIds:o},{token:s}),(e=>e.user)),removeSSOapps:(n,o)=>t.transformResponse(e.httpClient.post(p.removeSSOApps,{loginId:n,ssoAppIds:o},{token:s}),(e=>e.user)),generateOTPForTestUser:(n,o,a)=>t.transformResponse(e.httpClient.post(p.generateOTPForTest,{deliveryMethod:n,loginId:o,loginOptions:a},{token:s}),(e=>e)),generateMagicLinkForTestUser:(n,o,a,r)=>t.transformResponse(e.httpClient.post(p.generateMagicLinkForTest,{deliveryMethod:n,loginId:o,URI:a,loginOptions:r},{token:s}),(e=>e)),generateEnchantedLinkForTestUser:(n,o,a)=>t.transformResponse(e.httpClient.post(p.generateEnchantedLinkForTest,{loginId:n,URI:o,loginOptions:a},{token:s}),(e=>e)),generateEmbeddedLink:(n,o)=>t.transformResponse(e.httpClient.post(p.generateEmbeddedLink,{loginId:n,customClaims:o},{token:s}),(e=>e)),setTemporaryPassword:(n,o)=>t.transformResponse(e.httpClient.post(p.setTemporaryPassword,{loginId:n,password:o},{token:s}),(e=>e)),setActivePassword:(n,o)=>t.transformResponse(e.httpClient.post(p.setActivePassword,{loginId:n,password:o},{token:s}),(e=>e)),setPassword:(n,o)=>t.transformResponse(e.httpClient.post(p.setPassword,{loginId:n,password:o},{token:s}),(e=>e)),expirePassword:n=>t.transformResponse(e.httpClient.post(p.expirePassword,{loginId:n},{token:s}),(e=>e)),removeAllPasskeys:n=>t.transformResponse(e.httpClient.post(p.removeAllPasskeys,{loginId:n},{token:s}),(e=>e)),history:n=>t.transformResponse(e.httpClient.post(p.history,n,{token:s}),(e=>e))}),A=(e,s)=>({updateName:n=>t.transformResponse(e.httpClient.post(d.updateName,{name:n},{token:s})),clone:(n,o)=>t.transformResponse(e.httpClient.post(d.clone,{name:n,tag:o},{token:s})),export:()=>t.transformResponse(e.httpClient.post(d.export,{},{token:s}),(e=>e.files)),import:n=>t.transformResponse(e.httpClient.post(d.import,{files:n},{token:s}))}),O=(e,s)=>({create:(n,o,a)=>t.transformResponse(e.httpClient.post(c.create,{name:n,selfProvisioningDomains:o,customAttributes:a},{token:s})),createWithId:(n,o,a,r)=>t.transformResponse(e.httpClient.post(c.create,{id:n,name:o,selfProvisioningDomains:a,customAttributes:r},{token:s})),update:(n,o,a,r)=>t.transformResponse(e.httpClient.post(c.update,{id:n,name:o,selfProvisioningDomains:a,customAttributes:r},{token:s})),delete:(n,o)=>t.transformResponse(e.httpClient.post(c.delete,{id:n,cascade:o},{token:s})),load:n=>t.transformResponse(e.httpClient.get(c.load,{queryParams:{id:n},token:s}),(e=>e)),loadAll:()=>t.transformResponse(e.httpClient.get(c.loadAll,{token:s}),(e=>e.tenants)),searchAll:(n,o,a,r)=>t.transformResponse(e.httpClient.post(c.searchAll,{tenantIds:n,tenantNames:o,tenantSelfProvisioningDomains:a,customAttributes:r},{token:s}),(e=>e.tenants)),getSettings:n=>t.transformResponse(e.httpClient.get(c.settings,{queryParams:{id:n},token:s}),(e=>e)),configureSettings:(n,o)=>t.transformResponse(e.httpClient.post(c.settings,Object.assign(Object.assign({},o),{tenantId:n}),{token:s}))}),S=(e,s)=>({update:(n,o)=>t.transformResponse(e.httpClient.post(h.update,{jwt:n,customClaims:o},{token:s})),impersonate:(n,o,a)=>t.transformResponse(e.httpClient.post(h.impersonate,{impersonatorId:n,loginId:o,validateConsent:a},{token:s}))}),j=(e,s)=>({create:(n,o)=>t.transformResponse(e.httpClient.post(f.create,{name:n,description:o},{token:s})),update:(n,o,a)=>t.transformResponse(e.httpClient.post(f.update,{name:n,newName:o,description:a},{token:s})),delete:n=>t.transformResponse(e.httpClient.post(f.delete,{name:n},{token:s})),loadAll:()=>t.transformResponse(e.httpClient.get(f.loadAll,{token:s}),(e=>e.permissions))}),N=(e,s)=>({create:(n,o,a,r)=>t.transformResponse(e.httpClient.post(k.create,{name:n,description:o,permissionNames:a,tenantId:r},{token:s})),update:(n,o,a,r,i)=>t.transformResponse(e.httpClient.post(k.update,{name:n,newName:o,description:a,permissionNames:r,tenantId:i},{token:s})),delete:(n,o)=>t.transformResponse(e.httpClient.post(k.delete,{name:n,tenantId:o},{token:s})),loadAll:()=>t.transformResponse(e.httpClient.get(k.loadAll,{token:s}),(e=>e.roles)),search:n=>t.transformResponse(e.httpClient.post(k.search,n,{token:s}),(e=>e.roles))}),P=(e,s)=>({loadAllGroups:n=>t.transformResponse(e.httpClient.post(y.loadAllGroups,{tenantId:n},{token:s})),loadAllGroupsForMember:(n,o,a)=>t.transformResponse(e.httpClient.post(y.loadAllGroupsForMember,{tenantId:n,loginIds:a,userIds:o},{token:s})),loadAllGroupMembers:(n,o)=>t.transformResponse(e.httpClient.post(y.loadAllGroupMembers,{tenantId:n,groupId:o},{token:s}))}),T=(e,s)=>({getSettings:n=>t.transformResponse(e.httpClient.get(u.settings,{queryParams:{tenantId:n},token:s}),(e=>e)),deleteSettings:n=>t.transformResponse(e.httpClient.delete(u.settings,{queryParams:{tenantId:n},token:s})),configureSettings:(n,o,a,r,i,l)=>t.transformResponse(e.httpClient.post(u.settings,{tenantId:n,idpURL:o,entityId:r,idpCert:a,redirectURL:i,domains:l},{token:s})),configureMetadata:(n,o,a,r)=>t.transformResponse(e.httpClient.post(u.metadata,{tenantId:n,idpMetadataURL:o,redirectURL:a,domains:r},{token:s})),configureMapping:(n,o,a)=>t.transformResponse(e.httpClient.post(u.mapping,{tenantId:n,roleMappings:o,attributeMapping:a},{token:s})),configureOIDCSettings:(n,o,a)=>{const r=Object.assign(Object.assign({},o),{userAttrMapping:o.attributeMapping});return delete r.attributeMapping,t.transformResponse(e.httpClient.post(u.oidc.configure,{tenantId:n,settings:r,domains:a},{token:s}))},configureSAMLSettings:(n,o,a,r)=>t.transformResponse(e.httpClient.post(u.saml.configure,{tenantId:n,settings:o,redirectUrl:a,domains:r},{token:s})),configureSAMLByMetadata:(n,o,a,r)=>t.transformResponse(e.httpClient.post(u.saml.metadata,{tenantId:n,settings:o,redirectUrl:a,domains:r},{token:s})),loadSettings:n=>t.transformResponse(e.httpClient.get(u.settingsv2,{queryParams:{tenantId:n},token:s}),(e=>{var t,s;const n=e;return n.oidc&&(n.oidc=Object.assign(Object.assign({},n.oidc),{attributeMapping:n.oidc.userAttrMapping}),delete n.oidc.userAttrMapping),(null===(t=n.saml)||void 0===t?void 0:t.groupsMapping)&&(n.saml.groupsMapping=null===(s=n.saml)||void 0===s?void 0:s.groupsMapping.map((e=>{const t=e;return t.roleName=t.role.name,delete t.role,t}))),n}))}),M=(e,s)=>({create:(n,o,a,r,i,l)=>t.transformResponse(e.httpClient.post(m.create,{name:n,expireTime:o,roleNames:a,keyTenants:r,userId:i,customClaims:l},{token:s})),load:n=>t.transformResponse(e.httpClient.get(m.load,{queryParams:{id:n},token:s}),(e=>e.key)),searchAll:n=>t.transformResponse(e.httpClient.post(m.search,{tenantIds:n},{token:s}),(e=>e.keys)),update:(n,o)=>t.transformResponse(e.httpClient.post(m.update,{id:n,name:o},{token:s}),(e=>e.key)),deactivate:n=>t.transformResponse(e.httpClient.post(m.deactivate,{id:n},{token:s})),activate:n=>t.transformResponse(e.httpClient.post(m.activate,{id:n},{token:s})),delete:n=>t.transformResponse(e.httpClient.post(m.delete,{id:n},{token:s}))}),E=(e,s)=>({list:()=>t.transformResponse(e.httpClient.post(R.list,{},{token:s})),delete:n=>t.transformResponse(e.httpClient.post(R.delete,{ids:n},{token:s})),export:n=>t.transformResponse(e.httpClient.post(R.export,{flowId:n},{token:s})),import:(n,o,a)=>t.transformResponse(e.httpClient.post(R.import,{flowId:n,flow:o,screens:a},{token:s}))}),x=(e,s)=>({export:()=>t.transformResponse(e.httpClient.post(C.export,{},{token:s})),import:n=>t.transformResponse(e.httpClient.post(C.import,{theme:n},{token:s}))}),U=(e,s)=>({search:n=>{const o=Object.assign(Object.assign({},n),{externalIds:n.loginIds});return delete o.loginIds,t.transformResponse(e.httpClient.post(I.search,o,{token:s}),(e=>null==e?void 0:e.audits.map((e=>{const t=Object.assign(Object.assign({},e),{occurred:parseFloat(e.occurred),loginIds:e.externalIds});return delete t.externalIds,t}))))},createEvent:n=>{const o=Object.assign({},n);return t.transformResponse(e.httpClient.post(I.createEvent,o,{token:s}))}}),L=(e,s)=>({saveSchema:(n,o)=>t.transformResponse(e.httpClient.post(b.schemaSave,{schema:n,upgrade:o},{token:s})),deleteSchema:()=>t.transformResponse(e.httpClient.post(b.schemaDelete,{},{token:s})),loadSchema:()=>t.transformResponse(e.httpClient.post(b.schemaLoad,{},{token:s}),(e=>e.schema)),saveNamespace:(n,o,a)=>t.transformResponse(e.httpClient.post(b.nsSave,{namespace:n,oldName:o,schemaName:a},{token:s})),deleteNamespace:(n,o)=>t.transformResponse(e.httpClient.post(b.nsDelete,{name:n,schemaName:o},{token:s})),saveRelationDefinition:(n,o,a,r)=>t.transformResponse(e.httpClient.post(b.rdSave,{relationDefinition:n,namespace:o,oldName:a,schemaName:r},{token:s})),deleteRelationDefinition:(n,o,a)=>t.transformResponse(e.httpClient.post(b.rdDelete,{name:n,namespace:o,schemaName:a},{token:s})),createRelations:n=>t.transformResponse(e.httpClient.post(b.reCreate,{relations:n},{token:s})),deleteRelations:n=>t.transformResponse(e.httpClient.post(b.reDelete,{relations:n},{token:s})),deleteRelationsForResources:n=>t.transformResponse(e.httpClient.post(b.reDeleteResources,{resources:n},{token:s})),hasRelations:n=>t.transformResponse(e.httpClient.post(b.hasRelations,{relationQueries:n},{token:s}),(e=>e.relationQueries)),whoCanAccess:(n,o,a)=>t.transformResponse(e.httpClient.post(b.who,{resource:n,relationDefinition:o,namespace:a},{token:s}),(e=>e.targets)),resourceRelations:n=>t.transformResponse(e.httpClient.post(b.resource,{resource:n},{token:s}),(e=>e.relations)),targetsRelations:n=>t.transformResponse(e.httpClient.post(b.targets,{targets:n},{token:s}),(e=>e.relations)),whatCanTargetAccess:n=>t.transformResponse(e.httpClient.post(b.targetAll,{target:n},{token:s}),(e=>e.relations)),getModified:n=>t.transformResponse(e.httpClient.post(b.getModified,{since:n?n.getTime():0},{token:s}),(e=>e))}),D=(e,s)=>({createOidcApplication:n=>{var o;return t.transformResponse(e.httpClient.post(g.oidcCreate,Object.assign(Object.assign({},n),{enabled:null===(o=n.enabled)||void 0===o||o}),{token:s}))},createSamlApplication:n=>{var o;return t.transformResponse(e.httpClient.post(g.samlCreate,Object.assign(Object.assign({},n),{enabled:null===(o=n.enabled)||void 0===o||o}),{token:s}))},updateOidcApplication:n=>t.transformResponse(e.httpClient.post(g.oidcUpdate,Object.assign({},n),{token:s})),updateSamlApplication:n=>t.transformResponse(e.httpClient.post(g.samlUpdate,Object.assign({},n),{token:s})),delete:n=>t.transformResponse(e.httpClient.post(g.delete,{id:n},{token:s})),load:n=>t.transformResponse(e.httpClient.get(g.load,{queryParams:{id:n},token:s}),(e=>e)),loadAll:()=>t.transformResponse(e.httpClient.get(g.loadAll,{token:s}),(e=>e.apps))}),q=(e,s)=>({getSettings:n=>t.transformResponse(e.httpClient.get(v.settings,{queryParams:{tenantId:n},token:s}),(e=>e)),configureSettings:(n,o)=>t.transformResponse(e.httpClient.post(v.settings,Object.assign(Object.assign({},o),{tenantId:n}),{token:s}))});var F;null!==(F=globalThis.Headers)&&void 0!==F||(globalThis.Headers=n.Headers);const z=(...e)=>(e.forEach((e=>{var t,s;e&&(null!==(t=(s=e).highWaterMark)&&void 0!==t||(s.highWaterMark=31457280))})),n.fetch(...e)),J=n=>{var o,{managementKey:p,publicKey:d}=n,m=e.__rest(n,["managementKey","publicKey"]);const c=a.default(Object.assign(Object.assign({fetch:z},m),{baseHeaders:Object.assign(Object.assign({},m.baseHeaders),{"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":"0.0.0-next-c1eb2147-20240627"})})),{projectId:g,logger:u}=m,h={},v=((e,t)=>({user:w(e,t),project:A(e,t),accessKey:M(e,t),tenant:O(e,t),ssoApplication:D(e,t),sso:T(e,t),jwt:S(e,t),permission:j(e,t),password:q(e,t),role:N(e,t),group:P(e,t),flow:E(e,t),theme:x(e,t),audit:U(e,t),authz:L(e,t)}))(c,p),f=Object.assign(Object.assign({},c),{management:v,async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(h[e.kid])return h[e.kid];if(Object.assign(h,await(async()=>{if(d)try{const e=JSON.parse(d),t=await s.importJWK(e);return{[e.kid]:t}}catch(e){throw null==u||u.error("Failed to parse the provided public key",e),new Error(`Failed to parse public key. Error: ${e}`)}const e=(await c.httpClient.get(`v2/keys/${g}`).then((e=>e.json()))).keys;return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await s.importJWK(e)])))).reduce(((e,[t,s])=>t?Object.assign(Object.assign({},e),{[t.toString()]:s}):e),{}):{}})()),!h[e.kid])throw Error("failed to fetch matching key");return h[e.kid]},async validateJwt(e){var t;const n=(await s.jwtVerify(e,f.getKey,{clockTolerance:5})).payload;if(n&&(n.iss=null===(t=n.iss)||void 0===t?void 0:t.split("/").pop(),n.iss!==g))throw new s.errors.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");return{jwt:e,token:n}},async validateSession(e){if(!e)throw Error("session token is required for validation");try{return await f.validateJwt(e)}catch(e){throw null==u||u.error("session validation failed",e),Error(`session validation failed. Error: ${e}`)}},async refreshSession(e){var t,s;if(!e)throw Error("refresh token is required to refresh a session");try{await f.validateJwt(e);const n=await f.refresh(e);if(n.ok){return await f.validateJwt(null===(t=n.data)||void 0===t?void 0:t.sessionJwt)}throw Error(null===(s=n.error)||void 0===s?void 0:s.errorMessage)}catch(e){throw null==u||u.error("refresh token validation failed",e),Error(`refresh token validation failed, Error: ${e}`)}},async validateAndRefreshSession(e,t){if(!e&&!t)throw Error("both session and refresh tokens are empty");try{return await f.validateSession(e)}catch(e){null==u||u.log(`session validation failed with error ${e} - trying to refresh it`)}return f.refreshSession(t)},async exchangeAccessKey(e,t){if(!e)throw Error("access key must not be empty");let s;try{s=await f.accessKey.exchange(e,t)}catch(e){throw null==u||u.error("failed to exchange access key",e),Error(`could not exchange access key - Failed to exchange. Error: ${e}`)}const{sessionJwt:n}=s.data;if(!n)throw null==u||u.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await f.validateJwt(n)}catch(e){throw null==u||u.error("failed to parse jwt from access key",e),Error(`could not exchange access key - failed to validate jwt. Error: ${e}`)}},validatePermissions:(e,t)=>f.validateTenantPermissions(e,"",t),getMatchedPermissions:(e,t)=>f.getMatchedTenantPermissions(e,"",t),validateTenantPermissions(e,t,s){if(t&&!l(e,t))return!1;const n=i(e,"permissions",t);return s.every((e=>n.includes(e)))},getMatchedTenantPermissions(e,t,s){if(t&&!l(e,t))return[];const n=i(e,"permissions",t);return s.filter((e=>n.includes(e)))},validateRoles:(e,t)=>f.validateTenantRoles(e,"",t),getMatchedRoles:(e,t)=>f.getMatchedTenantRoles(e,"",t),validateTenantRoles(e,t,s){if(t&&!l(e,t))return!1;const n=i(e,"roles",t);return s.every((e=>n.includes(e)))},getMatchedTenantRoles(e,t,s){if(t&&!l(e,t))return[];const n=i(e,"roles",t);return s.filter((e=>n.includes(e)))}});return t.wrapWith(f,["otp.verify.email","otp.verify.sms","otp.verify.voice","otp.verify.whatsapp","magicLink.verify","enchantedLink.signUp","enchantedLink.signIn","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"],r)};J.RefreshTokenCookieName="DSR",J.SessionTokenCookieName="DS",exports.default=J,exports.descopeErrors={badRequest:"E011001",missingArguments:"E011002",invalidRequest:"E011003",invalidArguments:"E011004",wrongOTPCode:"E061102",tooManyOTPAttempts:"E061103",enchantedLinkPending:"E062503",userNotFound:"E062108"};
//# sourceMappingURL=index.cjs.js.map
import * as _descope_core_js_sdk from '@descope/core-js-sdk';
import _descope_core_js_sdk__default, { SdkResponse, ExchangeAccessKeyResponse } from '@descope/core-js-sdk';
export { DeliveryMethod, OAuthProvider } from '@descope/core-js-sdk';
import _descope_core_js_sdk__default, { DeliveryMethod, UserResponse, SdkResponse, AccessKeyLoginOptions, ExchangeAccessKeyResponse } from '@descope/core-js-sdk';
export { DeliveryMethod, JWTResponse, OAuthProvider, ResponseData, SdkResponse } from '@descope/core-js-sdk';
import { JWTHeaderParameters, KeyLike } from 'jose';
/** Represents a tenant association for a User or Access Key. The tenantId is required to denote
/** Parsed JWT token */
interface Token {
sub?: string;
exp?: number;
iss?: string;
[claim: string]: unknown;
}
/** All information regarding token including the raw JWT, parsed JWT and cookies */
interface AuthenticationInfo {
jwt: string;
token: Token;
cookies?: string[];
}
declare type DeliveryMethodForTestUser = DeliveryMethod | 'Embedded';
declare type ExpirationUnit = 'minutes' | 'hours' | 'days' | 'weeks';
/**
* Represents a tenant association for a User or Access Key. The tenantId is required to denote
* which tenant the user or access key belongs to. The roleNames array is an optional list of

@@ -18,2 +35,67 @@ * roles for the user or access key in this specific tenant.

};
/**
* Options to create or update an OIDC application.
*
* **Note:** When updating, `id` will be required to perform the operation
*/
declare type OidcApplicationOptions = {
name: string;
loginPageUrl: string;
id?: string;
description?: string;
logo?: string;
enabled?: boolean;
};
/**
* Options to create or update a SAML application.
*
* **Note:** When updating, `id` will be required to perform the operation
*/
declare type SamlApplicationOptions = {
name: string;
loginPageUrl: string;
id?: string;
description?: string;
logo?: string;
enabled?: boolean;
useMetadataInfo?: boolean;
metadataUrl?: string;
entityId?: string;
acsUrl?: string;
certificate?: string;
attributeMapping?: SamlIdpAttributeMappingInfo[];
groupsMapping?: SamlIdpGroupsMappingInfo[];
acsAllowedCallbacks?: string[];
subjectNameIdType?: string;
subjectNameIdFormat?: string;
};
/**
* Represents a SAML IDP attribute mapping object. Use this class for mapping Descope attribute
* to the relevant SAML Assertion attributes matching your expected SP attributes names.
*/
declare type SamlIdpAttributeMappingInfo = {
name: string;
type: string;
value: string;
};
/** Represents a SAML IDP Role Group mapping object. */
declare type SAMLIDPRoleGroupMappingInfo = {
id: string;
name: string;
};
/**
* Represents a SAML IDP groups mapping object. Use this class for mapping Descope roles
* to the relevant SAML Assertion groups attributes that matching your expected SP groups attributes names.
*/
declare type SamlIdpGroupsMappingInfo = {
name: string;
type: string;
filterType: string;
value: string;
roles: SAMLIDPRoleGroupMappingInfo[];
};
/** The ID of a newly created SSO application */
declare type CreateSSOApplicationResponse = {
id: string;
};
/** An access key that can be used to access descope */

@@ -30,2 +112,4 @@ declare type AccessKey = {

createdBy: string;
clientId: string;
boundUserId?: string;
};

@@ -40,4 +124,5 @@ /** Access Key extended details including created key cleartext */

groups: string[];
role: string;
roleName: string;
};
declare type RoleMappings = RoleMapping[];
/** Represents a mapping between Descope and IDP user attributes */

@@ -61,3 +146,75 @@ declare type AttributeMapping = {

selfProvisioningDomains: string[];
customAttributes?: Record<string, string | number | boolean>;
domains?: string[];
authType?: 'none' | 'saml' | 'oidc';
};
/** Represents settings of a tenant in a project. It has an id, a name and an array of
* self provisioning domains used to associate users with that tenant.
*/
declare type TenantSettings = {
selfProvisioningDomains: string[];
domains?: string[];
authType?: 'none' | 'saml' | 'oidc';
sessionSettingsEnabled?: boolean;
refreshTokenExpiration?: number;
refreshTokenExpirationUnit?: ExpirationUnit;
sessionTokenExpiration?: number;
sessionTokenExpirationUnit?: ExpirationUnit;
stepupTokenExpiration?: number;
stepupTokenExpirationUnit?: ExpirationUnit;
enableInactivity?: boolean;
InactivityTime?: number;
InactivityTimeUnit?: ExpirationUnit;
JITDisabled?: boolean;
};
/** Represents password settings of a tenant in a project. It has the password policy details. */
declare type PasswordSettings = {
enabled: boolean;
minLength: number;
lowercase: boolean;
uppercase: boolean;
number: boolean;
nonAlphaNumeric: boolean;
expiration: boolean;
expirationWeeks: number;
reuse: boolean;
reuseAmount: number;
lock: boolean;
lockAttempts: number;
};
/** Represents OIDC settings of an SSO application in a project. */
declare type SSOApplicationOIDCSettings = {
loginPageUrl: string;
issuer: string;
discoveryUrl: string;
};
/** Represents SAML settings of an SSO application in a project. */
declare type SSOApplicationSAMLSettings = {
loginPageUrl: string;
idpCert: string;
useMetadataInfo: boolean;
metadataUrl: string;
entityId: string;
acsUrl: string;
certificate: string;
attributeMapping: SamlIdpAttributeMappingInfo[];
groupsMapping: SamlIdpGroupsMappingInfo[];
idpMetadataUrl: string;
idpEntityId: string;
idpSsoUrl: string;
acsAllowedCallbacks: string[];
subjectNameIdType: string;
subjectNameIdFormat: string;
};
/** Represents an SSO application in a project. */
declare type SSOApplication = {
id: string;
name: string;
description: string;
enabled: boolean;
logo: string;
appType: string;
samlSettings: SSOApplicationSAMLSettings;
oidcSettings: SSOApplicationOIDCSettings;
};
/** Represents a permission in a project. It has a name and optionally a description.

@@ -78,3 +235,12 @@ * It also has a flag indicating whether it is system default or not.

permissionNames: string[];
createdTime: number;
tenantId?: string;
};
/** Search roles based on the parameters */
declare type RoleSearchOptions = {
tenantIds?: string[];
roleNames?: string[];
roleNameLike?: string;
permissionNames?: string[];
};
/** Represents a group in a project. It has an id and display name and a list of group members. */

@@ -92,37 +258,434 @@ declare type Group = {

};
declare type Flow = {
id: string;
name: string;
description?: string;
dsl: any;
disabled: boolean;
etag?: string;
};
declare type FlowMetadata = {
id: string;
name: string;
description?: string;
disabled: boolean;
};
declare type Screen = {
id: string;
flowId: string;
inputs?: any;
interactions?: any;
htmlTemplate: any;
};
declare type FlowsResponse = {
flows: FlowMetadata[];
total: number;
};
declare type FlowResponse = {
flow: Flow;
screens: Screen[];
};
declare type Theme = {
id: string;
cssTemplate?: any;
};
declare type ThemeResponse = {
theme: Theme;
};
declare type GenerateOTPForTestResponse = {
loginId: string;
code: string;
};
declare type GenerateMagicLinkForTestResponse = {
loginId: string;
link: string;
};
declare type GenerateEnchantedLinkForTestResponse = {
loginId: string;
link: string;
pendingRef: string;
};
declare type GenerateEmbeddedLinkResponse = {
token: string;
};
declare type AttributesTypes = string | boolean | number;
declare type TemplateOptions = Record<string, string>;
declare type User = {
loginId: string;
email?: string;
phone?: string;
displayName?: string;
roles?: string[];
userTenants?: AssociatedTenant[];
customAttributes?: Record<string, AttributesTypes>;
picture?: string;
verifiedEmail?: boolean;
verifiedPhone?: boolean;
test?: boolean;
additionalLoginIds?: string[];
password?: string;
hashedPassword?: UserPasswordHashed;
seed?: string;
};
declare type UserPasswordHashed = {
bcrypt?: UserPasswordBcrypt;
pbkdf2?: UserPasswordPbkdf2;
firebase?: UserPasswordFirebase;
django?: UserPasswordDjango;
};
declare type UserPasswordBcrypt = {
hash: string;
};
declare type UserPasswordPbkdf2 = {
hash: string;
salt: string;
iterations: number;
type: 'sha1' | 'sha256' | 'sha512';
};
declare type UserPasswordFirebase = {
hash: string;
salt: string;
saltSeparator: string;
signerKey: string;
memory: number;
rounds: number;
};
declare type UserPasswordDjango = {
hash: string;
};
declare type UserMapping = {
name: string;
email: string;
username: string;
phoneNumber: string;
group: string;
};
declare type RoleItem = {
id: string;
name: string;
};
declare type GroupsMapping = {
role: RoleItem;
groups: string[];
};
declare type SSOSettingsResponse = {
tenantId: string;
idpEntityId: string;
idpSSOUrl: string;
idpCertificate: string;
idpMetadataUrl: string;
spEntityId: string;
spACSUrl: string;
spCertificate: string;
userMapping: UserMapping;
groupsMapping: GroupsMapping[];
redirectUrl: string;
domains: string[];
domain: string;
};
declare type SSOSAMLSettingsResponse = {
idpEntityId: string;
idpSSOUrl: string;
idpCertificate: string;
idpMetadataUrl: string;
spEntityId: string;
spACSUrl: string;
spCertificate: string;
attributeMapping: AttributeMapping;
groupsMapping: RoleMappings;
redirectUrl: string;
};
declare type SSOSettings = {
tenant: Tenant;
saml?: SSOSAMLSettingsResponse;
oidc?: SSOOIDCSettings;
};
declare type OIDCAttributeMapping = {
loginId?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
email?: string;
verifiedEmail?: string;
username?: string;
phoneNumber?: string;
verifiedPhone?: string;
picture?: string;
};
declare type Prompt = 'none' | 'login' | 'consent' | 'select_account';
declare type SSOOIDCSettings = {
name: string;
clientId: string;
clientSecret?: string;
redirectUrl?: string;
authUrl?: string;
tokenUrl?: string;
userDataUrl?: string;
scope?: string[];
JWKsUrl?: string;
attributeMapping?: OIDCAttributeMapping;
manageProviderTokens?: boolean;
callbackDomain?: string;
prompt?: Prompt[];
grantType?: 'authorization_code' | 'implicit';
issuer?: string;
};
declare type SSOSAMLSettings = {
idpUrl: string;
idpCert: string;
entityId: string;
roleMappings?: RoleMappings;
attributeMapping?: AttributeMapping;
};
declare type SSOSAMLByMetadataSettings = {
idpMetadataUrl: string;
roleMappings?: RoleMappings;
attributeMapping?: AttributeMapping;
};
declare type ProviderTokenResponse = {
provider: string;
providerUserId: string;
accessToken: string;
expiration: number;
scopes: string[];
};
declare type UserFailedResponse = {
failure: string;
user: UserResponse;
};
declare type InviteBatchResponse = {
createdUsers: UserResponse[];
failedUsers: UserFailedResponse[];
};
/**
* Search options to filter which audit records we should retrieve.
* All parameters are optional. `From` is currently limited to 30 days.
*/
declare type AuditSearchOptions = {
userIds?: string[];
actions?: string[];
excludedActions?: string[];
devices?: string[];
methods?: string[];
geos?: string[];
remoteAddresses?: string[];
loginIds?: string[];
tenants?: string[];
noTenants?: boolean;
text?: string;
from?: number;
to?: number;
};
declare type AuditType = 'info' | 'warn' | 'error';
/** Audit create options for creating audit event */
declare type AuditCreateOptions = {
userId?: string;
action: string;
type: AuditType;
actorId: string;
tenantId: string;
data?: Record<string, any>;
};
/** Audit record response from the audit trail. Occurred is in milliseconds. */
declare type AuditRecord = {
projectId: string;
userId: string;
action: string;
occurred: number;
device: string;
method: string;
geo: string;
remoteAddress: string;
loginIds: string[];
tenants: string[];
data: Record<string, any>;
};
declare type UserStatus = 'enabled' | 'disabled' | 'invited';
declare type AuthzNodeExpressionType = 'self' | 'targetSet' | 'relationLeft' | 'relationRight';
/**
* AuthzNodeExpression holds the definition of a child node
*/
declare type AuthzNodeExpression = {
neType: AuthzNodeExpressionType;
relationDefinition?: string;
relationDefinitionNamespace?: string;
targetRelationDefinition?: string;
targetRelationDefinitionNamespace?: string;
};
declare type AuthzNodeType = 'child' | 'union' | 'intersect' | 'sub';
/**
* AuthzNode holds the definition of a complex relation definition
*/
declare type AuthzNode = {
nType: AuthzNodeType;
children?: AuthzNode[];
expression?: AuthzNodeExpression;
};
/**
* AuthzRelationDefinition defines a relation within a namespace
*/
declare type AuthzRelationDefinition = {
name: string;
complexDefinition?: AuthzNode;
};
/**
* AuthzNamespace defines an entity in the authorization schema
*/
declare type AuthzNamespace = {
name: string;
relationDefinitions: AuthzRelationDefinition[];
};
/**
* AuthzSchema holds the full schema (all namespaces) for a project
*/
declare type AuthzSchema = {
name?: string;
namespaces: AuthzNamespace[];
};
/**
* AuthzUserQuery represents a target of a relation for ABAC (query on users)
*/
declare type AuthzUserQuery = {
tenants?: string[];
roles?: string[];
text?: string;
statuses?: UserStatus[];
ssoOnly?: boolean;
withTestUser?: boolean;
customAttributes?: Record<string, any>;
};
/**
* AuthzRelation defines a relation between resource and target
*/
declare type AuthzRelation = {
resource: string;
relationDefinition: string;
namespace: string;
target?: string;
targetSetResource?: string;
targetSetRelationDefinition?: string;
targetSetRelationDefinitionNamespace?: string;
query?: AuthzUserQuery;
};
/**
* AuthzRelationQuery queries the service if a given relation exists
*/
declare type AuthzRelationQuery = {
resource: string;
relationDefinition: string;
namespace: string;
target: string;
hasRelation?: boolean;
};
/**
* AuthzModified has the list of resources and targets that were modified since given time returned from GetModified
*/
declare type AuthzModified = {
resources: string[];
targets: string[];
schemaChanged: boolean;
};
declare type CloneProjectResponse = {
projectId: string;
projectName: string;
tag?: string;
};
/** Parsed JWT token */
interface Token {
sub?: string;
exp?: number;
iss?: string;
[claim: string]: unknown;
interface UserOptions {
email?: string;
phone?: string;
displayName?: string;
roles?: string[];
userTenants?: AssociatedTenant[];
customAttributes?: Record<string, AttributesTypes>;
picture?: string;
verifiedEmail?: boolean;
verifiedPhone?: boolean;
givenName?: string;
middleName?: string;
familyName?: string;
additionalLoginIds?: string[];
ssoAppIds?: string[];
}
/** All information regarding token including the raw JWT, parsed JWT and cookies */
interface AuthenticationInfo {
jwt: string;
token: Token;
cookies?: string[];
}
/** Common Error Codes */
declare const descopeErrors: {
badRequest: string;
missingArguments: string;
invalidRequest: string;
invalidArguments: string;
wrongOTPCode: string;
tooManyOTPAttempts: string;
enchantedLinkPending: string;
userNotFound: string;
};
/** Configuration arguments which include the Descope core SDK args and an optional management key */
declare type NodeSdkArgs = Parameters<typeof _descope_core_js_sdk__default>[0] & {
managementKey?: string;
publicKey?: string;
};
declare const nodeSdk: {
({ managementKey, ...config }: NodeSdkArgs): {
({ managementKey, publicKey, ...config }: NodeSdkArgs): {
management: {
user: {
create: (loginId: string, email?: string, phone?: string, displayName?: string, roles?: string[], userTenants?: AssociatedTenant[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
invite: (loginId: string, email?: string, phone?: string, displayName?: string, roles?: string[], userTenants?: AssociatedTenant[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
update: (loginId: string, email?: string, phone?: string, displayName?: string, roles?: string[], userTenants?: AssociatedTenant[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
create: {
(loginId: string, options?: UserOptions): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
(loginId: string, email?: string, phone?: string, displayName?: string, roles?: string[], userTenants?: AssociatedTenant[], customAttributes?: Record<string, AttributesTypes>, picture?: string, verifiedEmail?: boolean, verifiedPhone?: boolean, givenName?: string, middleName?: string, familyName?: string, additionalLoginIds?: string[]): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
};
createTestUser: {
(loginId: string, options?: UserOptions): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
(loginId: string, email?: string, phone?: string, displayName?: string, roles?: string[], userTenants?: AssociatedTenant[], customAttributes?: Record<string, AttributesTypes>, picture?: string, verifiedEmail?: boolean, verifiedPhone?: boolean, givenName?: string, middleName?: string, familyName?: string, additionalLoginIds?: string[]): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
};
invite: {
(loginId: string, options?: UserOptions & {
inviteUrl?: string;
sendMail?: boolean;
sendSMS?: boolean;
templateOptions?: TemplateOptions;
}): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
(loginId: string, email?: string, phone?: string, displayName?: string, roles?: string[], userTenants?: AssociatedTenant[], customAttributes?: Record<string, AttributesTypes>, picture?: string, verifiedEmail?: boolean, verifiedPhone?: boolean, inviteUrl?: string, sendMail?: boolean, sendSMS?: boolean, givenName?: string, middleName?: string, familyName?: string, additionalLoginIds?: string[]): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
};
inviteBatch: (users: User[], inviteUrl?: string, sendMail?: boolean, sendSMS?: boolean, templateOptions?: TemplateOptions) => Promise<SdkResponse<InviteBatchResponse>>;
update: {
(loginId: string, options?: UserOptions): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
(loginId: string, email?: string, phone?: string, displayName?: string, roles?: string[], userTenants?: AssociatedTenant[], customAttributes?: Record<string, AttributesTypes>, picture?: string, verifiedEmail?: boolean, verifiedPhone?: boolean, givenName?: string, middleName?: string, familyName?: string, additionalLoginIds?: string[]): Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
};
delete: (loginId: string) => Promise<SdkResponse<never>>;
deleteByUserId: (userId: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
deleteAllTestUsers: () => Promise<SdkResponse<never>>;
load: (loginId: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
loadByUserId: (userId: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
searchAll: (tenantIds?: string[], roles?: string[], limit?: number, page?: number) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse[]>>;
logoutUser: (loginId: string) => Promise<SdkResponse<never>>;
logoutUserByUserId: (userId: string) => Promise<SdkResponse<never>>;
searchAll: (tenantIds?: string[], roles?: string[], limit?: number, page?: number, testUsersOnly?: boolean, withTestUser?: boolean, customAttributes?: Record<string, AttributesTypes>, statuses?: UserStatus[], emails?: string[], phones?: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse[]>>;
search: (searchReq: {
page?: number;
limit?: number;
sort?: {
field: string;
desc?: boolean;
}[];
text?: string;
emails?: string[];
phones?: string[];
statuses?: UserStatus[];
roles?: string[];
tenantIds?: string[];
customAttributes?: Record<string, AttributesTypes>;
withTestUser?: boolean;
testUsersOnly?: boolean;
ssoAppIds?: string[];
}) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse[]>>;
getProviderToken: (loginId: string, provider: string) => Promise<SdkResponse<ProviderTokenResponse>>;
activate: (loginId: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
deactivate: (loginId: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
updateLoginId: (loginId: string, newLoginId?: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
updateEmail: (loginId: string, email: string, isVerified: boolean) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
updatePhone: (loginId: string, phone: string, isVerified: boolean) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
updateDisplayName: (loginId: string, displayName: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
updateDisplayName: (loginId: string, displayName?: string, givenName?: string, middleName?: string, familyName?: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
updatePicture: (loginId: string, picture: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
updateCustomAttribute: (loginId: string, attributeKey: string, attributeValue: AttributesTypes) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
setRoles: (loginId: string, roles: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
addRoles: (loginId: string, roles: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;

@@ -132,7 +695,27 @@ removeRoles: (loginId: string, roles: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;

removeTenant: (loginId: string, tenantId: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
setTenantRoles: (loginId: string, tenantId: string, roles: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
addTenantRoles: (loginId: string, tenantId: string, roles: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
removeTenantRoles: (loginId: string, tenantId: string, roles: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
addSSOapps: (loginId: string, ssoAppIds: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
setSSOapps: (loginId: string, ssoAppIds: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
removeSSOapps: (loginId: string, ssoAppIds: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
generateOTPForTestUser: (deliveryMethod: DeliveryMethodForTestUser, loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions) => Promise<SdkResponse<GenerateOTPForTestResponse>>;
generateMagicLinkForTestUser: (deliveryMethod: DeliveryMethodForTestUser, loginId: string, uri: string, loginOptions?: _descope_core_js_sdk.LoginOptions) => Promise<SdkResponse<GenerateMagicLinkForTestResponse>>;
generateEnchantedLinkForTestUser: (loginId: string, uri: string, loginOptions?: _descope_core_js_sdk.LoginOptions) => Promise<SdkResponse<GenerateEnchantedLinkForTestResponse>>;
generateEmbeddedLink: (loginId: string, customClaims?: Record<string, any>) => Promise<SdkResponse<GenerateEmbeddedLinkResponse>>;
setTemporaryPassword: (loginId: string, password: string) => Promise<SdkResponse<never>>;
setActivePassword: (loginId: string, password: string) => Promise<SdkResponse<never>>;
setPassword: (loginId: string, password: string) => Promise<SdkResponse<never>>;
expirePassword: (loginId: string) => Promise<SdkResponse<never>>;
removeAllPasskeys: (loginId: string) => Promise<SdkResponse<never>>;
history: (userIds: string[]) => Promise<SdkResponse<_descope_core_js_sdk.UserHistoryResponse[]>>;
};
project: {
updateName: (name: string) => Promise<SdkResponse<never>>;
clone: (name: string, tag?: "production") => Promise<SdkResponse<CloneProjectResponse>>;
export: () => Promise<SdkResponse<Record<string, any>>>;
import: (files: Record<string, any>) => Promise<SdkResponse<never>>;
};
accessKey: {
create: (name: string, expireTime: number, roles?: string[], keyTenants?: AssociatedTenant[]) => Promise<SdkResponse<CreatedAccessKeyResponse>>;
create: (name: string, expireTime: number, roles?: string[], keyTenants?: AssociatedTenant[], userId?: string, customClaims?: Record<string, any>) => Promise<SdkResponse<CreatedAccessKeyResponse>>;
load: (id: string) => Promise<SdkResponse<AccessKey>>;

@@ -146,15 +729,39 @@ searchAll: (tenantIds?: string[]) => Promise<SdkResponse<AccessKey[]>>;

tenant: {
create: (name: string, selfProvisioningDomains?: string[]) => Promise<SdkResponse<CreateTenantResponse>>;
createWithId: (id: string, name: string, selfProvisioningDomains?: string[]) => Promise<SdkResponse<never>>;
update: (id: string, name: string, selfProvisioningDomains?: string[]) => Promise<SdkResponse<never>>;
delete: (id: string) => Promise<SdkResponse<never>>;
create: (name: string, selfProvisioningDomains?: string[], customAttributes?: Record<string, AttributesTypes>) => Promise<SdkResponse<CreateTenantResponse>>;
createWithId: (id: string, name: string, selfProvisioningDomains?: string[], customAttributes?: Record<string, AttributesTypes>) => Promise<SdkResponse<never>>;
update: (id: string, name: string, selfProvisioningDomains?: string[], customAttributes?: Record<string, AttributesTypes>) => Promise<SdkResponse<never>>;
delete: (id: string, cascade?: boolean) => Promise<SdkResponse<never>>;
load: (id: string) => Promise<SdkResponse<Tenant>>;
loadAll: () => Promise<SdkResponse<Tenant[]>>;
searchAll: (ids?: string[], names?: string[], selfProvisioningDomains?: string[], customAttributes?: Record<string, AttributesTypes>) => Promise<SdkResponse<Tenant[]>>;
getSettings: (tenantId: string) => Promise<SdkResponse<TenantSettings>>;
configureSettings: (tenantId: string, settings: TenantSettings) => Promise<SdkResponse<never>>;
};
ssoApplication: {
createOidcApplication: (options: OidcApplicationOptions) => Promise<SdkResponse<CreateSSOApplicationResponse>>;
createSamlApplication: (options: SamlApplicationOptions) => Promise<SdkResponse<CreateSSOApplicationResponse>>;
updateOidcApplication: (options: OidcApplicationOptions & {
id: string;
}) => Promise<SdkResponse<never>>;
updateSamlApplication: (options: SamlApplicationOptions & {
id: string;
}) => Promise<SdkResponse<never>>;
delete: (id: string) => Promise<SdkResponse<never>>;
load: (id: string) => Promise<SdkResponse<SSOApplication>>;
loadAll: () => Promise<SdkResponse<SSOApplication[]>>;
};
sso: {
configureSettings: (tenantId: string, idpURL: string, idpCert: string, entityId: string, redirectURL?: string, domain?: string) => Promise<SdkResponse<never>>;
configureMetadata: (tenantId: string, idpMetadataURL: string) => Promise<SdkResponse<never>>;
configureMapping: (tenantId: string, roleMapping?: RoleMapping, attributeMapping?: AttributeMapping) => Promise<SdkResponse<never>>;
getSettings: (tenantId: string) => Promise<SdkResponse<SSOSettingsResponse>>;
deleteSettings: (tenantId: string) => Promise<SdkResponse<never>>;
configureSettings: (tenantId: string, idpURL: string, idpCert: string, entityId: string, redirectURL: string, domains: string[]) => Promise<SdkResponse<never>>;
configureMetadata: (tenantId: string, idpMetadataURL: string, redirectURL: string, domains: string[]) => Promise<SdkResponse<never>>;
configureMapping: (tenantId: string, roleMappings?: RoleMappings, attributeMapping?: AttributeMapping) => Promise<SdkResponse<never>>;
configureOIDCSettings: (tenantId: string, settings: SSOOIDCSettings, domains?: string[]) => Promise<SdkResponse<never>>;
configureSAMLSettings: (tenantId: string, settings: SSOSAMLSettings, redirectUrl?: string, domains?: string[]) => Promise<SdkResponse<never>>;
configureSAMLByMetadata: (tenantId: string, settings: SSOSAMLByMetadataSettings, redirectUrl?: string, domains?: string[]) => Promise<SdkResponse<never>>;
loadSettings: (tenantId: string) => Promise<SdkResponse<SSOSettings>>;
};
jwt: {
update: (jwt: string, customClaims?: Record<string, any>) => Promise<SdkResponse<UpdateJWTResponse>>;
impersonate: (impersonatorId: string, loginId: string, validateConsent: boolean) => Promise<SdkResponse<UpdateJWTResponse>>;
};

@@ -167,7 +774,12 @@ permission: {

};
password: {
getSettings: (tenantId: string) => Promise<SdkResponse<PasswordSettings>>;
configureSettings: (tenantId: string, settings: PasswordSettings) => Promise<SdkResponse<never>>;
};
role: {
create: (name: string, description?: string, permissionNames?: string[]) => Promise<SdkResponse<never>>;
update: (name: string, newName: string, description?: string, permissionNames?: string[]) => Promise<SdkResponse<never>>;
delete: (name: string) => Promise<SdkResponse<never>>;
create: (name: string, description?: string, permissionNames?: string[], tenantId?: string) => Promise<SdkResponse<never>>;
update: (name: string, newName: string, description?: string, permissionNames?: string[], tenantId?: string) => Promise<SdkResponse<never>>;
delete: (name: string, tenantId?: string) => Promise<SdkResponse<never>>;
loadAll: () => Promise<SdkResponse<Role[]>>;
search: (options: RoleSearchOptions) => Promise<SdkResponse<Role[]>>;
};

@@ -179,2 +791,34 @@ group: {

};
flow: {
list: () => Promise<SdkResponse<FlowsResponse>>;
delete: (flowIds: string[]) => Promise<SdkResponse<never>>;
export: (flowId: string) => Promise<SdkResponse<FlowResponse>>;
import: (flowId: string, flow: Flow, screens?: Screen[]) => Promise<SdkResponse<FlowResponse>>;
};
theme: {
export: () => Promise<SdkResponse<ThemeResponse>>;
import: (theme: Theme) => Promise<SdkResponse<ThemeResponse>>;
};
audit: {
search: (searchOptions: AuditSearchOptions) => Promise<SdkResponse<AuditRecord[]>>;
createEvent: (createOptions: AuditCreateOptions) => Promise<SdkResponse<never>>;
};
authz: {
saveSchema: (schema: AuthzSchema, upgrade: boolean) => Promise<SdkResponse<never>>;
deleteSchema: () => Promise<SdkResponse<never>>;
loadSchema: () => Promise<SdkResponse<AuthzSchema>>;
saveNamespace: (namespace: AuthzNamespace, oldName?: string, schemaName?: string) => Promise<SdkResponse<never>>;
deleteNamespace: (name: string, schemaName?: string) => Promise<SdkResponse<never>>;
saveRelationDefinition: (relationDefinition: AuthzRelationDefinition, namespace: string, oldName?: string, schemaName?: string) => Promise<SdkResponse<never>>;
deleteRelationDefinition: (name: string, namespace: string, schemaName?: string) => Promise<SdkResponse<never>>;
createRelations: (relations: AuthzRelation[]) => Promise<SdkResponse<never>>;
deleteRelations: (relations: AuthzRelation[]) => Promise<SdkResponse<never>>;
deleteRelationsForResources: (resources: string[]) => Promise<SdkResponse<never>>;
hasRelations: (relationQueries: AuthzRelationQuery[]) => Promise<SdkResponse<AuthzRelationQuery[]>>;
whoCanAccess: (resource: string, relationDefinition: string, namespace: string) => Promise<SdkResponse<string[]>>;
resourceRelations: (resource: string) => Promise<SdkResponse<AuthzRelation[]>>;
targetsRelations: (targets: string[]) => Promise<SdkResponse<AuthzRelation[]>>;
whatCanTargetAccess: (target: string) => Promise<SdkResponse<AuthzRelation[]>>;
getModified: (since: Date) => Promise<SdkResponse<AuthzModified>>;
};
};

@@ -186,17 +830,21 @@ getKey: (header: JWTHeaderParameters) => Promise<KeyLike | Uint8Array>;

validateAndRefreshSession: (sessionToken?: string, refreshToken?: string) => Promise<AuthenticationInfo>;
exchangeAccessKey: (accessKey: string) => Promise<AuthenticationInfo>;
exchangeAccessKey: (accessKey: string, loginOptions?: AccessKeyLoginOptions) => Promise<AuthenticationInfo>;
validatePermissions: (authInfo: AuthenticationInfo, permissions: string[]) => boolean;
getMatchedPermissions: (authInfo: AuthenticationInfo, permissions: string[]) => string[];
validateTenantPermissions: (authInfo: AuthenticationInfo, tenant: string, permissions: string[]) => boolean;
getMatchedTenantPermissions: (authInfo: AuthenticationInfo, tenant: string, permissions: string[]) => string[];
validateRoles: (authInfo: AuthenticationInfo, roles: string[]) => boolean;
getMatchedRoles: (authInfo: AuthenticationInfo, roles: string[]) => string[];
validateTenantRoles: (authInfo: AuthenticationInfo, tenant: string, roles: string[]) => boolean;
getMatchedTenantRoles: (authInfo: AuthenticationInfo, tenant: string, roles: string[]) => string[];
accessKey: {
exchange: (accessKey: string) => Promise<SdkResponse<ExchangeAccessKeyResponse>>;
exchange: (accessKey: string, loginOptions?: AccessKeyLoginOptions) => Promise<SdkResponse<ExchangeAccessKeyResponse>>;
};
otp: {
verify: {
email: (loginId: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {
sms: (loginId: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {
refreshJwt?: string;
cookies?: string[];
}>>;
sms: (loginId: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {
voice: (loginId: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {
refreshJwt?: string;

@@ -209,36 +857,135 @@ cookies?: string[];

}>>;
email: (loginId: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {
refreshJwt?: string;
cookies?: string[];
}>>;
};
signIn: {
email: (loginId: string) => Promise<SdkResponse<never>>;
sms: (loginId: string) => Promise<SdkResponse<never>>;
whatsapp: (loginId: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
email: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
};
signUp: {
email: (loginId: string, user?: {
sms: (loginId: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<never>>;
sms: (loginId: string, user?: {
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: (loginId: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<never>>;
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: (loginId: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<never>>;
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
email: (loginId: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
};
signUpOrIn: {
email: (loginId: string) => Promise<SdkResponse<never>>;
sms: (loginId: string) => Promise<SdkResponse<never>>;
whatsapp: (loginId: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
email: (loginId: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
};
update: {
email: (loginId: string, email: string, token?: string) => Promise<SdkResponse<never>>;
email: <T extends boolean>(loginId: string, email: string, token?: string, updateOptions?: {
addToLoginIDs?: T;
onMergeUseExisting?: T extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
phone: {
email: (loginId: string, phone: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, phone: string) => Promise<SdkResponse<never>>;
whatsapp: (loginId: string, phone: string) => Promise<SdkResponse<never>>;
sms: <T_1 extends boolean>(loginId: string, phone: string, token?: string, updateOptions?: {
addToLoginIDs?: T_1;
onMergeUseExisting?: T_1 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: <T_1 extends boolean>(loginId: string, phone: string, token?: string, updateOptions?: {
addToLoginIDs?: T_1;
onMergeUseExisting?: T_1 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: <T_1 extends boolean>(loginId: string, phone: string, token?: string, updateOptions?: {
addToLoginIDs?: T_1;
onMergeUseExisting?: T_1 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
};

@@ -253,34 +1000,149 @@ };

signIn: {
email: (loginId: string, uri: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, uri: string) => Promise<SdkResponse<never>>;
whatsapp: (loginId: string, uri: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, URI: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: (loginId: string, URI: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: (loginId: string, URI: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
email: (loginId: string, URI: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
};
signUp: {
email: (loginId: string, uri: string, user?: {
sms: (loginId: string, URI: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<never>>;
sms: (loginId: string, uri: string, user?: {
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: (loginId: string, URI: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<never>>;
whatsapp: (loginId: string, uri: string, user?: {
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: (loginId: string, URI: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<never>>;
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
email: (loginId: string, URI: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
};
signUpOrIn: {
email: (loginId: string, uri: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, uri: string) => Promise<SdkResponse<never>>;
whatsapp: (loginId: string, uri: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, URI?: string, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: (loginId: string, URI?: string, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: (loginId: string, URI?: string, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
email: (loginId: string, URI?: string, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
};
update: {
email: (loginId: string, email: string, URI?: string, token?: string) => Promise<SdkResponse<never>>;
email: <T_2 extends boolean>(loginId: string, email: string, URI?: string, token?: string, updateOptions?: {
addToLoginIDs?: T_2;
onMergeUseExisting?: T_2 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedEmail: string;
}>>;
phone: {
email: (loginId: string, phone: string) => Promise<SdkResponse<never>>;
sms: (loginId: string, phone: string) => Promise<SdkResponse<never>>;
whatsapp: (loginId: string, phone: string) => Promise<SdkResponse<never>>;
sms: <T_3 extends boolean>(loginId: string, phone: string, URI?: string, token?: string, updateOptions?: {
addToLoginIDs?: T_3;
onMergeUseExisting?: T_3 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
voice: <T_3 extends boolean>(loginId: string, phone: string, URI?: string, token?: string, updateOptions?: {
addToLoginIDs?: T_3;
onMergeUseExisting?: T_3 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
whatsapp: <T_3 extends boolean>(loginId: string, phone: string, URI?: string, token?: string, updateOptions?: {
addToLoginIDs?: T_3;
onMergeUseExisting?: T_3 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<{
maskedPhone: string;
}>>;
};

@@ -291,11 +1153,24 @@ };

verify: (token: string) => Promise<SdkResponse<never>>;
signIn: (loginId: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse & {
signIn: (loginId: string, URI?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse & {
refreshJwt?: string;
cookies?: string[];
}>>;
signUpOrIn: (loginId: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse>>;
signUp: (loginId: string, uri: string, user?: {
signUpOrIn: (loginId: string, URI?: string, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse>>;
signUp: (loginId: string, URI?: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}, signUpOptions?: {
customClaims?: Record<string, any>;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse & {

@@ -310,47 +1185,22 @@ refreshJwt?: string;

update: {
email: (loginId: string, email: string, URI?: string, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse>>;
email: <T_4 extends boolean>(loginId: string, email: string, URI?: string, token?: string, updateOptions?: {
addToLoginIDs?: T_4;
onMergeUseExisting?: T_4 extends true ? boolean : never;
templateOptions?: {
[x: string]: string;
};
}) => Promise<SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse>>;
};
};
oauth: {
start: {
facebook: <B extends {
redirect: boolean;
}>(redirectURL?: string, config?: B) => Promise<B extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
github: <B_1 extends {
redirect: boolean;
}>(redirectURL?: string, config?: B_1) => Promise<B_1 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
google: <B_2 extends {
redirect: boolean;
}>(redirectURL?: string, config?: B_2) => Promise<B_2 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
microsoft: <B_3 extends {
redirect: boolean;
}>(redirectURL?: string, config?: B_3) => Promise<B_3 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
gitlab: <B_4 extends {
redirect: boolean;
}>(redirectURL?: string, config?: B_4) => Promise<B_4 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
apple: <B_5 extends {
redirect: boolean;
}>(redirectURL?: string, config?: B_5) => Promise<B_5 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
discord: <B_6 extends {
redirect: boolean;
}>(redirectURL?: string, config?: B_6) => Promise<B_6 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
linkedin: <B_7 extends {
redirect: boolean;
}>(redirectURL?: string, config?: B_7) => Promise<B_7 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
start: ((provider: string, redirectUrl?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>) & {
facebook: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
github: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
google: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
microsoft: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
gitlab: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
apple: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
discord: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
linkedin: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
slack: (redirectURL?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
};

@@ -361,9 +1211,7 @@ exchange: (code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {

}>>;
startNative: (provider: string, loginOptions?: _descope_core_js_sdk.LoginOptions) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
finishNative: (provider: string, stateId: string, user?: string, code?: string, idToken?: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
};
saml: {
start: <B_1 extends {
redirect: boolean;
}>(tenantNameOrEmail: string, config?: B_1) => Promise<B_1 extends {
redirect: true;
} ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
start: (tenantIdOrEmail: string, redirectUrl?: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.URLResponse>>;
exchange: (code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {

@@ -378,9 +1226,8 @@ refreshJwt?: string;

name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
verify: (loginId: string, code: string, loginOptions?: {
stepup?: boolean;
mfa?: boolean;
customClaims?: Record<string, any>;
}, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {
verify: (loginId: string, code: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse & {
refreshJwt?: string;

@@ -404,7 +1251,3 @@ cookies?: string[];

signIn: {
start: (loginId: string, origin: string, loginOptions?: {
stepup?: boolean;
mfa?: boolean;
customClaims?: Record<string, any>;
}, token?: string) => Promise<SdkResponse<{
start: (loginId: string, origin: string, loginOptions?: _descope_core_js_sdk.LoginOptions, token?: string) => Promise<SdkResponse<{
transactionId: string;

@@ -435,5 +1278,34 @@ options: string;

};
password: {
signUp: (loginId: string, password: string, user?: {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
signIn: (loginId: string, password: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
sendReset: (loginId: string, redirectUrl?: string, templateOptions?: {
[x: string]: string;
}) => Promise<SdkResponse<{
resetMethod: string;
pendingRef?: string;
linkId?: string;
maskedEmail: string;
}>>;
update: (loginId: string, newPassword: string, token?: string) => Promise<SdkResponse<never>>;
replace: (loginId: string, oldPassword: string, newPassword: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
policy: () => Promise<SdkResponse<{
minLength: number;
lowercase: boolean;
uppercase: boolean;
number: boolean;
nonAlphanumeric: boolean;
}>>;
};
flow: {
start: (flowId: string, options?: {
redirectUrl?: string;
location?: string;
tenant?: string;

@@ -444,3 +1316,3 @@ deviceInfo?: {

lastAuth?: {
authMethod?: "otp" | "oauth" | "saml" | "totp" | "webauthn" | "magiclink" | "enchantedlink";
authMethod?: "saml" | "otp" | "oauth" | "totp" | "webauthn" | "magiclink" | "enchantedlink";
oauthProvider?: string;

@@ -450,6 +1322,19 @@ name?: string;

};
}, conditionInteractionId?: string, interactionId?: string, input?: {
redirectAuth?: {
callbackUrl: string;
codeChallenge: string;
};
oidcIdpStateId?: string;
preview?: boolean;
samlIdpStateId?: string;
samlIdpUsername?: string;
ssoAppId?: string;
oidcLoginHint?: string;
abTestingKey?: number;
startOptionsVersion?: number;
client?: Record<string, any>;
}, conditionInteractionId?: string, interactionId?: string, version?: number, componentsVersion?: string, input?: {
[x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any)[])[])[])[])[])[])[])[])[])[])[];
}) => Promise<SdkResponse<_descope_core_js_sdk.FlowResponse>>;
next: (executionId: string, stepId: string, interactionId: string, input?: {
next: (executionId: string, stepId: string, interactionId: string, version?: number, componentsVersion?: string, input?: {
[x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any)[])[])[])[])[])[])[])[])[])[])[];

@@ -462,6 +1347,9 @@ }) => Promise<SdkResponse<_descope_core_js_sdk.FlowResponse>>;

}>>;
selectTenant: (tenantId: string, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
logout: (token?: string) => Promise<SdkResponse<never>>;
logoutAll: (token?: string) => Promise<SdkResponse<never>>;
me: (token?: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
history: (token?: string) => Promise<SdkResponse<_descope_core_js_sdk.UserHistoryResponse>>;
isJwtExpired: (token: string) => boolean;
getTenants: (token: string) => string[];
getJwtPermissions: (token: string, tenant?: string) => string[];

@@ -491,3 +1379,3 @@ getJwtRoles: (token: string, tenant?: string) => string[];

}) => Promise<Response>;
delete: (path: string, body?: any, config?: {
delete: (path: string, config?: {
headers?: HeadersInit;

@@ -525,2 +1413,2 @@ queryParams?: {

export { nodeSdk as default };
export { AuthenticationInfo, nodeSdk as default, descopeErrors };

@@ -1,2 +0,2 @@

import{__rest as e}from"tslib";import t,{transformResponse as a,wrapWith as n}from"@descope/core-js-sdk";import{jwtVerify as s,errors as o,importJWK as r}from"jose";import i,{Headers as l}from"node-fetch-commonjs";const d=t=>async(...a)=>{var n,s,o;const r=await t(...a);if(!r.data)return r;let i=r.data,{refreshJwt:l}=i,d=e(i,["refreshJwt"]);const p=[];var m;return l?p.push(`${"DSR"}=${l}; Domain=${(null==(m=d)?void 0:m.cookieDomain)||""}; Max-Age=${(null==m?void 0:m.cookieMaxAge)||""}; Path=${(null==m?void 0:m.cookiePath)||"/"}; HttpOnly; SameSite=Strict`):(null===(n=r.response)||void 0===n?void 0:n.headers.get("set-cookie"))&&(l=((e,t)=>{const a=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return a?a[1]:null})(null===(s=r.response)||void 0===s?void 0:s.headers.get("set-cookie"),"DSR"),p.push(null===(o=r.response)||void 0===o?void 0:o.headers.get("set-cookie"))),Object.assign(Object.assign({},r),{data:Object.assign(Object.assign({},r.data),{refreshJwt:l,cookies:p})})};function p(e,t,a){var n,s;const o=a?null===(s=null===(n=e.token.tenants)||void 0===n?void 0:n[a])||void 0===s?void 0:s[t]:e.token[t];return Array.isArray(o)?o:[]}var m={create:"/v1/mgmt/user/create",update:"/v1/mgmt/user/update",delete:"/v1/mgmt/user/delete",load:"/v1/mgmt/user",search:"/v1/mgmt/user/search",updateStatus:"/v1/mgmt/user/update/status",updateEmail:"/v1/mgmt/user/update/email",updatePhone:"/v1/mgmt/user/update/phone",updateDisplayName:"/v1/mgmt/user/update/name",addRole:"/v1/mgmt/user/update/role/add",removeRole:"/v1/mgmt/user/update/role/remove",addTenant:"/v1/mgmt/user/update/tenant/add",removeTenant:"/v1/mgmt/user/update/tenant/remove"},c={create:"/v1/mgmt/accesskey/create",load:"/v1/mgmt/accesskey",search:"/v1/mgmt/accesskey/search",update:"/v1/mgmt/accesskey/update",deactivate:"/v1/mgmt/accesskey/deactivate",activate:"/v1/mgmt/accesskey/activate",delete:"/v1/mgmt/accesskey/delete"},u={create:"/v1/mgmt/tenant/create",update:"/v1/mgmt/tenant/update",delete:"/v1/mgmt/tenant/delete",loadAll:"/v1/mgmt/tenant/all"},h={configure:"/v1/mgmt/sso/settings",metadata:"/v1/mgmt/sso/metadata",mapping:"/v1/mgmt/sso/mapping"},g={update:"/v1/mgmt/jwt/update"},v={create:"/v1/mgmt/permission/create",update:"/v1/mgmt/permission/update",delete:"/v1/mgmt/permission/delete",loadAll:"/v1/mgmt/permission/all"},k={create:"/v1/mgmt/role/create",update:"/v1/mgmt/role/update",delete:"/v1/mgmt/role/delete",loadAll:"/v1/mgmt/role/all"},y={loadAllGroups:"/v1/mgmt/group/all",loadAllGroupsForMember:"/v1/mgmt/group/member/all",loadAllGroupMembers:"/v1/mgmt/group/members"};const f=(e,t)=>({create:(n,s,o,r,i,l)=>a(e.httpClient.post(m.create,{loginId:n,email:s,phone:o,displayName:r,roleNames:i,userTenants:l},{token:t}),(e=>e.user)),invite:(n,s,o,r,i,l)=>a(e.httpClient.post(m.create,{loginId:n,email:s,phone:o,displayName:r,roleNames:i,userTenants:l,invite:!0},{token:t}),(e=>e.user)),update:(n,s,o,r,i,l)=>a(e.httpClient.post(m.update,{loginId:n,email:s,phone:o,displayName:r,roleNames:i,userTenants:l},{token:t}),(e=>e.user)),delete:n=>a(e.httpClient.post(m.delete,{loginId:n},{token:t})),load:n=>a(e.httpClient.get(m.load,{queryParams:{loginId:n},token:t}),(e=>e.user)),loadByUserId:n=>a(e.httpClient.get(m.load,{queryParams:{userId:n},token:t}),(e=>e.user)),searchAll:(n,s,o,r)=>a(e.httpClient.post(m.search,{tenantIds:n,roleNames:s,limit:o,page:r},{token:t}),(e=>e.users)),activate:n=>a(e.httpClient.post(m.updateStatus,{loginId:n,status:"enabled"},{token:t}),(e=>e.user)),deactivate:n=>a(e.httpClient.post(m.updateStatus,{loginId:n,status:"disabled"},{token:t}),(e=>e.user)),updateEmail:(n,s,o)=>a(e.httpClient.post(m.updateEmail,{loginId:n,email:s,verified:o},{token:t}),(e=>e.user)),updatePhone:(n,s,o)=>a(e.httpClient.post(m.updatePhone,{loginId:n,phone:s,verified:o},{token:t}),(e=>e.user)),updateDisplayName:(n,s)=>a(e.httpClient.post(m.updateDisplayName,{loginId:n,displayName:s},{token:t}),(e=>e.user)),addRoles:(n,s)=>a(e.httpClient.post(m.addRole,{loginId:n,roleNames:s},{token:t}),(e=>e.user)),removeRoles:(n,s)=>a(e.httpClient.post(m.removeRole,{loginId:n,roleNames:s},{token:t}),(e=>e.user)),addTenant:(n,s)=>a(e.httpClient.post(m.addTenant,{loginId:n,tenantId:s},{token:t}),(e=>e.user)),removeTenant:(n,s)=>a(e.httpClient.post(m.removeTenant,{loginId:n,tenantId:s},{token:t}),(e=>e.user)),addTenantRoles:(n,s,o)=>a(e.httpClient.post(m.addRole,{loginId:n,tenantId:s,roleNames:o},{token:t}),(e=>e.user)),removeTenantRoles:(n,s,o)=>a(e.httpClient.post(m.removeRole,{loginId:n,tenantId:s,roleNames:o},{token:t}),(e=>e.user))}),C=(e,t)=>({create:(n,s)=>a(e.httpClient.post(u.create,{name:n,selfProvisioningDomains:s},{token:t})),createWithId:(n,s,o)=>a(e.httpClient.post(u.create,{id:n,name:s,selfProvisioningDomains:o},{token:t})),update:(n,s,o)=>a(e.httpClient.post(u.update,{id:n,name:s,selfProvisioningDomains:o},{token:t})),delete:n=>a(e.httpClient.post(u.delete,{id:n},{token:t})),loadAll:()=>a(e.httpClient.get(u.loadAll,{token:t}),(e=>e.tenants))}),w=(e,t)=>({update:(n,s)=>a(e.httpClient.post(g.update,{jwt:n,customClaims:s},{token:t}))}),I=(e,t)=>({create:(n,s)=>a(e.httpClient.post(v.create,{name:n,description:s},{token:t})),update:(n,s,o)=>a(e.httpClient.post(v.update,{name:n,newName:s,description:o},{token:t})),delete:n=>a(e.httpClient.post(v.delete,{name:n},{token:t})),loadAll:()=>a(e.httpClient.get(v.loadAll,{token:t}),(e=>e.permissions))}),b=(e,t)=>({create:(n,s,o)=>a(e.httpClient.post(k.create,{name:n,description:s,permissionNames:o},{token:t})),update:(n,s,o,r)=>a(e.httpClient.post(k.update,{name:n,newName:s,description:o,permissionNames:r},{token:t})),delete:n=>a(e.httpClient.post(k.delete,{name:n},{token:t})),loadAll:()=>a(e.httpClient.get(k.loadAll,{token:t}),(e=>e.roles))}),A=(e,t)=>({loadAllGroups:n=>a(e.httpClient.post(y.loadAllGroups,{tenantId:n},{token:t})),loadAllGroupsForMember:(n,s,o)=>a(e.httpClient.post(y.loadAllGroupsForMember,{tenantId:n,loginIds:o,userIds:s},{token:t})),loadAllGroupMembers:(n,s)=>a(e.httpClient.post(y.loadAllGroupMembers,{tenantId:n,groupId:s},{token:t}))}),j=(e,t)=>({configureSettings:(n,s,o,r,i,l)=>a(e.httpClient.post(h.configure,{tenantId:n,idpURL:s,entityId:r,idpCert:o,redirectURL:i,domain:l},{token:t})),configureMetadata:(n,s)=>a(e.httpClient.post(h.metadata,{tenantId:n,idpMetadataURL:s},{token:t})),configureMapping:(n,s,o)=>a(e.httpClient.post(h.mapping,{tenantId:n,roleMapping:s,attributeMapping:o},{token:t}))}),T=(e,t)=>({create:(n,s,o,r)=>a(e.httpClient.post(c.create,{name:n,expireTime:s,roleNames:o,keyTenants:r},{token:t})),load:n=>a(e.httpClient.get(c.load,{queryParams:{id:n},token:t}),(e=>e.key)),searchAll:n=>a(e.httpClient.post(c.search,{tenantIds:n},{token:t}),(e=>e.keys)),update:(n,s)=>a(e.httpClient.post(c.update,{id:n,name:s},{token:t}),(e=>e.key)),deactivate:n=>a(e.httpClient.post(c.deactivate,{id:n},{token:t})),activate:n=>a(e.httpClient.post(c.activate,{id:n},{token:t})),delete:n=>a(e.httpClient.post(c.delete,{id:n},{token:t}))});var N;null!==(N=globalThis.Headers)&&void 0!==N||(globalThis.Headers=l);const R=(...e)=>(e.forEach((e=>{var t,a;e&&(null!==(t=(a=e).highWaterMark)&&void 0!==t||(a.highWaterMark=32212254720))})),i(...e)),x=a=>{var i,{managementKey:l}=a,m=e(a,["managementKey"]);const c=t(Object.assign(Object.assign({},m),{fetch:R,baseHeaders:Object.assign(Object.assign({},m.baseHeaders),{"x-descope-sdk-name":"nodejs","x-descope-sdk-node-version":(null===(i=null===process||void 0===process?void 0:process.versions)||void 0===i?void 0:i.node)||"","x-descope-sdk-version":"0.0.0-next-c074bc45-20230308"})})),{projectId:u,logger:h}=m,g={},v=((e,t)=>({user:f(e,t),accessKey:T(e,t),tenant:C(e,t),sso:j(e,t),jwt:w(e,t),permission:I(e,t),role:b(e,t),group:A(e,t)}))(c,l),k=Object.assign(Object.assign({},c),{management:v,async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(g[e.kid])return g[e.kid];if(Object.assign(g,await(async()=>{const e=(await c.httpClient.get(`v2/keys/${u}`).then((e=>e.json()))).keys;return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await r(e)])))).reduce(((e,[t,a])=>t?Object.assign(Object.assign({},e),{[t.toString()]:a}):e),{}):{}})()),!g[e.kid])throw Error("failed to fetch matching key");return g[e.kid]},async validateJwt(e){var t;const a=(await s(e,k.getKey,{clockTolerance:5})).payload;if(a&&(a.iss=null===(t=a.iss)||void 0===t?void 0:t.split("/").pop(),a.iss!==u))throw new o.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");return{jwt:e,token:a}},async validateSession(e){if(!e)throw Error("session token is required for validation");try{return await k.validateJwt(e)}catch(e){throw null==h||h.error("session validation failed",e),Error("session validation failed")}},async refreshSession(e){var t,a;if(!e)throw Error("refresh token is required to refresh a session");try{await k.validateJwt(e);const n=await k.refresh(e);if(n.ok){return await k.validateJwt(null===(t=n.data)||void 0===t?void 0:t.sessionJwt)}throw Error(null===(a=n.error)||void 0===a?void 0:a.errorMessage)}catch(e){throw null==h||h.error("refresh token validation failed",e),Error("refresh token validation failed")}},async validateAndRefreshSession(e,t){if(!e&&!t)throw Error("both session and refresh tokens are empty");try{return await k.validateSession(e)}catch(e){null==h||h.log("session validation failed - trying to refresh it")}return k.refreshSession(t)},async exchangeAccessKey(e){if(!e)throw Error("access key must not be empty");let t;try{t=await k.accessKey.exchange(e)}catch(e){throw null==h||h.error("failed to exchange access key",e),Error("could not exchange access key")}const{sessionJwt:a}=t.data;if(!a)throw null==h||h.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await k.validateJwt(a)}catch(e){throw null==h||h.error("failed to parse jwt from access key",e),Error("could not exchange access key")}},validatePermissions:(e,t)=>k.validateTenantPermissions(e,null,t),validateTenantPermissions(e,t,a){const n=p(e,"permissions",t);return a.every((e=>n.includes(e)))},validateRoles:(e,t)=>k.validateTenantRoles(e,null,t),validateTenantRoles(e,t,a){const n=p(e,"roles",t);return a.every((e=>n.includes(e)))}});return n(k,["otp.verify.email","otp.verify.sms","otp.verify.whatsapp","magicLink.verify","enchantedLink.signUp","enchantedLink.signIn","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"],d)};x.RefreshTokenCookieName="DSR",x.SessionTokenCookieName="DS";export{x as default};
import{__rest as e}from"tslib";import t,{transformResponse as s,wrapWith as a}from"@descope/core-js-sdk";import{jwtVerify as n,errors as o,importJWK as i}from"jose";import{Headers as r,fetch as l}from"cross-fetch";const d=t=>async(...s)=>{var a,n,o;const i=await t(...s);if(!i.data)return i;let r=i.data,{refreshJwt:l}=r,d=e(r,["refreshJwt"]);const p=[];var m;return l?p.push(`${"DSR"}=${l}; Domain=${(null==(m=d)?void 0:m.cookieDomain)||""}; Max-Age=${(null==m?void 0:m.cookieMaxAge)||""}; Path=${(null==m?void 0:m.cookiePath)||"/"}; HttpOnly; SameSite=Strict`):(null===(a=i.response)||void 0===a?void 0:a.headers.get("set-cookie"))&&(l=((e,t)=>{const s=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return s?s[1]:null})(null===(n=i.response)||void 0===n?void 0:n.headers.get("set-cookie"),"DSR"),p.push(null===(o=i.response)||void 0===o?void 0:o.headers.get("set-cookie"))),Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{refreshJwt:l,cookies:p})})};function p(e,t,s){var a,n;const o=s?null===(n=null===(a=e.token.tenants)||void 0===a?void 0:a[s])||void 0===n?void 0:n[t]:e.token[t];return Array.isArray(o)?o:[]}function m(e,t){var s;return!!(null===(s=e.token.tenants)||void 0===s?void 0:s[t])}var c={create:"/v1/mgmt/user/create",createBatch:"/v1/mgmt/user/create/batch",update:"/v1/mgmt/user/update",delete:"/v1/mgmt/user/delete",deleteAllTestUsers:"/v1/mgmt/user/test/delete/all",load:"/v1/mgmt/user",logout:"/v1/mgmt/user/logout",search:"/v1/mgmt/user/search",getProviderToken:"/v1/mgmt/user/provider/token",updateStatus:"/v1/mgmt/user/update/status",updateLoginId:"/v1/mgmt/user/update/loginid",updateEmail:"/v1/mgmt/user/update/email",updatePhone:"/v1/mgmt/user/update/phone",updateDisplayName:"/v1/mgmt/user/update/name",updatePicture:"/v1/mgmt/user/update/picture",updateCustomAttribute:"/v1/mgmt/user/update/customAttribute",setRole:"/v1/mgmt/user/update/role/set",addRole:"/v1/mgmt/user/update/role/add",removeRole:"/v1/mgmt/user/update/role/remove",setSSOApps:"/v1/mgmt/user/update/ssoapp/set",addSSOApps:"/v1/mgmt/user/update/ssoapp/add",removeSSOApps:"/v1/mgmt/user/update/ssoapp/remove",addTenant:"/v1/mgmt/user/update/tenant/add",removeTenant:"/v1/mgmt/user/update/tenant/remove",setPassword:"/v1/mgmt/user/password/set",setTemporaryPassword:"/v1/mgmt/user/password/set/temporary",setActivePassword:"/v1/mgmt/user/password/set/active",expirePassword:"/v1/mgmt/user/password/expire",removeAllPasskeys:"/v1/mgmt/user/passkeys/delete",generateOTPForTest:"/v1/mgmt/tests/generate/otp",generateMagicLinkForTest:"/v1/mgmt/tests/generate/magiclink",generateEnchantedLinkForTest:"/v1/mgmt/tests/generate/enchantedlink",generateEmbeddedLink:"/v1/mgmt/user/signin/embeddedlink",history:"/v1/mgmt/user/history"},g={updateName:"/v1/mgmt/project/update/name",clone:"/v1/mgmt/project/clone",export:"/v1/mgmt/project/export",import:"/v1/mgmt/project/import"},u={create:"/v1/mgmt/accesskey/create",load:"/v1/mgmt/accesskey",search:"/v1/mgmt/accesskey/search",update:"/v1/mgmt/accesskey/update",deactivate:"/v1/mgmt/accesskey/deactivate",activate:"/v1/mgmt/accesskey/activate",delete:"/v1/mgmt/accesskey/delete"},h={create:"/v1/mgmt/tenant/create",update:"/v1/mgmt/tenant/update",delete:"/v1/mgmt/tenant/delete",load:"/v1/mgmt/tenant",settings:"/v1/mgmt/tenant/settings",loadAll:"/v1/mgmt/tenant/all",searchAll:"/v1/mgmt/tenant/search"},v={oidcCreate:"/v1/mgmt/sso/idp/app/oidc/create",samlCreate:"/v1/mgmt/sso/idp/app/saml/create",oidcUpdate:"/v1/mgmt/sso/idp/app/oidc/update",samlUpdate:"/v1/mgmt/sso/idp/app/saml/update",delete:"/v1/mgmt/sso/idp/app/delete",load:"/v1/mgmt/sso/idp/app/load",loadAll:"/v1/mgmt/sso/idp/apps/load"},k={settings:"/v1/mgmt/sso/settings",metadata:"/v1/mgmt/sso/metadata",mapping:"/v1/mgmt/sso/mapping",settingsv2:"/v2/mgmt/sso/settings",oidc:{configure:"/v1/mgmt/sso/oidc"},saml:{configure:"/v1/mgmt/sso/saml",metadata:"/v1/mgmt/sso/saml/metadata"}},C={update:"/v1/mgmt/jwt/update",impersonate:"/v1/mgmt/impersonate"},f={settings:"/v1/mgmt/password/settings"},y={create:"/v1/mgmt/permission/create",update:"/v1/mgmt/permission/update",delete:"/v1/mgmt/permission/delete",loadAll:"/v1/mgmt/permission/all"},I={create:"/v1/mgmt/role/create",update:"/v1/mgmt/role/update",delete:"/v1/mgmt/role/delete",loadAll:"/v1/mgmt/role/all",search:"/v1/mgmt/role/search"},b={list:"/v1/mgmt/flow/list",delete:"/v1/mgmt/flow/delete",export:"/v1/mgmt/flow/export",import:"/v1/mgmt/flow/import"},w={export:"/v1/mgmt/theme/export",import:"/v1/mgmt/theme/import"},A={loadAllGroups:"/v1/mgmt/group/all",loadAllGroupsForMember:"/v1/mgmt/group/member/all",loadAllGroupMembers:"/v1/mgmt/group/members"},O={search:"/v1/mgmt/audit/search",createEvent:"/v1/mgmt/audit/event"},S={schemaSave:"/v1/mgmt/authz/schema/save",schemaDelete:"/v1/mgmt/authz/schema/delete",schemaLoad:"/v1/mgmt/authz/schema/load",nsSave:"/v1/mgmt/authz/ns/save",nsDelete:"/v1/mgmt/authz/ns/delete",rdSave:"/v1/mgmt/authz/rd/save",rdDelete:"/v1/mgmt/authz/rd/delete",reCreate:"/v1/mgmt/authz/re/create",reDelete:"/v1/mgmt/authz/re/delete",reDeleteResources:"/v1/mgmt/authz/re/deleteresources",hasRelations:"/v1/mgmt/authz/re/has",who:"/v1/mgmt/authz/re/who",resource:"/v1/mgmt/authz/re/resource",targets:"/v1/mgmt/authz/re/targets",targetAll:"/v1/mgmt/authz/re/targetall",getModified:"/v1/mgmt/authz/getmodified"};const N=(e,t)=>({create:function(a,n,o,i,r,l,d,p,m,g,u,h,v,k){const C="string"==typeof n?{loginId:a,email:n,phone:o,displayName:i,givenName:u,middleName:h,familyName:v,roleNames:r,userTenants:l,customAttributes:d,picture:p,verifiedEmail:m,verifiedPhone:g,additionalLoginIds:k}:Object.assign(Object.assign({loginId:a},n),{roleNames:null==n?void 0:n.roles,roles:void 0});return s(e.httpClient.post(c.create,C,{token:t}),(e=>e.user))},createTestUser:function(a,n,o,i,r,l,d,p,m,g,u,h,v,k){const C="string"==typeof n?{loginId:a,email:n,phone:o,displayName:i,givenName:u,middleName:h,familyName:v,roleNames:r,userTenants:l,customAttributes:d,picture:p,verifiedEmail:m,verifiedPhone:g,additionalLoginIds:k,test:!0}:Object.assign(Object.assign({loginId:a},n),{roleNames:null==n?void 0:n.roles,roles:void 0,test:!0});return s(e.httpClient.post(c.create,C,{token:t}),(e=>e.user))},invite:function(a,n,o,i,r,l,d,p,m,g,u,h,v,k,C,f,y){const I="string"==typeof n?{loginId:a,email:n,phone:o,displayName:i,givenName:k,middleName:C,familyName:f,roleNames:r,userTenants:l,invite:!0,customAttributes:d,picture:p,verifiedEmail:m,verifiedPhone:g,inviteUrl:u,sendMail:h,sendSMS:v,additionalLoginIds:y}:Object.assign(Object.assign({loginId:a},n),{roleNames:null==n?void 0:n.roles,roles:void 0,invite:!0});return s(e.httpClient.post(c.create,I,{token:t}),(e=>e.user))},inviteBatch:(a,n,o,i,r)=>s(e.httpClient.post(c.createBatch,{users:a,invite:!0,inviteUrl:n,sendMail:o,sendSMS:i,templateOptions:r},{token:t}),(e=>e)),update:function(a,n,o,i,r,l,d,p,m,g,u,h,v,k){const C="string"==typeof n?{loginId:a,email:n,phone:o,displayName:i,givenName:u,middleName:h,familyName:v,roleNames:r,userTenants:l,customAttributes:d,picture:p,verifiedEmail:m,verifiedPhone:g,additionalLoginIds:k}:Object.assign(Object.assign({loginId:a},n),{roleNames:null==n?void 0:n.roles,roles:void 0});return s(e.httpClient.post(c.update,C,{token:t}),(e=>e.user))},delete:a=>s(e.httpClient.post(c.delete,{loginId:a},{token:t})),deleteByUserId:a=>s(e.httpClient.post(c.delete,{userId:a},{token:t})),deleteAllTestUsers:()=>s(e.httpClient.delete(c.deleteAllTestUsers,{token:t})),load:a=>s(e.httpClient.get(c.load,{queryParams:{loginId:a},token:t}),(e=>e.user)),loadByUserId:a=>s(e.httpClient.get(c.load,{queryParams:{userId:a},token:t}),(e=>e.user)),logoutUser:a=>s(e.httpClient.post(c.logout,{loginId:a},{token:t})),logoutUserByUserId:a=>s(e.httpClient.post(c.logout,{userId:a},{token:t})),searchAll:(a,n,o,i,r,l,d,p,m,g)=>s(e.httpClient.post(c.search,{tenantIds:a,roleNames:n,limit:o,page:i,testUsersOnly:r,withTestUser:l,customAttributes:d,statuses:p,emails:m,phones:g},{token:t}),(e=>e.users)),search:a=>s(e.httpClient.post(c.search,Object.assign(Object.assign({},a),{roleNames:a.roles,roles:void 0}),{token:t}),(e=>e.users)),getProviderToken:(a,n)=>s(e.httpClient.get(c.getProviderToken,{queryParams:{loginId:a,provider:n},token:t}),(e=>e)),activate:a=>s(e.httpClient.post(c.updateStatus,{loginId:a,status:"enabled"},{token:t}),(e=>e.user)),deactivate:a=>s(e.httpClient.post(c.updateStatus,{loginId:a,status:"disabled"},{token:t}),(e=>e.user)),updateLoginId:(a,n)=>s(e.httpClient.post(c.updateLoginId,{loginId:a,newLoginId:n},{token:t}),(e=>e.user)),updateEmail:(a,n,o)=>s(e.httpClient.post(c.updateEmail,{loginId:a,email:n,verified:o},{token:t}),(e=>e.user)),updatePhone:(a,n,o)=>s(e.httpClient.post(c.updatePhone,{loginId:a,phone:n,verified:o},{token:t}),(e=>e.user)),updateDisplayName:(a,n,o,i,r)=>s(e.httpClient.post(c.updateDisplayName,{loginId:a,displayName:n,givenName:o,middleName:i,familyName:r},{token:t}),(e=>e.user)),updatePicture:(a,n)=>s(e.httpClient.post(c.updatePicture,{loginId:a,picture:n},{token:t}),(e=>e.user)),updateCustomAttribute:(a,n,o)=>s(e.httpClient.post(c.updateCustomAttribute,{loginId:a,attributeKey:n,attributeValue:o},{token:t}),(e=>e.user)),setRoles:(a,n)=>s(e.httpClient.post(c.setRole,{loginId:a,roleNames:n},{token:t}),(e=>e.user)),addRoles:(a,n)=>s(e.httpClient.post(c.addRole,{loginId:a,roleNames:n},{token:t}),(e=>e.user)),removeRoles:(a,n)=>s(e.httpClient.post(c.removeRole,{loginId:a,roleNames:n},{token:t}),(e=>e.user)),addTenant:(a,n)=>s(e.httpClient.post(c.addTenant,{loginId:a,tenantId:n},{token:t}),(e=>e.user)),removeTenant:(a,n)=>s(e.httpClient.post(c.removeTenant,{loginId:a,tenantId:n},{token:t}),(e=>e.user)),setTenantRoles:(a,n,o)=>s(e.httpClient.post(c.setRole,{loginId:a,tenantId:n,roleNames:o},{token:t}),(e=>e.user)),addTenantRoles:(a,n,o)=>s(e.httpClient.post(c.addRole,{loginId:a,tenantId:n,roleNames:o},{token:t}),(e=>e.user)),removeTenantRoles:(a,n,o)=>s(e.httpClient.post(c.removeRole,{loginId:a,tenantId:n,roleNames:o},{token:t}),(e=>e.user)),addSSOapps:(a,n)=>s(e.httpClient.post(c.addSSOApps,{loginId:a,ssoAppIds:n},{token:t}),(e=>e.user)),setSSOapps:(a,n)=>s(e.httpClient.post(c.setSSOApps,{loginId:a,ssoAppIds:n},{token:t}),(e=>e.user)),removeSSOapps:(a,n)=>s(e.httpClient.post(c.removeSSOApps,{loginId:a,ssoAppIds:n},{token:t}),(e=>e.user)),generateOTPForTestUser:(a,n,o)=>s(e.httpClient.post(c.generateOTPForTest,{deliveryMethod:a,loginId:n,loginOptions:o},{token:t}),(e=>e)),generateMagicLinkForTestUser:(a,n,o,i)=>s(e.httpClient.post(c.generateMagicLinkForTest,{deliveryMethod:a,loginId:n,URI:o,loginOptions:i},{token:t}),(e=>e)),generateEnchantedLinkForTestUser:(a,n,o)=>s(e.httpClient.post(c.generateEnchantedLinkForTest,{loginId:a,URI:n,loginOptions:o},{token:t}),(e=>e)),generateEmbeddedLink:(a,n)=>s(e.httpClient.post(c.generateEmbeddedLink,{loginId:a,customClaims:n},{token:t}),(e=>e)),setTemporaryPassword:(a,n)=>s(e.httpClient.post(c.setTemporaryPassword,{loginId:a,password:n},{token:t}),(e=>e)),setActivePassword:(a,n)=>s(e.httpClient.post(c.setActivePassword,{loginId:a,password:n},{token:t}),(e=>e)),setPassword:(a,n)=>s(e.httpClient.post(c.setPassword,{loginId:a,password:n},{token:t}),(e=>e)),expirePassword:a=>s(e.httpClient.post(c.expirePassword,{loginId:a},{token:t}),(e=>e)),removeAllPasskeys:a=>s(e.httpClient.post(c.removeAllPasskeys,{loginId:a},{token:t}),(e=>e)),history:a=>s(e.httpClient.post(c.history,a,{token:t}),(e=>e))}),j=(e,t)=>({updateName:a=>s(e.httpClient.post(g.updateName,{name:a},{token:t})),clone:(a,n)=>s(e.httpClient.post(g.clone,{name:a,tag:n},{token:t})),export:()=>s(e.httpClient.post(g.export,{},{token:t}),(e=>e.files)),import:a=>s(e.httpClient.post(g.import,{files:a},{token:t}))}),P=(e,t)=>({create:(a,n,o)=>s(e.httpClient.post(h.create,{name:a,selfProvisioningDomains:n,customAttributes:o},{token:t})),createWithId:(a,n,o,i)=>s(e.httpClient.post(h.create,{id:a,name:n,selfProvisioningDomains:o,customAttributes:i},{token:t})),update:(a,n,o,i)=>s(e.httpClient.post(h.update,{id:a,name:n,selfProvisioningDomains:o,customAttributes:i},{token:t})),delete:(a,n)=>s(e.httpClient.post(h.delete,{id:a,cascade:n},{token:t})),load:a=>s(e.httpClient.get(h.load,{queryParams:{id:a},token:t}),(e=>e)),loadAll:()=>s(e.httpClient.get(h.loadAll,{token:t}),(e=>e.tenants)),searchAll:(a,n,o,i)=>s(e.httpClient.post(h.searchAll,{tenantIds:a,tenantNames:n,tenantSelfProvisioningDomains:o,customAttributes:i},{token:t}),(e=>e.tenants)),getSettings:a=>s(e.httpClient.get(h.settings,{queryParams:{id:a},token:t}),(e=>e)),configureSettings:(a,n)=>s(e.httpClient.post(h.settings,Object.assign(Object.assign({},n),{tenantId:a}),{token:t}))}),T=(e,t)=>({update:(a,n)=>s(e.httpClient.post(C.update,{jwt:a,customClaims:n},{token:t})),impersonate:(a,n,o)=>s(e.httpClient.post(C.impersonate,{impersonatorId:a,loginId:n,validateConsent:o},{token:t}))}),R=(e,t)=>({create:(a,n)=>s(e.httpClient.post(y.create,{name:a,description:n},{token:t})),update:(a,n,o)=>s(e.httpClient.post(y.update,{name:a,newName:n,description:o},{token:t})),delete:a=>s(e.httpClient.post(y.delete,{name:a},{token:t})),loadAll:()=>s(e.httpClient.get(y.loadAll,{token:t}),(e=>e.permissions))}),M=(e,t)=>({create:(a,n,o,i)=>s(e.httpClient.post(I.create,{name:a,description:n,permissionNames:o,tenantId:i},{token:t})),update:(a,n,o,i,r)=>s(e.httpClient.post(I.update,{name:a,newName:n,description:o,permissionNames:i,tenantId:r},{token:t})),delete:(a,n)=>s(e.httpClient.post(I.delete,{name:a,tenantId:n},{token:t})),loadAll:()=>s(e.httpClient.get(I.loadAll,{token:t}),(e=>e.roles)),search:a=>s(e.httpClient.post(I.search,a,{token:t}),(e=>e.roles))}),E=(e,t)=>({loadAllGroups:a=>s(e.httpClient.post(A.loadAllGroups,{tenantId:a},{token:t})),loadAllGroupsForMember:(a,n,o)=>s(e.httpClient.post(A.loadAllGroupsForMember,{tenantId:a,loginIds:o,userIds:n},{token:t})),loadAllGroupMembers:(a,n)=>s(e.httpClient.post(A.loadAllGroupMembers,{tenantId:a,groupId:n},{token:t}))}),x=(e,t)=>({getSettings:a=>s(e.httpClient.get(k.settings,{queryParams:{tenantId:a},token:t}),(e=>e)),deleteSettings:a=>s(e.httpClient.delete(k.settings,{queryParams:{tenantId:a},token:t})),configureSettings:(a,n,o,i,r,l)=>s(e.httpClient.post(k.settings,{tenantId:a,idpURL:n,entityId:i,idpCert:o,redirectURL:r,domains:l},{token:t})),configureMetadata:(a,n,o,i)=>s(e.httpClient.post(k.metadata,{tenantId:a,idpMetadataURL:n,redirectURL:o,domains:i},{token:t})),configureMapping:(a,n,o)=>s(e.httpClient.post(k.mapping,{tenantId:a,roleMappings:n,attributeMapping:o},{token:t})),configureOIDCSettings:(a,n,o)=>{const i=Object.assign(Object.assign({},n),{userAttrMapping:n.attributeMapping});return delete i.attributeMapping,s(e.httpClient.post(k.oidc.configure,{tenantId:a,settings:i,domains:o},{token:t}))},configureSAMLSettings:(a,n,o,i)=>s(e.httpClient.post(k.saml.configure,{tenantId:a,settings:n,redirectUrl:o,domains:i},{token:t})),configureSAMLByMetadata:(a,n,o,i)=>s(e.httpClient.post(k.saml.metadata,{tenantId:a,settings:n,redirectUrl:o,domains:i},{token:t})),loadSettings:a=>s(e.httpClient.get(k.settingsv2,{queryParams:{tenantId:a},token:t}),(e=>{var t,s;const a=e;return a.oidc&&(a.oidc=Object.assign(Object.assign({},a.oidc),{attributeMapping:a.oidc.userAttrMapping}),delete a.oidc.userAttrMapping),(null===(t=a.saml)||void 0===t?void 0:t.groupsMapping)&&(a.saml.groupsMapping=null===(s=a.saml)||void 0===s?void 0:s.groupsMapping.map((e=>{const t=e;return t.roleName=t.role.name,delete t.role,t}))),a}))}),U=(e,t)=>({create:(a,n,o,i,r,l)=>s(e.httpClient.post(u.create,{name:a,expireTime:n,roleNames:o,keyTenants:i,userId:r,customClaims:l},{token:t})),load:a=>s(e.httpClient.get(u.load,{queryParams:{id:a},token:t}),(e=>e.key)),searchAll:a=>s(e.httpClient.post(u.search,{tenantIds:a},{token:t}),(e=>e.keys)),update:(a,n)=>s(e.httpClient.post(u.update,{id:a,name:n},{token:t}),(e=>e.key)),deactivate:a=>s(e.httpClient.post(u.deactivate,{id:a},{token:t})),activate:a=>s(e.httpClient.post(u.activate,{id:a},{token:t})),delete:a=>s(e.httpClient.post(u.delete,{id:a},{token:t}))}),L=(e,t)=>({list:()=>s(e.httpClient.post(b.list,{},{token:t})),delete:a=>s(e.httpClient.post(b.delete,{ids:a},{token:t})),export:a=>s(e.httpClient.post(b.export,{flowId:a},{token:t})),import:(a,n,o)=>s(e.httpClient.post(b.import,{flowId:a,flow:n,screens:o},{token:t}))}),D=(e,t)=>({export:()=>s(e.httpClient.post(w.export,{},{token:t})),import:a=>s(e.httpClient.post(w.import,{theme:a},{token:t}))}),F=(e,t)=>({search:a=>{const n=Object.assign(Object.assign({},a),{externalIds:a.loginIds});return delete n.loginIds,s(e.httpClient.post(O.search,n,{token:t}),(e=>null==e?void 0:e.audits.map((e=>{const t=Object.assign(Object.assign({},e),{occurred:parseFloat(e.occurred),loginIds:e.externalIds});return delete t.externalIds,t}))))},createEvent:a=>{const n=Object.assign({},a);return s(e.httpClient.post(O.createEvent,n,{token:t}))}}),z=(e,t)=>({saveSchema:(a,n)=>s(e.httpClient.post(S.schemaSave,{schema:a,upgrade:n},{token:t})),deleteSchema:()=>s(e.httpClient.post(S.schemaDelete,{},{token:t})),loadSchema:()=>s(e.httpClient.post(S.schemaLoad,{},{token:t}),(e=>e.schema)),saveNamespace:(a,n,o)=>s(e.httpClient.post(S.nsSave,{namespace:a,oldName:n,schemaName:o},{token:t})),deleteNamespace:(a,n)=>s(e.httpClient.post(S.nsDelete,{name:a,schemaName:n},{token:t})),saveRelationDefinition:(a,n,o,i)=>s(e.httpClient.post(S.rdSave,{relationDefinition:a,namespace:n,oldName:o,schemaName:i},{token:t})),deleteRelationDefinition:(a,n,o)=>s(e.httpClient.post(S.rdDelete,{name:a,namespace:n,schemaName:o},{token:t})),createRelations:a=>s(e.httpClient.post(S.reCreate,{relations:a},{token:t})),deleteRelations:a=>s(e.httpClient.post(S.reDelete,{relations:a},{token:t})),deleteRelationsForResources:a=>s(e.httpClient.post(S.reDeleteResources,{resources:a},{token:t})),hasRelations:a=>s(e.httpClient.post(S.hasRelations,{relationQueries:a},{token:t}),(e=>e.relationQueries)),whoCanAccess:(a,n,o)=>s(e.httpClient.post(S.who,{resource:a,relationDefinition:n,namespace:o},{token:t}),(e=>e.targets)),resourceRelations:a=>s(e.httpClient.post(S.resource,{resource:a},{token:t}),(e=>e.relations)),targetsRelations:a=>s(e.httpClient.post(S.targets,{targets:a},{token:t}),(e=>e.relations)),whatCanTargetAccess:a=>s(e.httpClient.post(S.targetAll,{target:a},{token:t}),(e=>e.relations)),getModified:a=>s(e.httpClient.post(S.getModified,{since:a?a.getTime():0},{token:t}),(e=>e))}),q=(e,t)=>({createOidcApplication:a=>{var n;return s(e.httpClient.post(v.oidcCreate,Object.assign(Object.assign({},a),{enabled:null===(n=a.enabled)||void 0===n||n}),{token:t}))},createSamlApplication:a=>{var n;return s(e.httpClient.post(v.samlCreate,Object.assign(Object.assign({},a),{enabled:null===(n=a.enabled)||void 0===n||n}),{token:t}))},updateOidcApplication:a=>s(e.httpClient.post(v.oidcUpdate,Object.assign({},a),{token:t})),updateSamlApplication:a=>s(e.httpClient.post(v.samlUpdate,Object.assign({},a),{token:t})),delete:a=>s(e.httpClient.post(v.delete,{id:a},{token:t})),load:a=>s(e.httpClient.get(v.load,{queryParams:{id:a},token:t}),(e=>e)),loadAll:()=>s(e.httpClient.get(v.loadAll,{token:t}),(e=>e.apps))}),$=(e,t)=>({getSettings:a=>s(e.httpClient.get(f.settings,{queryParams:{tenantId:a},token:t}),(e=>e)),configureSettings:(a,n)=>s(e.httpClient.post(f.settings,Object.assign(Object.assign({},n),{tenantId:a}),{token:t}))});var J;null!==(J=globalThis.Headers)&&void 0!==J||(globalThis.Headers=r);const K=(...e)=>(e.forEach((e=>{var t,s;e&&(null!==(t=(s=e).highWaterMark)&&void 0!==t||(s.highWaterMark=31457280))})),l(...e)),G={badRequest:"E011001",missingArguments:"E011002",invalidRequest:"E011003",invalidArguments:"E011004",wrongOTPCode:"E061102",tooManyOTPAttempts:"E061103",enchantedLinkPending:"E062503",userNotFound:"E062108"},B=s=>{var r,{managementKey:l,publicKey:c}=s,g=e(s,["managementKey","publicKey"]);const u=t(Object.assign(Object.assign({fetch:K},g),{baseHeaders:Object.assign(Object.assign({},g.baseHeaders),{"x-descope-sdk-name":"nodejs","x-descope-sdk-node-version":(null===(r=null===process||void 0===process?void 0:process.versions)||void 0===r?void 0:r.node)||"","x-descope-sdk-version":"0.0.0-next-c1eb2147-20240627"})})),{projectId:h,logger:v}=g,k={},C=((e,t)=>({user:N(e,t),project:j(e,t),accessKey:U(e,t),tenant:P(e,t),ssoApplication:q(e,t),sso:x(e,t),jwt:T(e,t),permission:R(e,t),password:$(e,t),role:M(e,t),group:E(e,t),flow:L(e,t),theme:D(e,t),audit:F(e,t),authz:z(e,t)}))(u,l),f=Object.assign(Object.assign({},u),{management:C,async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(k[e.kid])return k[e.kid];if(Object.assign(k,await(async()=>{if(c)try{const e=JSON.parse(c),t=await i(e);return{[e.kid]:t}}catch(e){throw null==v||v.error("Failed to parse the provided public key",e),new Error(`Failed to parse public key. Error: ${e}`)}const e=(await u.httpClient.get(`v2/keys/${h}`).then((e=>e.json()))).keys;return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await i(e)])))).reduce(((e,[t,s])=>t?Object.assign(Object.assign({},e),{[t.toString()]:s}):e),{}):{}})()),!k[e.kid])throw Error("failed to fetch matching key");return k[e.kid]},async validateJwt(e){var t;const s=(await n(e,f.getKey,{clockTolerance:5})).payload;if(s&&(s.iss=null===(t=s.iss)||void 0===t?void 0:t.split("/").pop(),s.iss!==h))throw new o.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");return{jwt:e,token:s}},async validateSession(e){if(!e)throw Error("session token is required for validation");try{return await f.validateJwt(e)}catch(e){throw null==v||v.error("session validation failed",e),Error(`session validation failed. Error: ${e}`)}},async refreshSession(e){var t,s;if(!e)throw Error("refresh token is required to refresh a session");try{await f.validateJwt(e);const a=await f.refresh(e);if(a.ok){return await f.validateJwt(null===(t=a.data)||void 0===t?void 0:t.sessionJwt)}throw Error(null===(s=a.error)||void 0===s?void 0:s.errorMessage)}catch(e){throw null==v||v.error("refresh token validation failed",e),Error(`refresh token validation failed, Error: ${e}`)}},async validateAndRefreshSession(e,t){if(!e&&!t)throw Error("both session and refresh tokens are empty");try{return await f.validateSession(e)}catch(e){null==v||v.log(`session validation failed with error ${e} - trying to refresh it`)}return f.refreshSession(t)},async exchangeAccessKey(e,t){if(!e)throw Error("access key must not be empty");let s;try{s=await f.accessKey.exchange(e,t)}catch(e){throw null==v||v.error("failed to exchange access key",e),Error(`could not exchange access key - Failed to exchange. Error: ${e}`)}const{sessionJwt:a}=s.data;if(!a)throw null==v||v.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await f.validateJwt(a)}catch(e){throw null==v||v.error("failed to parse jwt from access key",e),Error(`could not exchange access key - failed to validate jwt. Error: ${e}`)}},validatePermissions:(e,t)=>f.validateTenantPermissions(e,"",t),getMatchedPermissions:(e,t)=>f.getMatchedTenantPermissions(e,"",t),validateTenantPermissions(e,t,s){if(t&&!m(e,t))return!1;const a=p(e,"permissions",t);return s.every((e=>a.includes(e)))},getMatchedTenantPermissions(e,t,s){if(t&&!m(e,t))return[];const a=p(e,"permissions",t);return s.filter((e=>a.includes(e)))},validateRoles:(e,t)=>f.validateTenantRoles(e,"",t),getMatchedRoles:(e,t)=>f.getMatchedTenantRoles(e,"",t),validateTenantRoles(e,t,s){if(t&&!m(e,t))return!1;const a=p(e,"roles",t);return s.every((e=>a.includes(e)))},getMatchedTenantRoles(e,t,s){if(t&&!m(e,t))return[];const a=p(e,"roles",t);return s.filter((e=>a.includes(e)))}});return a(f,["otp.verify.email","otp.verify.sms","otp.verify.voice","otp.verify.whatsapp","magicLink.verify","enchantedLink.signUp","enchantedLink.signIn","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"],d)};B.RefreshTokenCookieName="DSR",B.SessionTokenCookieName="DS";export{B as default,G as descopeErrors};
//# sourceMappingURL=index.esm.js.map
{
"name": "@descope/node-sdk",
"version": "0.0.0-next-c074bc45-20230308",
"version": "0.0.0-next-c1eb2147-20240627",
"description": "Node.js library used to integrate with Descope",

@@ -10,4 +10,10 @@ "typings": "./dist/index.d.ts",

"exports": {
"require": "./dist/cjs/index.cjs.js",
"import": "./dist/index.esm.js"
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/cjs/index.cjs.js"
},
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.esm.js"
}
},

@@ -53,12 +59,11 @@ "type": "module",

"devDependencies": {
"@rollup/plugin-commonjs": "^22.0.0",
"@rollup/plugin-commonjs": "^25.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.3.0",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-replace": "^5.0.0",
"@rollup/plugin-typescript": "^8.3.0",
"@size-limit/preset-small-lib": "^8.0.0",
"@size-limit/preset-small-lib": "^11.0.0",
"@types/jest": "^29.0.0",
"@types/jsonwebtoken": "^9.0.0",
"@types/node": "^15.14.9",
"@types/node-fetch": "^2.6.1",
"@types/node": "^20.0.0",
"@typescript-eslint/eslint-plugin": "^5.25.0",

@@ -69,7 +74,7 @@ "@typescript-eslint/parser": "^5.27.0",

"eslint-config-airbnb-typescript": "^17.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-config-prettier": "^9.0.0",
"eslint-import-resolver-typescript": "^3.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jest": "^26.4.6",
"eslint-plugin-jest-dom": "^4.0.2",
"eslint-plugin-jest": "^27.0.0",
"eslint-plugin-jest-dom": "^5.0.0",
"eslint-plugin-jest-formatting": "^3.1.0",

@@ -81,6 +86,6 @@ "eslint-plugin-no-only-tests": "^3.0.0",

"jest": "^29.0.0",
"jsdoc": "^3.6.10",
"lint-staged": "^13.0.3",
"jsdoc": "^4.0.0",
"lint-staged": "^15.0.0",
"nock": "^13.2.4",
"prettier": "^2.7.1",
"prettier": "^2.8.8",
"pretty-quick": "^3.1.3",

@@ -93,3 +98,3 @@ "rollup": "^2.62.0",

"rollup-plugin-dts": "^4.2.2",
"rollup-plugin-esbuild": "^4.9.1",
"rollup-plugin-esbuild": "^6.0.0",
"rollup-plugin-inject-process-env": "^1.3.1",

@@ -103,9 +108,7 @@ "rollup-plugin-livereload": "^2.0.5",

"dependencies": {
"@descope/core-js-sdk": "0.0.42",
"jose": "4.12.0",
"node-fetch-commonjs": "3.2.4"
},
"peerDependencies": {
"tslib": ">=1.14.1"
"@descope/core-js-sdk": "2.12.0",
"cross-fetch": "^4.0.0",
"jose": "5.2.2",
"tslib": "^2.0.0"
}
}

@@ -18,7 +18,10 @@ # Descope SDK for Node.js

## Setup
## Authentication Functions
A Descope `Project ID` is required to initialize the SDK. Find it on the
[project page in the Descope Console](https://app.descope.com/settings/project).
### Setup
Before you can use authentication functions listed below, you must initialize `descopeClient` to use all of the built-in SDK functions.
You'll need your Descope `Project ID` to create this, and you can find it on the [project page](https://app.descope.com/settings/project) in the Descope Console.
```typescript

@@ -30,9 +33,89 @@ import DescopeClient from '@descope/node-sdk';

## Usage
Once you've created a `descopeClient`, you can use that to work with the following functions:
Here are some examples how to manage and authenticate users:
1. [OTP Authentication](#otp-authentication)
2. [Magic Link](#magic-link)
3. [Enchanted Link](#enchanted-link)
4. [OAuth](#oauth)
5. [SSO/SAML](#ssosaml)
6. [TOTP Authentication](#totp-authentication)
7. [Passwords](#passwords)
8. [Session Validation](#session-validation)
9. [Roles & Permission Validation](#roles--permission-validation)
10. [Logging Out](#logging-out)
## Management Functions
### Setup
Before you can use management functions listed below, you must initialize `descopeClient`.
If you wish to also use management functions, you will need to initialize a new version of your `descopeClient`, but this time with a `ManagementKey` as well as your `Project ID`. Create a management key in the [Descope Console](https://app.descope.com/settings/company/managementkeys).
```typescript
import DescopeClient from '@descope/node-sdk';
const descopeClient = DescopeClient({
projectId: 'my-project-ID',
managementKey: 'management-key',
});
```
Then, you can use that to work with the following functions:
1. [Manage Tenants](#manage-tenants)
2. [Manage Users](#manage-users)
3. [Manage Access Keys](#manage-access-keys)
4. [Manage SSO Setting](#manage-sso-setting)
5. [Manage Permissions](#manage-permissions)
6. [Manage Roles](#manage-roles)
7. [Query SSO Groups](#query-sso-groups)
8. [Manage Flows](#manage-flows)
9. [Manage JWTs](#manage-jwts)
10. [Impersonate](#impersonate)
11. [Embedded Links](#embedded-links)
12. [Audit](#audit)
13. [Manage Authz](#manage-authz)
14. [Manage Project](#manage-project)
15. [Manage SSO applications](#manage-sso-applications)
If you wish to run any of our code samples and play with them, check out our [Code Examples](#code-examples) section.
If you're performing end-to-end testing, check out the [Utils for your end to end (e2e) tests and integration tests](#utils-for-your-end-to-end-e2e-tests-and-integration-tests) section. You will need to use the `descopeClient` you created under the setup of [Management Functions](#management-functions).
---
## Error Handling
Every `async` operation may fail. In case it does, there will be information regarding what happened on the response object.
A typical case of error handling might look something like:
```ts
import { SdkResponse, descopeErrors } from '@descope/node-sdk';
// ...
try {
const resp = await sdk.otp.signIn.email(loginId);
if (resp.error) {
switch (resp.error.errorCode) {
case descopeErrors.userNotFound:
// Handle specifically
break;
default:
// Handle generally
// `resp.error` will contain `errorCode`, `errorDescription` and sometimes `errorMessage` to
// help understand what went wrong. See SdkResponse for more information.
}
}
} catch (e) {
// Handle technical error
}
```
---
### OTP Authentication
Send a user a one-time password (OTP) using your preferred delivery method (_email / SMS_). An email address or phone number must be provided accordingly.
Send a user a one-time password (OTP) using your preferred delivery method (_Email / SMS / Voice call / WhatsApp_). An email address or phone number must be provided accordingly.

@@ -224,2 +307,68 @@ The user can either `sign up`, `sign in` or `sign up or in`

### Passwords
The user can also authenticate with a password, though it's recommended to
prefer passwordless authentication methods if possible. Sign up requires the
caller to provide a valid password that meets all the requirements configured
for the [password authentication method](https://app.descope.com/settings/authentication/password) in the Descope console.
```js
// Every user must have a loginId. All other user information is optional
const loginId = 'desmond@descope.com';
const password = 'qYlvi65KaX';
const user = {
name: 'Desmond Copeland',
email: loginId,
};
const jwtResponse = await descopeClient.password.signUp(loginId, password, user);
// jwtResponse.data.sessionJwt;
// jwtResponse.data.refreshJwt;
```
The user can later sign in using the same loginId and password.
```js
const jwtResponse = await descopeClient.password.signIn(loginId, password);
// jwtResponse.data.sessionJwt;
// jwtResponse.data.refreshJwt;
```
The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)
In case the user needs to update their password, one of two methods are available: Resetting their password or replacing their password
**Changing Passwords**
_NOTE: sendReset will only work if the user has a validated email address. Otherwise password reset prompts cannot be sent._
In the [password authentication method](https://app.descope.com/settings/authentication/password) in the Descope console, it is possible to define which alternative authentication method can be used in order to authenticate the user, in order to reset and update their password.
```js
// Start the reset process by sending a password reset prompt. In this example we'll assume
// that magic link is configured as the reset method. The optional redirect URL is used in the
// same way as in regular magic link authentication.
const loginId = 'desmond@descope.com';
const redirectURL = 'https://myapp.com/password-reset';
const passwordResetResponse = await descopeClient.password.sendReset(loginId, redirectURL);
```
The magic link, in this case, must then be verified like any other magic link (see the [magic link section](#magic-link) for more details). However, after verifying the user, it is expected
to allow them to provide a new password instead of the old one. Since the user is now authenticated, this is possible via:
```js
// The refresh token is required to make sure the user is authenticated.
await descopeClient.password.update(loginId, newPassword, token);
```
`update()` can always be called when the user is authenticated and has a valid session.
Alternatively, it is also possible to replace an existing active password with a new one.
```js
// Replaces the user's current password with a new one
const jwtResponse = await descopeClient.password.replace(loginId, oldPassword, newPassword);
// jwtResponse.data.sessionJwt;
// jwtResponse.data.refreshJwt;
```
### Session Validation

@@ -273,3 +422,3 @@

res.status(401).json({
error: new Error('Unauthorized!'),
error: 'Unauthorized!',
});

@@ -290,7 +439,5 @@ }

// You can validate specific permissions
const validTenantPermissions = await descopeClient.validateTenantPermissions(
authInfo,
'my-tenant-ID',
['Permission to validate'],
);
const validTenantPermissions = descopeClient.validateTenantPermissions(authInfo, 'my-tenant-ID', [
'Permission to validate',
]);
if (!validTenantPermissions) {

@@ -301,3 +448,3 @@ // Deny access

// Or validate roles directly
const validTenantRoles = await descopeClient.validateTenantRoles(authInfo, 'my-tenant-ID', [
const validTenantRoles = descopeClient.validateTenantRoles(authInfo, 'my-tenant-ID', [
'Role to validate',

@@ -308,2 +455,14 @@ ]);

}
// Or get the matched roles/permissions
const matchedTenantRoles = descopeClient.getMatchedTenantRoles(authInfo, 'my-tenant-ID', [
'Role to validate',
'Another role to validate',
]);
const matchedTenantPermissions = descopeClient.getMatchedTenantPermissions(
authInfo,
'my-tenant-ID',
['Permission to validate', 'Another permission to validate'],
);
```

@@ -315,5 +474,3 @@

// You can validate specific permissions
const validPermissions = await descopeClient.validatePermissions(authInfo, [
'Permission to validate',
]);
const validPermissions = descopeClient.validatePermissions(authInfo, ['Permission to validate']);
if (!validPermissions) {

@@ -324,6 +481,17 @@ // Deny access

// Or validate roles directly
const validRoles = await descopeClient.validateRoles(authInfo, ['Role to validate']);
const validRoles = descopeClient.validateRoles(authInfo, ['Role to validate']);
if (!validRoles) {
// Deny access
}
// Or get the matched roles/permissions
const matchedRoles = descopeClient.getMatchedRoles(authInfo, [
'Role to validate',
'Another role to validate',
]);
const matchedPermissions = descopeClient.getMatchedPermissions(authInfo, [
'Permission to validate',
'Another permission to validate',
]);
```

@@ -347,6 +515,6 @@

## Management API
## Management Functions
It is very common for some form of management or automation to be required. These can be performed
using the management API. Please note that these actions are more sensitive as they are administrative
using the management functions. Please note that these actions are more sensitive as they are administrative
in nature. Please use responsibly.

@@ -370,3 +538,3 @@

You can create, update, delete or load tenants:
You can create, update, delete or load tenants, as well as read and update tenant settings:

@@ -376,16 +544,26 @@ ```typescript

// Users logging in to this tenant
await descopeClient.management.tenant.create('My Tenant', ['domain.com']);
await descopeClient.management.tenant.create('My Tenant', ['domain.com'], {
customAttributeName: 'val',
});
// You can optionally set your own ID when creating a tenant
await descopeClient.management.tenant.createWithId('my-custom-id', 'My Tenant', ['domain.com']);
await descopeClient.management.tenant.createWithId('my-custom-id', 'My Tenant', ['domain.com'], {
customAttributeName: 'val',
});
// Update will override all fields as is. Use carefully.
await descopeClient.management.tenant.update('my-custom-id', 'My Tenant', [
'domain.com',
'another-domain.com',
]);
await descopeClient.management.tenant.update(
'my-custom-id',
'My Tenant',
['domain.com', 'another-domain.com'],
{ customAttributeName: 'val' },
);
// Tenant deletion cannot be undone. Use carefully.
await descopeClient.management.tenant.delete('my-custom-id');
// Pass true to cascade value, in case you want to delete all users/keys associated only with this tenant
await descopeClient.management.tenant.delete('my-custom-id', false);
// Load tenant by id
const tenant = await descopeClient.management.tenant.load('my-custom-id');
// Load all tenants

@@ -396,4 +574,106 @@ const tenantsRes = await descopeClient.management.tenant.loadAll();

});
// Search all tenants according to various parameters
const searchRes = await descopeClient.management.tenant.searchAll(['id']);
searchRes.data.forEach((tenant) => {
// do something
});
// Load tenant settings by id
const tenantSettings = await descopeClient.management.tenant.getSettings('my-tenant-id');
// Update will override all fields as is. Use carefully.
await descopeClient.management.tenant.configureSettings('my-tenant-id', {
domains: ['domain1.com'],
selfProvisioningDomains: ['domain1.com'],
sessionSettingsEnabled: true,
refreshTokenExpiration: 12,
refreshTokenExpirationUnit: 'days',
sessionTokenExpiration: 10,
sessionTokenExpirationUnit: 'minutes',
enableInactivity: true,
JITDisabled: false,
InactivityTime: 10,
InactivityTimeUnit: 'minutes',
});
```
### Manage Password
You can read and update any tenant password settings and policy:
```typescript
// Load tenant password settings by id
const passwordSettings = await descopeClient.management.password.getSettings('my-tenant-id');
// Update will override all fields as is. Use carefully.
await descopeClient.management.password.configureSettings('my-tenant-id', {
enabled: true,
minLength: 8,
expiration: true,
expirationWeeks: 4,
lock: true,
lockAttempts: 5,
reuse: true,
reuseAmount: 6,
lowercase: true,
uppercase: false,
number: true,
nonAlphaNumeric: false,
});
```
### Manage SSO applications
You can create, update, delete or load SSO applications:
```typescript
// Create OIDC sso application
await descopeClient.management.ssoApplication.createOidcApplication({
name: 'My OIDC app name',
loginPageUrl: 'http://dummy.com/login',
});
// Create SAML sso application
await descopeClient.management.ssoApplication.createSamlApplication({
name: 'My SAML app name',
loginPageUrl: 'http://dummy.com/login',
useMetadataInfo: true,
metadataUrl: 'http://dummy.com/metadata',
});
// Update OIDC sso application.
// Update will override all fields as is. Use carefully.
await descopeClient.management.ssoApplication.updateOidcApplication({
id: 'my-app-id',
name: 'My OIDC app name',
loginPageUrl: 'http://dummy.com/login',
});
// Update SAML sso application.
// Update will override all fields as is. Use carefully.
await descopeClient.management.ssoApplication.updateSamlApplication({
id: 'my-app-id',
name: 'My SAML app name',
loginPageUrl: 'http://dummy.com/login',
enabled: true,
useMetadataInfo: false,
entityId: 'entity1234',
aceUrl: 'http://dummy.com/acs',
certificate: 'certificate',
});
// Tenant deletion cannot be undone. Use carefully.
await descopeClient.management.ssoApplication.delete('my-app-id');
// Load sso application by id
const app = await descopeClient.management.ssoApplication.load('my-app-id');
// Load all sso applications
const appsRes = await descopeClient.management.ssoApplication.loadAll();
appsRes.data.forEach((app) => {
// do something
});
```
### Manage Users

@@ -407,35 +687,55 @@

// on a per-tenant basis.
await descopeClient.management.user.create(
'desmond@descope.com',
'desmond@descope.com',
null,
'Desmond Copeland',
null,
[{ tenantId: 'tenant-ID1', roleNames: ['role-name1'] }],
);
await descopeClient.management.user.create('desmond@descope.com', {
email: 'desmond@descope.com',
displayName: 'Desmond Copeland',
userTenants: [{ tenantId: 'tenant-ID1', roleNames: ['role-name1'] }],
});
// Alternatively, a user can be created and invited via an email message.
// Alternatively, a user can be created and invited via an email / text message.
// Make sure to configure the invite URL in the Descope console prior to using this function,
// and that an email address is provided in the information.
await descopeClient.management.user.invite(
'desmond@descope.com',
'desmond@descope.com',
null,
'Desmond Copeland',
null,
[{ tenantId: 'tenant-ID1', roleNames: ['role-name1'] }],
// and that an email address / phone number is provided in the information.
await descopeClient.management.user.invite('desmond@descope.com', {
email: 'desmond@descope.com',
displayName: 'Desmond Copeland',
userTenants: [{ tenantId: 'tenant-ID1', roleNames: ['role-name1'] }],
// You can inject custom data into the template.
// Note that you first need to configure custom template in Descope Console
// For example: configure {{options_k1}} in the custom template, and pass { k1: 'v1' } as templateOptions
templateOptions: { k1: 'v1', k2: 'v2' },
});
// You can invite batch of users via an email / text message.
// Make sure to configure the invite URL in the Descope console prior to using this function,
// and that an email address / phone number is provided in the information. You can also set
// a cleartext password or import a prehashed one from another service.
await descopeClient.management.user.inviteBatch(
[
{
loginId: 'desmond@descope.com',
email: 'desmond@descope.com',
phone: '+123456789123',
displayName: 'Desmond Copeland',
userTenants: [{ tenantId: 'tenant-ID1', roleNames: ['role-name1'] }],
hashedPassword: {
bcrypt: {
hash: '$2a$...',
},
},
},
],
'<invite_url>',
true,
false,
);
// Update will override all fields as is. Use carefully.
await descopeClient.management.user.update(
'desmond@descope.com',
'desmond@descope.com',
null,
'Desmond Copeland',
null,
[{ tenantId: 'tenant-ID1', roleNames: ['role-name1', 'role-name2'] }],
);
await descopeClient.management.user.update('desmond@descope.com', {
email: 'desmond@descope.com',
displayName: 'Desmond Copeland',
userTenants: [{ tenantId: 'tenant-ID1', roleNames: ['role-name1'] }],
});
// Update explicit data for a user rather than overriding all fields
await descopeClient.management.user.updatePhone('desmond@descope.com', '+18005551234', true);
await descopeClient.management.user.updateLoginId('desmond@descope.com', 'bane@descope.com');
await descopeClient.management.user.removeTenantRoles(

@@ -458,8 +758,61 @@ 'desmond@descope.com',

// Results can be paginated using the limit and page parameters
const usersRes = await descopeClient.management.user.searchAll(['tenant-ID']);
const usersRes = await descopeClient.management.user.search({ tenantIds: ['tenant-ID'] });
usersRes.data.forEach((user) => {
// do something
});
await descopeClient.management.user.logoutUser('my-custom-id');
await descopeClient.management.user.logoutUserByUserId('<user-ID>');
// Get users' authentication history
const userIds = ['user-id-1', 'user-id-2'];
const usersHistoryRes = await descopeClient.management.user.history(userIds);
usersHistoryRes.forEach((userHistory) => {
// do something
});
```
#### Set or Expire User Password
You can set a new active password for a user that they can sign in with.
You can also set a temporary password that they user will be forced to change on the next login.
For a user that already has an active password, you can expire their current password, effectively requiring them to change it on the next login.
```typescript
// Set a user's temporary password
await descopeClient.management.user.setTemporaryPassword('<login-ID>', '<some-password>');
// Set a user's password
await descopeClient.management.user.setActivePassword('<login-ID>', '<some-password>');
// Or alternatively, expire a user password
await descopeClient.management.user.expirePassword('<login-ID>');
```
### Manage Project
You can update project name, as well as to clone the current project to a new one:
```typescript
// Update will override all fields as is. Use carefully.
await descopeClient.management.project.updateName('new-project-name');
// Clone the current project to a new one
// Note that this action is supported only with a pro license or above.
const cloneRes = await descopeClient.management.project.clone('new-project-name');
```
You can manage your project's settings and configurations by exporting your
project's environment. You can also import previously exported data into
the same project or a different one.
```typescript
// Exports the current state of the project
const files = await descopeClient.management.project.export();
// Import the previously exported data into the current project
await descopeClient.management.project.import(files);
```
### Manage Access Keys

@@ -473,2 +826,4 @@

// on a per-tenant basis.
// If userId is supplied, then authorization will be ignored, and the access key will be bound to the user's authorization.
// If customClaims is supplied, then those claims will be present in the JWT returned by calls to ExchangeAccessKey.
await descopeClient.management.accessKey.create(

@@ -508,2 +863,5 @@ 'key-name',

```typescript
// You can get SSO settings for a specific tenant ID
const ssoSettings = await descopeClient.management.sso.loadSettings("tenant-id")
// You can configure SSO settings manually by setting the required fields directly

@@ -514,9 +872,15 @@ const tenantId = 'tenant-id' // Which tenant this configuration is for

const idpCert = '<your-cert-here>'
const redirectURL = 'https://my-app.com/handle-saml' // Global redirect URL for SSO/SAML
const domain = 'tenant-users.com' // Users authentication with this domain will be logged in to this tenant
await descopeClient.management.sso.configureSettings(tenantID, idpURL, entityID, idpCert, redirectURL, domain)
const redirectURL = 'https://my-app.com/handle-sso' // Global redirect URL for SSO/SAML
const domains = ['tenant-users.com'] // Users authentication with this domain will be logged in to this tenant
await descopeClient.management.sso.configureSAMLSettings(tenantID, {idpURL, entityID, idpCert}, redirectURL, domains)
// Alternatively, configure using an SSO metadata URL
await descopeClient.management.sso.configureMetadata(tenantID, 'https://idp.com/my-idp-metadata')
await descopeClient.management.sso.configureSAMLByMetadata(tenantID, {idpMetadataUrl: 'https://idp.com/my-idp-metadata'}, redirectURL, domains)
// In case SSO is configured to work with OIDC use the following
const name = 'some-name';
const clientId = 'client id of OIDC';
const clientSecret = 'client secret';
await descopeClient.management.sso.configureOIDCSettings(tenantID, {name, clientId, clientSecret, redirectUrl}, domains)
// Map IDP groups to Descope roles, or map user attributes.

@@ -526,3 +890,3 @@ // This function overrides any previous mapping (even when empty). Use carefully.

tenantId,
{ groups: ['IDP_ADMIN'], role: 'Tenant Admin'}
[{ groups: ['IDP_ADMIN'], roleName: 'Tenant Admin'}]
{ name: 'IDP_NAME', phoneNumber: 'IDP_PHONE'},

@@ -540,2 +904,5 @@ )

// You can delete SSO settings for a specific tenant ID
await descopeClient.management.sso.deleteSettings("tenant-id")
### Manage Permissions

@@ -572,6 +939,8 @@

// You can optionally set a description and associated permission for a roles.
// The optional `tenantId` will scope this role for a specific tenant. If left empty, the role will be available to all tenants.
const name = 'My Role';
const tenantId = '<tenant id>';
let description = 'Optional description to briefly explain what this role allows.';
const permissionNames = ['My Updated Permission'];
descopeClient.management.role.create(name, description, permissionNames);
descopeClient.management.role.create(name, description, permissionNames, tenantId);

@@ -582,6 +951,6 @@ // Update will override all fields as is. Use carefully.

permissionNames.push('Another Permission');
descopeClient.management.role.update(name, newName, description, permissionNames);
descopeClient.management.role.update(name, newName, description, permissionNames, tenantId);
// Role deletion cannot be undone. Use carefully.
descopeClient.management.role.delete(newName);
descopeClient.management.role.delete(newName, tenantId);

@@ -593,2 +962,11 @@ // Load all roles

});
// Search roles
const rolesRes = await descopeClient.management.role.search({
tenantIds: ['t1', 't2'],
roleNames: ['role1'],
});
rolesRes.data.forEach((role) => {
// do something
});
```

@@ -625,2 +1003,41 @@

### Manage Flows
You can list your flows and also import and export flows and screens, or the project theme:
```typescript
// List all project flows
const res = await descopeClient.management.flow.list();
console.log('found total flows', res.total);
res.flows.forEach((flowMetadata) => {
// do something
});
// Delete flows by ids
await descopeClient.management.flow.delete(['flow-1', 'flow-2']);
// Export the flow and it's matching screens based on the given id
const res = await descopeClient.management.flow.export('sign-up');
console.log('found flow', res.data.flow);
res.data.screens.forEach((screen) => {
// do something
});
// Import the given flow and screens as the given id
const { flow, screens } = res.data;
const updatedRes = descopeClient.management.flow.import('sign-up', flow, screens);
console.log('updated flow', updatedRes.data.flow);
updatedRes.data.screens.forEach((screen) => {
// do something
});
// Export the current theme of the project
const res = descopeClient.management.theme.export();
console.log(res.data.theme);
// Import the given theme to the project
const updatedRes = descopeClient.management.theme.import(theme);
console.log(updatedRes.data.theme);
```
### Manage JWTs

@@ -637,5 +1054,287 @@

### Impersonate
You can impersonate to another user
The impersonator user must have the `impersonation` permission in order for this request to work.
The response would be a refresh JWT of the impersonated user
```typescript
const updatedJWTRes = await descopeClient.management.jwt.impersonate(
'impersonator-id',
'login-id',
true,
);
```
Note 1: The generate code/link functions, work only for test users, will not work for regular users.
Note 2: In case of testing sign-in / sign-up operations with test users, need to make sure to generate the code prior calling the sign-in / sign-up operations.
### Embedded Links
Embedded links can be created to directly receive a verifiable token without sending it.
This token can then be verified using the magic link 'verify' function, either directly or through a flow.
```typescript
const { token } = await descopeClient.management.user.generateEmbeddedLink('desmond@descope.com', {
key1: 'value1',
});
```
### Audit
You can perform an audit search for either specific values or full-text across the fields. Audit search is limited to the last 30 days.
```typescript
// Full text search on the last 10 days
const audits = await descopeClient.management.audit.search({
from: Date.now() - 10 * 24 * 60 * 60 * 1000,
text: 'some-text',
});
console.log(audits);
// Search successful logins in the last 30 days
const audits = await descopeClient.management.audit.search({ actions: ['LoginSucceed'] });
console.log(audits);
```
You can also create audit event with data
```typescript
await descopeClient.management.audit.createEvent({
action: 'pencil.created',
type: 'info', // info/warn/error
actorId: 'UXXX',
tenantId: 'tenant-id',
data: {
some: 'data',
},
});
```
### Manage Authz
Descope support full relation based access control (ReBAC) using a zanzibar like schema and operations.
A schema is comprized of namespaces (entities like documents, folders, orgs, etc.) and each namespace has relation definitions to define relations.
Each relation definition can be simple (either you have it or not) or complex (union of nodes).
A simple example for a file system like schema would be:
```yaml
# Example schema for the authz tests
name: Files
namespaces:
- name: org
relationDefinitions:
- name: parent
- name: member
complexDefinition:
nType: union
children:
- nType: child
expression:
neType: self
- nType: child
expression:
neType: relationLeft
relationDefinition: parent
relationDefinitionNamespace: org
targetRelationDefinition: member
targetRelationDefinitionNamespace: org
- name: folder
relationDefinitions:
- name: parent
- name: owner
complexDefinition:
nType: union
children:
- nType: child
expression:
neType: self
- nType: child
expression:
neType: relationRight
relationDefinition: parent
relationDefinitionNamespace: folder
targetRelationDefinition: owner
targetRelationDefinitionNamespace: folder
- name: editor
complexDefinition:
nType: union
children:
- nType: child
expression:
neType: self
- nType: child
expression:
neType: relationRight
relationDefinition: parent
relationDefinitionNamespace: folder
targetRelationDefinition: editor
targetRelationDefinitionNamespace: folder
- nType: child
expression:
neType: targetSet
targetRelationDefinition: owner
targetRelationDefinitionNamespace: folder
- name: viewer
complexDefinition:
nType: union
children:
- nType: child
expression:
neType: self
- nType: child
expression:
neType: relationRight
relationDefinition: parent
relationDefinitionNamespace: folder
targetRelationDefinition: viewer
targetRelationDefinitionNamespace: folder
- nType: child
expression:
neType: targetSet
targetRelationDefinition: editor
targetRelationDefinitionNamespace: folder
- name: doc
relationDefinitions:
- name: parent
- name: owner
complexDefinition:
nType: union
children:
- nType: child
expression:
neType: self
- nType: child
expression:
neType: relationRight
relationDefinition: parent
relationDefinitionNamespace: doc
targetRelationDefinition: owner
targetRelationDefinitionNamespace: folder
- name: editor
complexDefinition:
nType: union
children:
- nType: child
expression:
neType: self
- nType: child
expression:
neType: relationRight
relationDefinition: parent
relationDefinitionNamespace: doc
targetRelationDefinition: editor
targetRelationDefinitionNamespace: folder
- nType: child
expression:
neType: targetSet
targetRelationDefinition: owner
targetRelationDefinitionNamespace: doc
- name: viewer
complexDefinition:
nType: union
children:
- nType: child
expression:
neType: self
- nType: child
expression:
neType: relationRight
relationDefinition: parent
relationDefinitionNamespace: doc
targetRelationDefinition: viewer
targetRelationDefinitionNamespace: folder
- nType: child
expression:
neType: targetSet
targetRelationDefinition: editor
targetRelationDefinitionNamespace: doc
```
Descope SDK allows you to fully manage the schema and relations as well as perform simple (and not so simple) checks regarding the existence of relations.
```typescript
// Load the existing schema
const s = await descopeClient.management.authz.loadSchema();
console.log(s);
// Save schema and make sure to remove all namespaces not listed
await descopeClient.management.authz.saveSchema(s, true);
// Create a relation between a resource and user
await descopeClient.management.authz.createRelations([
{
resource: 'some-doc',
relationDefinition: 'owner',
namespace: 'doc',
target: 'u1',
},
{
resource: 'some-doc',
relationDefinition: 'editor',
namespace: 'doc',
target: 'u2',
},
]);
// Check if target has the relevant relation
// The answer should be true because an owner is also a viewer
const q = await descopeClient.management.authz.hasRelations([
{
resource: 'some-doc',
relationDefinition: 'viewer',
namespace: 'doc',
target: 'u1',
},
]);
```
### Utils for your end to end (e2e) tests and integration tests
To ease your e2e tests, we exposed dedicated management methods,
that way, you don't need to use 3rd party messaging services in order to receive sign-in/up Email, SMS, Voice call or WhatsApp, and avoid the need of parsing the code and token from them.
```typescript
// User for test can be created, this user will be able to generate code/link without
// the need of 3rd party messaging services.
// Test user must have a loginId, other fields are optional.
// Roles should be set directly if no tenants exist, otherwise set
// on a per-tenant basis.
await descopeClient.management.user.createTestUser('desmond@descope.com', {
email: 'desmond@descope.com',
displayName: 'Desmond Copeland',
userTenants: [{ tenantId: 'tenant-ID1', roleNames: ['role-name1'] }],
});
// Now test user got created, and this user will be available until you delete it,
// you can use any management operation for test user CRUD.
// You can also delete all test users.
await descopeClient.management.user.deleteAllTestUsers();
// OTP code can be generated for test user, for example:
const { code } = await descopeClient.management.user.generateOTPForTestUser(
'sms', // you can use also 'email', 'whatsapp', 'voice'
'desmond@descope.com',
);
// Now you can verify the code is valid (using descopeClient.auth.*.verify for example)
// LoginOptions can be provided to set custom claims to the generated jwt.
// Same as OTP, magic link can be generated for test user, for example:
const { link } = await descopeClient.management.user.generateMagicLinkForTestUser(
'email',
'desmond@descope.com',
'',
);
// Enchanted link can be generated for test user, for example:
const { link, pendingRef } = await descopeClient.management.user.generateEnchantedLinkForTestUser(
'desmond@descope.com',
'',
);
```
## Code Examples
You can find various usage examples in the [examples folder](https://github.com/descope/node-sdk/blob/main/examples).
You can find various usage examples in the [examples folder](/examples).

@@ -679,2 +1378,23 @@ ### Setup

## Providing Custom Public Key
By default, the SDK will download the public key from Descope's servers. You can also provide your own public key. This is useful when the server you are running the SDK on does not have access to the internet.
You can find your public key in the `https://api.descope.com/v2/keys/<project-id>` endpoint. For further information, please see the [Descope Documentation and API reference page](https://docs.descope.com/api/openapi/sessiongetkeys/operation/GetKeysV2).
To provide your own public key, you can do so by providing the `publicKey` option when initializing the SDK:
```typescript
import DescopeClient from '@descope/node-sdk';
const descopeClient = DescopeClient({
projectId: 'my-project-ID',
publicKey: '{"alg":"RS256", ... }',
});
// The public key will be used when validating jwt
const sessionJWt = '<session-jwt>';
await descopeClient.validateJwt(sessionJWt);
```
## Learn More

@@ -681,0 +1401,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc