@descope/vue-sdk 0.0.0-next-fe60cdb6-20230614 → 0.0.0-next-46dc962a-20230629

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,7 @@
1
- # Descope SDK for Vue
1
+ # Descope Vue SDK
2
2
 
3
- The Descope SDK for Vue provides convenient access to the Descope for an application written on top of Vue. You can read more on the [Descope Website](https://descope.com).
3
+ The Descope Vue SDK provides convenient access to the Descope for an application written on top of Vue.
4
+ You can read more on the [Descope Website](https://descope.com).
4
5
 
5
6
  ## Requirements
6
7
 
@@ -17,9 +18,7 @@ npm i --save @descope/vue-sdk
17
18
 
18
19
  ## Usage
19
20
 
20
- ### Render it in your application
21
-
22
- #### Add Descope plugin to your application
21
+ ### Add Descope plugin to your application
23
22
 
24
23
  ```js
25
24
  import { createApp } from 'vue';
@@ -37,7 +36,7 @@ app.use(descope, {
37
36
  app.mount('#app');
38
37
  ```
39
38
 
40
- #### Use Descope to render specific flow
39
+ ### Use Descope to render specific flow
41
40
 
42
41
  ```js
43
42
  <template>
@@ -61,7 +60,7 @@ const handleSuccess = (e) => {
61
60
  </script>
62
61
  ```
63
62
 
64
- #### Use the `useDescope`, `useSession` and `useUser` functions in your components in order to get authentication state, user details and utilities
63
+ ### Use the `useDescope`, `useSession` and `useUser` functions in your components in order to get authentication state, user details and utilities
65
64
 
66
65
  This can be helpful to implement application-specific logic. Examples:
67
66
 
@@ -94,7 +93,100 @@ Note: `useSession` triggers a single request to the Descope backend to attempt t
94
93
 
95
94
  **For more SDK usage examples refer to [docs](https://docs.descope.com/build/guides/client_sdks/)**
96
95
 
97
- #### Refresh token lifecycle
96
+ ### Session token server validation (pass session token to server API)
97
+
98
+ When developing a full-stack application, it is common to have private server API which requires a valid session token:
99
+
100
+ ![session-token-validation-diagram](https://docs.descope.com/static/SessionValidation-cf7b2d5d26594f96421d894273a713d8.png)
101
+
102
+ Note: Descope also provides server-side SDKs in various languages (NodeJS, Go, Python, etc). Descope's server SDKs have out-of-the-box session validation API that supports the options described bellow. To read more about session validation, Read [this section](https://docs.descope.com/build/guides/gettingstarted/#session-validation) in Descope documentation.
103
+
104
+ There are 2 ways to achieve that:
105
+
106
+ 1. Using `getSessionToken` to get the token, and pass it on the `Authorization` Header (Recommended)
107
+ 2. Passing `sessionTokenViaCookie` boolean option when initializing the plugin (Use cautiously, session token may grow, especially in cases of using authorization, or adding custom claim)
108
+
109
+ #### 1. Using `getSessionToken` to get the token
110
+
111
+ An example for api function, and passing the token on the `Authorization` header:
112
+
113
+ ```js
114
+ import { getSessionToken } from '@descope/vue-sdk';
115
+
116
+ // fetch data using back
117
+ // Note: Descope backend SDKs support extracting session token from the Authorization header
118
+ export const fetchData = async () => {
119
+ const sessionToken = getSessionToken();
120
+ const res = await fetch('/path/to/server/api', {
121
+ headers: {
122
+ Authorization: `Bearer ${sessionToken}`
123
+ }
124
+ });
125
+ // ... use res
126
+ };
127
+ ```
128
+
129
+ #### 2. Passing `sessionTokenViaCookie` option when initializing the plugin
130
+
131
+ When doing so, Descope SDK will automatically store session token on the `DS` cookie.
132
+
133
+ Note: Use this option if session token will stay small (less than 1k). Session token can grow, especially in cases of using authorization, or adding custom claims
134
+
135
+ Example:
136
+
137
+ ```js
138
+ import { createApp } from 'vue';
139
+ import App from './components/App.vue';
140
+ import descope from '@descope/vue-sdk';
141
+
142
+ const app = createApp(App);
143
+
144
+ app.use(descope, {
145
+ projectId: 'project-id',
146
+ sessionTokenViaCookie: true
147
+ });
148
+ ```
149
+
150
+ Now, whenever you call `fetch`, the cookie will automatically be sent with the request.
151
+ Descope backend SDKs also support extracting the token from the `DS` cookie.
152
+
153
+ ### Get the Descope SDK instance
154
+
155
+ In case you need the SDK instance outside the Vue application, you can use the `getSdk` function
156
+
157
+ **Make sure to call it only after initializing the descope plugin, this is where the SDK instance is actually created, otherwise you will no instance.**
158
+
159
+ For example:
160
+
161
+ ```js
162
+ import { createApp } from 'vue';
163
+ import App from './components/App.vue';
164
+ import descope, { getSdk } from '../src';
165
+
166
+ const app = createApp(App);
167
+
168
+ app.use(descope, {
169
+ projectId: 'project-id'
170
+ });
171
+
172
+ const sdk = getSdk();
173
+
174
+ sdk?.onSessionTokenChange((newSession) => {
175
+ // here you can implement custom logic when the session is changing
176
+ });
177
+ ```
178
+
179
+ ### Helper Functions
180
+
181
+ You can also use the following functions to assist with various actions managing your JWT.
182
+
183
+ `getSessionToken()` - Get current session token.
184
+ `getRefreshToken()` - Get current refresh token.
185
+ `refresh(token = getRefreshToken())` - Force a refresh on current session token using an existing valid refresh token.
186
+ `getJwtRoles(token = getSessionToken(), tenant = '')` - Get current roles from an existing session token. Provide tenant id for specific tenant roles.
187
+ `getJwtPermissions(token = getSessionToken(), tenant = '')` - Fet current permissions from an existing session token. Provide tenant id for specific tenant permissions.
188
+
189
+ ### Refresh token lifecycle
98
190
 
99
191
  Descope SDK is automatically refreshes the session token when it is about to expire. This is done in the background using the refresh token, without any additional configuration.
100
192
 
@@ -103,7 +195,7 @@ you must also configure a custom domain, and set it as the `baseUrl` to the `des
103
195
 
104
196
  ## Code Example
105
197
 
106
- You can find an example Vue app in the [examples folder](./example).
198
+ You can find an example Vue app in the [example folder](./example).
107
199
 
108
200
  ### Setup
109
201
 
@@ -130,11 +222,10 @@ npm i && npm start
130
222
 
131
223
  See the following table for customization environment variables for the example app:
132
224
 
133
- | Env Variable | Description | Default value |
134
- | ------------ | ----------- | ------------- |
135
-
136
- | VUE_APP_DESCOPE_FLOW_ID | Which flow ID to use in the login page | **sign-up-or-in** |
137
- | VUE_APP_DESCOPE_BASE_URL | Custom Descope base URL | None |
225
+ | Env Variable | Description | Default value |
226
+ | ------------------------ | -------------------------------------- | ----------------- |
227
+ | VUE_APP_DESCOPE_FLOW_ID | Which flow ID to use in the login page | **sign-up-or-in** |
228
+ | VUE_APP_DESCOPE_BASE_URL | Custom Descope base URL | None |
138
229
 
139
230
  Example for `.env.local` file template:
140
231
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@descope/web-component"),s=require("vue"),o=require("@descope/web-js-sdk");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t=r(e),n=r(o);const u=Symbol("$descope"),a={"x-descope-sdk-name":"vue","x-descope-sdk-version":"0.0.0-next-fe60cdb6-20230614"},i=()=>{const e=s.inject(u);if(!e)throw Error("Missing Descope context, make sure you are using the Descope plugin");return e},l=()=>i().sdk;t.default.sdkConfigOverrides={baseHeaders:a};var c={name:"Descope",props:{flowId:{type:String,required:!0},tenant:{type:String},theme:{type:String},debug:{type:Boolean},telemetryKey:{type:String},redirectUrl:{type:String},autoFocus:{type:Boolean}},emits:["success","error"],setup(e,{emit:s}){const{projectId:o,baseUrl:r,sessionTokenViaCookie:t}=i().options,n=l();return{projectId:o,baseUrl:r,sessionTokenViaCookie:t,onSuccess:async e=>{s("success",e),await(n.httpClient.hooks?.afterRequest?.({},new Response(JSON.stringify(e.detail))))},onError:e=>s("error",e)}}};const d=["project-id","base-url","flow-id","^theme","^tenant","^debug","^telemetryKey","redirect-url","auto-focus"];c.render=function(e,o,r,t,n,u){return s.openBlock(),s.createElementBlock("div",null,[s.createElementVNode("descope-wc",{"project-id":t.projectId,"base-url":t.baseUrl,"flow-id":r.flowId,"^theme":r.theme,"^tenant":r.tenant,"^debug":r.debug,"^telemetryKey":r.telemetryKey,"redirect-url":r.redirectUrl,"auto-focus":r.autoFocus,onSuccess:o[0]||(o[0]=(...e)=>t.onSuccess&&t.onSuccess(...e)),onError:o[1]||(o[1]=(...e)=>t.onError&&t.onError(...e))},null,40,d)])},c.__file="src/Descope.vue";const p=s.ref(null);var v={install:function(e,o){const r=n.default({persistTokens:!0,autoRefresh:!0,baseHeaders:a,...o}),t=s.ref(null),i=s.ref(""),l=s.ref(null),c=s.ref(null);r.onSessionTokenChange((e=>{i.value=e})),r.onUserChange((e=>{c.value=e}));const d=async()=>{t.value=!0,await r.refresh(),t.value=!1},v=s.computed((()=>null===t.value)),f=s.computed((()=>null===l.value));p.value=async()=>(!i.value&&v.value&&await d(),!!s.unref(i)),e.provide(u,{session:{fetchSession:d,isLoading:s.readonly(t),session:s.readonly(i),isFetchSessionWasNeverCalled:v},user:{fetchUser:async()=>{l.value=!0,await r.me(),l.value=!1},isLoading:s.readonly(l),user:s.readonly(c),isFetchUserWasNeverCalled:f},sdk:r,options:o})}};exports.Descope=c,exports.default=v,exports.routeGuard=()=>s.unref(p)?.(),exports.useDescope=l,exports.useSession=()=>{const{session:e}=i();return e.isFetchSessionWasNeverCalled.value&&e.fetchSession(),{isLoading:s.computed((()=>e.isLoading.value||e.isFetchSessionWasNeverCalled.value)),sessionToken:e.session,isAuthenticated:s.computed((()=>!!e.session.value))}},exports.useUser=()=>{const{user:e,session:o}=i(),r=()=>{!e.user.value&&o.session.value&&e.fetchUser()};return r(),s.watch(o.session,r),{isLoading:s.computed((()=>e.isLoading.value||e.isFetchUserWasNeverCalled.value)),user:e.user}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@descope/web-component"),s=require("vue"),o=require("@descope/web-js-sdk");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(e),n=t(o);const i=Symbol("$descope"),u={"x-descope-sdk-name":"vue","x-descope-sdk-version":"0.0.0-next-46dc962a-20230629"},a="undefined"!=typeof window,l=()=>{const e=s.inject(i);if(!e)throw Error("Missing Descope context, make sure you are using the Descope plugin");return e},c=()=>l().sdk;r.default.sdkConfigOverrides={baseHeaders:u};var d={name:"Descope",props:{flowId:{type:String,required:!0},tenant:{type:String},theme:{type:String},debug:{type:Boolean},telemetryKey:{type:String},redirectUrl:{type:String},autoFocus:{type:Boolean}},emits:["success","error"],setup(e,{emit:s}){const{projectId:o,baseUrl:t,sessionTokenViaCookie:r}=l().options,n=c();return{projectId:o,baseUrl:t,sessionTokenViaCookie:r,onSuccess:async e=>{s("success",e),await(n.httpClient.hooks?.afterRequest?.({},new Response(JSON.stringify(e.detail))))},onError:e=>s("error",e)}}};const p=["project-id","base-url","flow-id","^theme","^tenant","^debug","^telemetryKey","redirect-url","auto-focus"];d.render=function(e,o,t,r,n,i){return s.openBlock(),s.createElementBlock("div",null,[s.createElementVNode("descope-wc",{"project-id":r.projectId,"base-url":r.baseUrl,"flow-id":t.flowId,"^theme":t.theme,"^tenant":t.tenant,"^debug":t.debug,"^telemetryKey":t.telemetryKey,"redirect-url":t.redirectUrl,"auto-focus":t.autoFocus,onSuccess:o[0]||(o[0]=(...e)=>r.onSuccess&&r.onSuccess(...e)),onError:o[1]||(o[1]=(...e)=>r.onError&&r.onError(...e))},null,40,p)])},d.__file="src/Descope.vue";const f=e=>(...s)=>{let o;try{o=e(...s)}catch(e){console.error(e)}return o};let v;const g=e=>{const s=n.default({...e,persistTokens:a,autoRefresh:a});return v=s,s};v=g({projectId:"temp pid"});const y=()=>a?v?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),h=f(((e=y(),s)=>v?.getJwtPermissions(e,s))),m=f(((e=y(),s)=>v?.getJwtRoles(e,s))),k=s.ref(null);let S;var w={install:function(e,o){const t=g({...o,persistTokens:!0,autoRefresh:!0,baseHeaders:u});S=t;const r=s.ref(null),n=s.ref(""),a=s.ref(null),l=s.ref(null);t.onSessionTokenChange((e=>{n.value=e})),t.onUserChange((e=>{l.value=e}));const c=async()=>{r.value=!0,await t.refresh(),r.value=!1},d=s.computed((()=>null===r.value)),p=s.computed((()=>null===a.value));k.value=async()=>(!n.value&&d.value&&await c(),!!s.unref(n)),e.provide(i,{session:{fetchSession:c,isLoading:s.readonly(r),session:s.readonly(n),isFetchSessionWasNeverCalled:d},user:{fetchUser:async()=>{a.value=!0,await t.me(),a.value=!1},isLoading:s.readonly(a),user:s.readonly(l),isFetchUserWasNeverCalled:p},sdk:t,options:o})}};exports.Descope=d,exports.default=w,exports.getJwtPermissions=h,exports.getJwtRoles=m,exports.getRefreshToken=()=>a?v?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),exports.getSdk=()=>S,exports.getSessionToken=y,exports.routeGuard=()=>s.unref(k)?.(),exports.useDescope=c,exports.useSession=()=>{const{session:e}=l();return e.isFetchSessionWasNeverCalled.value&&e.fetchSession(),{isLoading:s.computed((()=>e.isLoading.value||e.isFetchSessionWasNeverCalled.value)),sessionToken:e.session,isAuthenticated:s.computed((()=>!!e.session.value))}},exports.useUser=()=>{const{user:e,session:o}=l(),t=()=>{!e.user.value&&o.session.value&&e.fetchUser()};return t(),s.watch(o.session,t),{isLoading:s.computed((()=>e.isLoading.value||e.isFetchUserWasNeverCalled.value)),user:e.user}};
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/Descope.vue?vue&type=template&id=8a031dec&lang.js"],"sourcesContent":["<template>\n\t<div>\n\t\t<descope-wc\n\t\t\t:project-id=\"projectId\"\n\t\t\t:base-url=\"baseUrl\"\n\t\t\t:flow-id=\"flowId\"\n\t\t\t:theme.attr=\"theme\"\n\t\t\t:tenant.attr=\"tenant\"\n\t\t\t:debug.attr=\"debug\"\n\t\t\t:telemetryKey.attr=\"telemetryKey\"\n\t\t\t:redirect-url=\"redirectUrl\"\n\t\t\t:auto-focus=\"autoFocus\"\n\t\t\t@success=\"onSuccess\"\n\t\t\t@error=\"onError\"\n\t\t/>\n\t</div>\n</template>\n\n<script lang=\"ts\">\nimport DescopeWc from '@descope/web-component';\nimport { useOptions, useDescope } from './hooks';\nimport { baseHeaders } from './constants';\nimport { RequestConfig } from '@descope/core-js-sdk';\nimport { SetupContext } from 'vue';\n\nDescopeWc.sdkConfigOverrides = { baseHeaders };\n\nexport default {\n\t// eslint-disable-next-line vue/multi-word-component-names\n\tname: 'Descope',\n\tprops: {\n\t\tflowId: {\n\t\t\ttype: String,\n\t\t\trequired: true\n\t\t},\n\t\ttenant: {\n\t\t\ttype: String\n\t\t},\n\t\ttheme: {\n\t\t\ttype: String\n\t\t},\n\t\tdebug: {\n\t\t\ttype: Boolean\n\t\t},\n\t\ttelemetryKey: {\n\t\t\ttype: String\n\t\t},\n\t\tredirectUrl: {\n\t\t\ttype: String\n\t\t},\n\t\tautoFocus: {\n\t\t\ttype: Boolean\n\t\t}\n\t},\n\temits: ['success', 'error'],\n\tsetup(_: unknown, { emit }: SetupContext) {\n\t\tconst { projectId, baseUrl, sessionTokenViaCookie } = useOptions();\n\t\tconst sdk = useDescope();\n\n\t\tconst onSuccess = async (e: CustomEvent) => {\n\t\t\t// Note: We need to emit AFTER the afterRequest hook has been called, but for\n\t\t\t// an unknown reason, the emit is not called if we await the hook.\n\t\t\temit('success', e);\n\t\t\tawait sdk.httpClient.hooks?.afterRequest?.(\n\t\t\t\t{} as RequestConfig,\n\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t);\n\t\t};\n\t\tconst onError = (e: Event) => emit('error', e);\n\n\t\treturn {\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tonSuccess,\n\t\t\tonError\n\t\t};\n\t}\n};\n</script>\n"],"names":["_createElementBlock","_createElementVNode","$setup","projectId","baseUrl","$props","flowId","theme","tenant","debug","telemetryKey","redirectUrl","autoFocus","onSuccess","args","onError"],"mappings":"itCACCA,qBAcK,MAAA,KAAA,CAbJC,EAAAA,mBAYC,aAAA,CAXC,aAAYC,EAASC,UACrB,WAAUD,EAAOE,QACjB,UAASC,EAAMC,OACf,SAAYD,EAAKE,MACjB,UAAaF,EAAMG,OACnB,SAAYH,EAAKI,MACjB,gBAAmBJ,EAAYK,aAC/B,eAAcL,EAAWM,YACzB,aAAYN,EAASO,UACrBC,8BAASX,EAASW,WAAAX,EAAAW,aAAAC,IAClBC,4BAAOb,EAAOa,SAAAb,EAAAa,WAAAD"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/Descope.vue?vue&type=template&id=8a031dec&lang.js"],"sourcesContent":["<template>\n\t<div>\n\t\t<descope-wc\n\t\t\t:project-id=\"projectId\"\n\t\t\t:base-url=\"baseUrl\"\n\t\t\t:flow-id=\"flowId\"\n\t\t\t:theme.attr=\"theme\"\n\t\t\t:tenant.attr=\"tenant\"\n\t\t\t:debug.attr=\"debug\"\n\t\t\t:telemetryKey.attr=\"telemetryKey\"\n\t\t\t:redirect-url=\"redirectUrl\"\n\t\t\t:auto-focus=\"autoFocus\"\n\t\t\t@success=\"onSuccess\"\n\t\t\t@error=\"onError\"\n\t\t/>\n\t</div>\n</template>\n\n<script lang=\"ts\">\nimport DescopeWc from '@descope/web-component';\nimport { useOptions, useDescope } from './hooks';\nimport { baseHeaders } from './constants';\nimport { RequestConfig } from '@descope/core-js-sdk';\nimport { SetupContext } from 'vue';\n\nDescopeWc.sdkConfigOverrides = { baseHeaders };\n\nexport default {\n\t// eslint-disable-next-line vue/multi-word-component-names\n\tname: 'Descope',\n\tprops: {\n\t\tflowId: {\n\t\t\ttype: String,\n\t\t\trequired: true\n\t\t},\n\t\ttenant: {\n\t\t\ttype: String\n\t\t},\n\t\ttheme: {\n\t\t\ttype: String\n\t\t},\n\t\tdebug: {\n\t\t\ttype: Boolean\n\t\t},\n\t\ttelemetryKey: {\n\t\t\ttype: String\n\t\t},\n\t\tredirectUrl: {\n\t\t\ttype: String\n\t\t},\n\t\tautoFocus: {\n\t\t\ttype: Boolean\n\t\t}\n\t},\n\temits: ['success', 'error'],\n\tsetup(_: unknown, { emit }: SetupContext) {\n\t\tconst { projectId, baseUrl, sessionTokenViaCookie } = useOptions();\n\t\tconst sdk = useDescope();\n\n\t\tconst onSuccess = async (e: CustomEvent) => {\n\t\t\t// Note: We need to emit AFTER the afterRequest hook has been called, but for\n\t\t\t// an unknown reason, the emit is not called if we await the hook.\n\t\t\temit('success', e);\n\t\t\tawait sdk.httpClient.hooks?.afterRequest?.(\n\t\t\t\t{} as RequestConfig,\n\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t);\n\t\t};\n\t\tconst onError = (e: Event) => emit('error', e);\n\n\t\treturn {\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tonSuccess,\n\t\t\tonError\n\t\t};\n\t}\n};\n</script>\n"],"names":["_createElementBlock","_createElementVNode","$setup","projectId","baseUrl","$props","flowId","theme","tenant","debug","telemetryKey","redirectUrl","autoFocus","onSuccess","args","onError"],"mappings":"8uCACCA,qBAcK,MAAA,KAAA,CAbJC,EAAAA,mBAYC,aAAA,CAXC,aAAYC,EAASC,UACrB,WAAUD,EAAOE,QACjB,UAASC,EAAMC,OACf,SAAYD,EAAKE,MACjB,UAAaF,EAAMG,OACnB,SAAYH,EAAKI,MACjB,gBAAmBJ,EAAYK,aAC/B,eAAcL,EAAWM,YACzB,aAAYN,EAASO,UACrBC,8BAASX,EAASW,WAAAX,EAAAW,aAAAC,IAClBC,4BAAOb,EAAOa,SAAAb,EAAAa,WAAAD"}