@strivacity/sdk-core 1.0.0 → 2.0.0-beta
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/CHANGELOG.md +29 -0
- package/README.md +9 -7
- package/dist/flows/BaseFlow.cjs +1 -1
- package/dist/flows/BaseFlow.cjs.map +1 -1
- package/dist/flows/BaseFlow.d.ts +42 -55
- package/dist/flows/BaseFlow.mjs +1 -1
- package/dist/flows/BaseFlow.mjs.map +1 -1
- package/dist/flows/NativeFlow.cjs +2 -0
- package/dist/flows/NativeFlow.cjs.map +1 -0
- package/dist/flows/NativeFlow.d.ts +24 -0
- package/dist/flows/NativeFlow.mjs +2 -0
- package/dist/flows/NativeFlow.mjs.map +1 -0
- package/dist/flows/PopupFlow.cjs +1 -1
- package/dist/flows/PopupFlow.cjs.map +1 -1
- package/dist/flows/PopupFlow.d.ts +7 -14
- package/dist/flows/PopupFlow.mjs +1 -1
- package/dist/flows/PopupFlow.mjs.map +1 -1
- package/dist/flows/RedirectFlow.cjs +1 -1
- package/dist/flows/RedirectFlow.cjs.map +1 -1
- package/dist/flows/RedirectFlow.d.ts +6 -12
- package/dist/flows/RedirectFlow.mjs +1 -1
- package/dist/flows/RedirectFlow.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +10 -4
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/storages/LocalStorage.cjs +1 -1
- package/dist/storages/LocalStorage.cjs.map +1 -1
- package/dist/storages/LocalStorage.d.ts +3 -3
- package/dist/storages/LocalStorage.mjs +1 -1
- package/dist/storages/LocalStorage.mjs.map +1 -1
- package/dist/storages/SessionStorage.cjs +1 -1
- package/dist/storages/SessionStorage.cjs.map +1 -1
- package/dist/storages/SessionStorage.d.ts +3 -3
- package/dist/storages/SessionStorage.mjs +1 -1
- package/dist/storages/SessionStorage.mjs.map +1 -1
- package/dist/types.cjs +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +257 -25
- package/dist/types.mjs +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/HttpClient.cjs +2 -0
- package/dist/utils/HttpClient.cjs.map +1 -0
- package/dist/utils/HttpClient.d.ts +4 -0
- package/dist/utils/HttpClient.mjs +2 -0
- package/dist/utils/HttpClient.mjs.map +1 -0
- package/dist/utils/Metadata.cjs +2 -0
- package/dist/utils/Metadata.cjs.map +1 -0
- package/dist/{Metadata.d.ts → utils/Metadata.d.ts} +26 -2
- package/dist/utils/Metadata.mjs +2 -0
- package/dist/utils/Metadata.mjs.map +1 -0
- package/dist/utils/NativeFlowHandler.cjs +2 -0
- package/dist/utils/NativeFlowHandler.cjs.map +1 -0
- package/dist/utils/NativeFlowHandler.d.ts +54 -0
- package/dist/utils/NativeFlowHandler.mjs +2 -0
- package/dist/utils/NativeFlowHandler.mjs.map +1 -0
- package/dist/utils/Session.cjs +2 -0
- package/dist/utils/Session.cjs.map +1 -0
- package/dist/{Session.d.ts → utils/Session.d.ts} +1 -1
- package/dist/utils/Session.mjs +2 -0
- package/dist/utils/Session.mjs.map +1 -0
- package/dist/utils/State.cjs +2 -0
- package/dist/utils/State.cjs.map +1 -0
- package/dist/utils/State.mjs +2 -0
- package/dist/utils/State.mjs.map +1 -0
- package/dist/utils/base64Url.cjs.map +1 -1
- package/dist/utils/base64Url.mjs.map +1 -1
- package/dist/utils/crypto.cjs.map +1 -1
- package/dist/utils/crypto.mjs.map +1 -1
- package/dist/utils/date.cjs.map +1 -1
- package/dist/utils/date.mjs.map +1 -1
- package/dist/utils/errors.cjs +2 -0
- package/dist/utils/errors.cjs.map +1 -0
- package/dist/utils/errors.d.ts +4 -0
- package/dist/utils/errors.mjs +2 -0
- package/dist/utils/errors.mjs.map +1 -0
- package/dist/utils/handlers.cjs +1 -1
- package/dist/utils/handlers.cjs.map +1 -1
- package/dist/utils/handlers.d.ts +11 -11
- package/dist/utils/handlers.mjs +1 -1
- package/dist/utils/handlers.mjs.map +1 -1
- package/dist/utils/jwt.cjs +1 -1
- package/dist/utils/jwt.cjs.map +1 -1
- package/dist/utils/jwt.mjs +1 -1
- package/dist/utils/jwt.mjs.map +1 -1
- package/dist/utils/object.cjs +2 -0
- package/dist/utils/object.cjs.map +1 -0
- package/dist/utils/object.d.ts +1 -0
- package/dist/utils/object.mjs +2 -0
- package/dist/utils/object.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/Metadata.cjs +0 -2
- package/dist/Metadata.cjs.map +0 -1
- package/dist/Metadata.mjs +0 -2
- package/dist/Metadata.mjs.map +0 -1
- package/dist/Session.cjs +0 -2
- package/dist/Session.cjs.map +0 -1
- package/dist/Session.mjs +0 -2
- package/dist/Session.mjs.map +0 -1
- package/dist/State.cjs +0 -2
- package/dist/State.cjs.map +0 -1
- package/dist/State.mjs +0 -2
- package/dist/State.mjs.map +0 -1
- package/dist/utils/constants.cjs +0 -2
- package/dist/utils/constants.cjs.map +0 -1
- package/dist/utils/constants.d.ts +0 -6
- package/dist/utils/constants.mjs +0 -2
- package/dist/utils/constants.mjs.map +0 -1
- package/dist/utils/fetch.cjs +0 -2
- package/dist/utils/fetch.cjs.map +0 -1
- package/dist/utils/fetch.d.ts +0 -2
- package/dist/utils/fetch.mjs +0 -2
- package/dist/utils/fetch.mjs.map +0 -1
- /package/dist/{State.d.ts → utils/State.d.ts} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
+
## 2.0.0-beta (2025-07-24)
|
|
2
|
+
|
|
3
|
+
### 🚀 Features
|
|
4
|
+
|
|
5
|
+
- ionic example app added ([494805a](https://github.com/strivacity/sdk-js/commit/494805a))
|
|
6
|
+
- ⚠️ NativeFlow implemented ([75b353f](https://github.com/strivacity/sdk-js/commit/75b353f))
|
|
7
|
+
- @strivacity/sdk-core package implemented ([a80d419](https://github.com/strivacity/sdk-js/commit/a80d419))
|
|
8
|
+
|
|
9
|
+
### 🩹 Fixes
|
|
10
|
+
|
|
11
|
+
- access token expiration handling fixed ([da1850d](https://github.com/strivacity/sdk-js/commit/da1850d))
|
|
12
|
+
|
|
13
|
+
### ⚠️ Breaking Changes
|
|
14
|
+
|
|
15
|
+
- ⚠️ NativeFlow implemented ([75b353f](https://github.com/strivacity/sdk-js/commit/75b353f))
|
|
16
|
+
|
|
17
|
+
## 1.0.1 (2025-02-03)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
### 🩹 Fixes
|
|
21
|
+
|
|
22
|
+
- publish workflow fixed
|
|
23
|
+
|
|
24
|
+
- disable npm provenance config
|
|
25
|
+
|
|
26
|
+
- add --access=public to the publish workflow
|
|
27
|
+
|
|
28
|
+
- access token expiration handling fixed
|
|
29
|
+
|
|
1
30
|
# 1.0.0 (2024-09-20)
|
|
2
31
|
|
|
3
32
|
|
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# @strivacity/sdk-core
|
|
2
2
|
|
|
3
|
+
## Example App
|
|
4
|
+
|
|
5
|
+
- [Example app](https://github.com/Strivacity/sdk-js/tree/main/apps/web-component)
|
|
6
|
+
|
|
3
7
|
### Install
|
|
4
8
|
|
|
5
9
|
```bash
|
|
@@ -12,6 +16,7 @@ npm install @strivacity/sdk-core
|
|
|
12
16
|
import { initFlow } from '@strivacity/sdk-core';
|
|
13
17
|
|
|
14
18
|
const sdk = initFlow({
|
|
19
|
+
mode: 'redirect', // or 'popup' or 'native'
|
|
15
20
|
issuer: 'https://<YOUR_DOMAIN>',
|
|
16
21
|
scopes: ['openid', 'profile'],
|
|
17
22
|
clientId: '<YOUR_CLIENT_ID>',
|
|
@@ -23,15 +28,15 @@ await sdk.login();
|
|
|
23
28
|
|
|
24
29
|
### API Documentation
|
|
25
30
|
|
|
26
|
-
#### `initFlow(options: SDKOptions & { mode?: 'popup' | 'redirect' }): PopupFlow | RedirectFlow`
|
|
31
|
+
#### `initFlow(options: SDKOptions & { mode?: 'popup' | 'redirect' | 'native' }): PopupFlow | RedirectFlow | NativeFlow`
|
|
27
32
|
|
|
28
|
-
The `initFlow` function initializes and returns an instance of either `PopupFlow` or `
|
|
33
|
+
The `initFlow` function initializes and returns an instance of either `PopupFlow`, `RedirectFlow`, or `NativeFlow`, based on the specified `mode`.
|
|
29
34
|
|
|
30
35
|
**Parameters:**
|
|
31
36
|
|
|
32
37
|
- `options`: An object containing configuration options for the SDK.
|
|
33
38
|
|
|
34
|
-
**Type:** `SDKOptions & { mode?: 'popup' | 'redirect' }`
|
|
39
|
+
**Type:** `SDKOptions & { mode?: 'popup' | 'redirect' | 'native' }`
|
|
35
40
|
|
|
36
41
|
**Properties:**
|
|
37
42
|
|
|
@@ -48,7 +53,4 @@ The `initFlow` function initializes and returns an instance of either `PopupFlow
|
|
|
48
53
|
|
|
49
54
|
- `popup`: Uses a popup window for authentication. Returns an instance of `PopupFlow`.
|
|
50
55
|
- `redirect`: Uses a full-page redirect for authentication. Returns an instance of `RedirectFlow`.
|
|
51
|
-
|
|
52
|
-
### Links
|
|
53
|
-
|
|
54
|
-
[Example app](https://github.com/Strivacity/sdk-js/tree/main/apps/web-component)
|
|
56
|
+
- `native`: Uses a native flow for authentication. Returns an instance of `NativeFlow`.
|
package/dist/flows/BaseFlow.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var I=Object.defineProperty;var m=t=>{throw TypeError(t)};var R=(t,e,s)=>e in t?I(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var o=(t,e,s)=>R(t,typeof e!="symbol"?e+"":e,s),k=(t,e,s)=>e.has(t)||m("Cannot "+s);var r=(t,e,s)=>(k(t,e,"read from private field"),s?s.call(t):e.get(t)),c=(t,e,s)=>e.has(t)?m("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),d=(t,e,s,i)=>(k(t,e,"write to private field"),i?i.call(t,s):e.set(t,s),s),y=(t,e,s)=>(k(t,e,"access private method"),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("../utils/jwt.cjs"),P=require("../utils/date.cjs"),q=require("../utils/Metadata.cjs"),v=require("../utils/Session.cjs"),j=require("../utils/State.cjs");require("../utils/base64Url.cjs");require("../utils/crypto.cjs");const p={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};var a,n,l,S;class U{constructor(e,s,i){c(this,l);c(this,a,!1);c(this,n,null);o(this,"httpClient");o(this,"storage");o(this,"metadata");o(this,"session",null);o(this,"options");if(!e.issuer)throw new Error("Missing option: issuer");if(!e.clientId)throw new Error("Missing option: clientId");if(!e.redirectUri)throw new Error("Missing option: redirectUri");if(!e.urlHandler)throw new Error("Missing option: urlHandler");if(!e.callbackHandler)throw new Error("Missing option: callbackHandler");if(e.scopes&&!Array.isArray(e.scopes))throw new Error("Invalid option: scopes");e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=i,this.metadata=new q.Metadata(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),y(this,l,S).call(this)}get idTokenClaims(){var e;return(e=this.session)==null?void 0:e.claims}get accessToken(){var e;return(e=this.session)==null?void 0:e.access_token}get refreshToken(){var e;return(e=this.session)==null?void 0:e.refresh_token}get accessTokenExpired(){var e,s;return!((e=this.session)!=null&&e.access_token)||!((s=this.session)!=null&&s.expires_at)||this.session.expires_at<=P.timestamp()}get accessTokenExpirationDate(){var e;return(e=this.session)==null?void 0:e.expires_at}get isAuthenticated(){return r(this,n)?r(this,n):(d(this,n,new Promise(async e=>{await this.waitToInitialize();try{this.refreshToken&&this.accessTokenExpired&&await this.refresh()}catch{}setTimeout(()=>{e(!this.accessTokenExpired),d(this,n,null)})})),r(this,n))}async logout(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");await this.waitToInitialize();const s=this.session;if(!(s!=null&&s.id_token))return;await this.storage.delete(this.options.storageTokenName),this.session=null;const i=new URL(await this.metadata.endSessionEndpoint);i.searchParams.append("id_token_hint",s==null?void 0:s.id_token),e!=null&&e.postLogoutRedirectUri&&i.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]);try{await this.options.urlHandler(i.toString(),e)}catch{}}async refresh(){var s,i;if(await this.waitToInitialize(),typeof((s=this.session)==null?void 0:s.refresh_token)!="string")return;const e=this.session;try{const h=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:(i=this.session)==null?void 0:i.refresh_token});Object.assign(this.session,await h.json()),this.session.id_token&&(this.session.claims=E.jwt.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}catch{this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}])}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{e!=null&&e.refresh_token?await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token}):e!=null&&e.access_token&&await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})}catch{s=!1}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e!=null&&e.refresh_token?this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]):e!=null&&e.access_token&&this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}])}}async tokenExchange(e={}){var h,w,u,f,T,g;if(await this.waitToInitialize(),this.session=new v.Session,Object.assign(this.session,e),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(!this.session.code)throw new Error("Invalid or missing code");let s;try{const _=await this.storage.get(`sty.${this.session.state}`);if(!_)throw new Error;s=j.State.fromSerializedData(_),await this.storage.delete(`sty.${this.session.state}`)}catch{throw new Error("Invalid or missing state")}const i=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(Object.assign(this.session,await i.json()),this.session.id_token&&(this.session.claims=E.jwt.decode(this.session.id_token)),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(this.session.scope!==((h=this.options.scopes)==null?void 0:h.join(" ")))throw new Error("Invalid scope");if(((w=this.session.claims)==null?void 0:w.nonce)!==s.nonce)throw new Error("Invalid nonce");if(((u=this.session.claims)==null?void 0:u.iss)!==await this.metadata.issuer)throw new Error("Invalid iss");if(Array.isArray((f=this.session.claims)==null?void 0:f.aud)?((T=this.session.claims)==null?void 0:T.aud[0])!==this.options.clientId:((g=this.session.claims)==null?void 0:g.aud)!==this.options.clientId)throw new Error("Invalid aud");await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}async getAuthorizationUrl(e={}){var i;const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",((i=this.options.scopes)==null?void 0:i.join(" "))||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),s}async waitToInitialize(){for(;!r(this,a);)await new Promise(e=>setTimeout(e,10))}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return p[e].add(s),{dispose:()=>{p[e].delete(s)}}}dispatchEvent(e,s){for(const i of p[e])i(...s)}}a=new WeakMap,n=new WeakMap,l=new WeakSet,S=async function(){this.session=v.Session.load(await this.storage.get(this.options.storageTokenName)),setTimeout(()=>{this.dispatchEvent("init",[]),this.session&&this.accessToken&&this.idTokenClaims&&this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.accessToken&&this.accessTokenExpired&&this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}]),d(this,a,!0)})};exports.BaseFlow=U;
|
|
2
2
|
//# sourceMappingURL=BaseFlow.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseFlow.cjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { KyInstance } from 'ky';\nimport type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutOptions } from '../types';\nimport { isBrowser } from '../utils/constants';\nimport { jwt } from '../utils/jwt';\nimport { fetch } from '../utils/fetch';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../Metadata';\nimport { Session } from '../Session';\nimport { State } from '../State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerOptions - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions, URLHandlerOptions extends ExtraRequestArgs> {\n\t/**\n\t * A promise that resolves to indicate whether authentication has been verified.\n\t *\n\t * @type {Promise<boolean> | null}\n\t */\n\tprotected isAuthPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {KyInstance}\n\t */\n\tprotected httpClient!: KyInstance;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\tprotected options: Options;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tprotected storage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tprotected metadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tprotected session: Session | null = null;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.isAuthPromise) {\n\t\t\treturn this.isAuthPromise;\n\t\t}\n\n\t\t// eslint-disable-next-line no-async-promise-executor\n\t\tthis.isAuthPromise = new Promise(async (resolve) => {\n\t\t\ttry {\n\t\t\t\tif (this.refreshToken && this.accessTokenExpired) {\n\t\t\t\t\tawait this.refresh();\n\t\t\t\t}\n\t\t\t} catch {}\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tresolve(!!this.session?.access_token || !!this.session?.refresh_token);\n\t\t\t\tthis.isAuthPromise = null;\n\t\t\t});\n\t\t});\n\n\t\treturn this.isAuthPromise;\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage) {\n\t\tif (!options.issuer) {\n\t\t\tthrow Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow Error('Missing option: redirectUri');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.httpClient = fetch.create({ retry: 0 });\n\t\tthis.options = options as Options;\n\t\tthis.storage = storage;\n\t\tthis.metadata = new Metadata(`${options.issuer}/.well-known/openid-configuration`);\n\t\tthis.session = Session.load(this.storage.get(this.options.storageTokenName as string));\n\n\t\tsetTimeout(() => {\n\t\t\tthis.dispatchEvent('init', []);\n\n\t\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\n\t\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerOptions} [options] - Additional options for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(options?: URLHandlerOptions): Promise<void>;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerOptions} [options] - Additional options for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(options?: URLHandlerOptions): Promise<void>;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerOptions & LogoutOptions} [options] - Additional options for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(options?: URLHandlerOptions & LogoutOptions): Promise<void> {\n\t\tif (!isBrowser) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\tthis.storage.delete(this.options.storageTokenName as string);\n\t\tthis.session = null;\n\n\t\tif (session?.id_token) {\n\t\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\t\tif (options?.postLogoutRedirectUri) {\n\t\t\t\turl.searchParams.append('post_logout_redirect_uri', options.postLogoutRedirectUri);\n\t\t\t}\n\n\t\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims as IdTokenClaims }]);\n\n\t\t\ttry {\n\t\t\t\tawait this.urlHandler(url, options as URLHandlerOptions);\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if no refresh token is available or if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\tthrow Error('No refresh token available');\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tthis.storage.set(this.options.storageTokenName as string, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tthis.storage.delete(this.options.storageTokenName as string);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token as string }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tthis.storage.delete(this.options.storageTokenName as string);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token as string, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token as string, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync exchangeCodeForTokens(params: Record<string, string> = {}): Promise<void> {\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tthis.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow Error('Invalid aud');\n\t\t}\n\n\t\tthis.storage.set(this.options.storageTokenName as string, JSON.stringify(this.session));\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [options={}] - Additional options to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tprotected async getAuthorizationUrl(options: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') as string);\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (options.prompt) {\n\t\t\turl.searchParams.append('prompt', options.prompt);\n\t\t}\n\t\tif (options.acrValues) {\n\t\t\turl.searchParams.append('acr_values', options.acrValues.join(' '));\n\t\t}\n\t\tif (options.loginHint) {\n\t\t\turl.searchParams.append('login_hint', options.loginHint);\n\t\t}\n\t\tif (options.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', options.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\t/**\n\t * Handles URL redirections for authentication and authorization processes.\n\t *\n\t * @param {string | URL} url - The URL to handle.\n\t * @param {URLHandlerOptions} [options] - Additional options for URL handling.\n\t * @returns {Promise<unknown>} - A promise that resolves when the URL handling is complete.\n\t */\n\tprotected abstract urlHandler(url: string | URL, options?: URLHandlerOptions): Promise<unknown>;\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string | URL} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<Response>} - A promise that resolves to the response from the request.\n\t */\n\tprotected async sendTokenRequest(url: string | URL, data: Record<string, string> = {}): Promise<Response> {\n\t\treturn await this.httpClient.post(url, {\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data),\n\t\t});\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","options","storage","__publicField","fetch","Metadata","Session","_a","timestamp","resolve","_b","isBrowser","session","url","request","jwt","success","params","state","serializedState","State","_c","_d","_e","_f","eventName","callbackFn","args","eventFn","data"],"mappings":"+gBAWA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,EAQO,MAAeC,CAAiF,CA2HtG,YAAYC,EAAkBC,EAAqB,CArHzCC,EAAA,qBAAyC,MAOzCA,EAAA,mBAOAA,EAAA,gBAOAA,EAAA,gBAOAA,EAAA,iBAOAA,EAAA,eAA0B,MAmF/B,GAAA,CAACF,EAAQ,OACZ,MAAM,MAAM,wBAAwB,EAEjC,GAAA,CAACA,EAAQ,SACZ,MAAM,MAAM,0BAA0B,EAEnC,GAAA,CAACA,EAAQ,YACZ,MAAM,MAAM,6BAA6B,EAE1C,GAAIA,EAAQ,QAAU,CAAC,MAAM,QAAQA,EAAQ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AAuB,CACzG,OAAO,MAAM,KAAK,WAAW,KAAKhB,EAAK,CACtC,QAAS,CAAE,eAAgB,mCAAoC,EAC/D,KAAM,IAAI,gBAAgBgB,CAAI,CAAA,CAC9B,CACF,CACD"}
|
|
1
|
+
{"version":3,"file":"BaseFlow.cjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutParams, SDKHttpClient, HttpClientResponse } from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initialized = false;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\t// eslint-disable-next-line no-async-promise-executor, @typescript-eslint/no-misused-promises\n\t\tthis.#isAuthenticatedPromise = new Promise(async (resolve) => {\n\t\t\tawait this.waitToInitialize();\n\n\t\t\ttry {\n\t\t\t\tif (this.refreshToken && this.accessTokenExpired) {\n\t\t\t\t\tawait this.refresh();\n\t\t\t\t}\n\t\t\t} catch {}\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tresolve(!this.accessTokenExpired);\n\t\t\t\tthis.#isAuthenticatedPromise = null;\n\t\t\t});\n\t\t});\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.issuer) {\n\t\t\tthrow new Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow new Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow new Error('Missing option: redirectUri');\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tthrow new Error('Missing option: urlHandler');\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tthrow new Error('Missing option: callbackHandler');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow new Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tvoid this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tsetTimeout(() => {\n\t\t\tthis.dispatchEvent('init', []);\n\n\t\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\n\t\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\t}\n\n\t\t\tthis.#initialized = true;\n\t\t});\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\n\t\ttry {\n\t\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t\t} catch {}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow new Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow new Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow new Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow new Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow new Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow new Error('Invalid aud');\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tprotected async waitToInitialize(): Promise<void> {\n\t\twhile (!this.#initialized) {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 10));\n\t\t}\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<Session>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<Session>> {\n\t\treturn this.httpClient.request<Session>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","options","storage","httpClient","__privateAdd","_BaseFlow_instances","_initialized","_isAuthenticatedPromise","__publicField","Metadata","__privateMethod","init_fn","_a","_b","timestamp","__privateGet","__privateSet","resolve","params","session","url","request","jwt","success","Session","state","serializedState","State","_c","_d","_e","_f","data","eventName","callbackFn","args","eventFn"],"mappings":"k1BAQA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,cAQO,MAAeC,CAAgH,CAgIrI,YAAYC,EAAkBC,EAAqBC,EAA2B,CAhIxEC,EAAA,KAAAC,GAIND,EAAA,KAAAE,EAAe,IAKfF,EAAA,KAAAG,EAAmD,MAOnDC,EAAA,mBAOAA,EAAA,gBAOAA,EAAA,iBAOAA,EAAA,eAA0B,MAO1BA,EAAA,gBAqFC,GAAI,CAACP,EAAQ,OACZ,MAAM,IAAI,MAAM,wBAAwB,EAEzC,GAAI,CAACA,EAAQ,SACZ,MAAM,IAAI,MAAM,0BAA0B,EAE3C,GAAI,CAACA,EAAQ,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Session } from '../Session';
|
|
1
|
+
import { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutParams, SDKHttpClient, HttpClientResponse } from '../types';
|
|
2
|
+
import { Metadata } from '../utils/Metadata';
|
|
3
|
+
import { Session } from '../utils/Session';
|
|
5
4
|
/**
|
|
6
5
|
* An abstract base class that provides common functionality for different OIDC flows.
|
|
7
6
|
*
|
|
8
7
|
* @template Options - The options type extending `SDKOptions` used for configuring the flow.
|
|
9
|
-
* @template
|
|
8
|
+
* @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.
|
|
10
9
|
*/
|
|
11
|
-
export declare abstract class BaseFlow<Options extends SDKOptions,
|
|
12
|
-
|
|
13
|
-
* A promise that resolves to indicate whether authentication has been verified.
|
|
14
|
-
*
|
|
15
|
-
* @type {Promise<boolean> | null}
|
|
16
|
-
*/
|
|
17
|
-
protected isAuthPromise: Promise<boolean> | null;
|
|
10
|
+
export declare abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {
|
|
11
|
+
#private;
|
|
18
12
|
/**
|
|
19
13
|
* An instance of the HTTP client used for making requests.
|
|
20
14
|
*
|
|
21
|
-
* @type {
|
|
15
|
+
* @type {SDKHttpClient}
|
|
22
16
|
*/
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* The configuration options for the flow.
|
|
26
|
-
*
|
|
27
|
-
* @type {Options}
|
|
28
|
-
*/
|
|
29
|
-
protected options: Options;
|
|
17
|
+
httpClient: SDKHttpClient;
|
|
30
18
|
/**
|
|
31
19
|
* The storage mechanism used to persist session data.
|
|
32
20
|
*
|
|
33
21
|
* @type {SDKStorage}
|
|
34
22
|
*/
|
|
35
|
-
|
|
23
|
+
storage: SDKStorage;
|
|
36
24
|
/**
|
|
37
25
|
* Metadata information about the authorization server.
|
|
38
26
|
*
|
|
39
27
|
* @type {Metadata}
|
|
40
28
|
*/
|
|
41
|
-
|
|
29
|
+
metadata: Metadata;
|
|
42
30
|
/**
|
|
43
31
|
* The current session data.
|
|
44
32
|
*
|
|
45
33
|
* @type {Session | null}
|
|
46
34
|
*/
|
|
47
|
-
|
|
35
|
+
session: Session | null;
|
|
36
|
+
/**
|
|
37
|
+
* The configuration options for the flow.
|
|
38
|
+
*
|
|
39
|
+
* @type {Options}
|
|
40
|
+
*/
|
|
41
|
+
options: Options;
|
|
48
42
|
/**
|
|
49
43
|
* Retrieves the ID token claims from the current session.
|
|
50
44
|
*
|
|
@@ -89,34 +83,34 @@ export declare abstract class BaseFlow<Options extends SDKOptions, URLHandlerOpt
|
|
|
89
83
|
*
|
|
90
84
|
* @throws {Error} Throws an error if required options are missing or invalid.
|
|
91
85
|
*/
|
|
92
|
-
constructor(options: Options, storage: SDKStorage);
|
|
86
|
+
constructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient);
|
|
93
87
|
/**
|
|
94
88
|
* Initiates the login process. Subclasses should implement this method to handle the specific login flow.
|
|
95
89
|
*
|
|
96
|
-
* @param {
|
|
90
|
+
* @param {URLHandlerParams} [params] - Additional params for handling URLs during login.
|
|
97
91
|
* @returns {Promise<void>} - A promise that resolves when the login process is complete.
|
|
98
92
|
*/
|
|
99
|
-
abstract login(
|
|
93
|
+
abstract login(params?: URLHandlerParams): unknown;
|
|
100
94
|
/**
|
|
101
95
|
* Registers a new user. Subclasses should implement this method to handle the specific registration flow.
|
|
102
96
|
*
|
|
103
|
-
* @param {
|
|
97
|
+
* @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.
|
|
104
98
|
* @returns {Promise<void>} - A promise that resolves when the registration process is complete.
|
|
105
99
|
*/
|
|
106
|
-
abstract register(
|
|
100
|
+
abstract register(params?: URLHandlerParams): unknown;
|
|
107
101
|
/**
|
|
108
102
|
* Logs out the current user and optionally redirects to a post-logout URI.
|
|
109
103
|
*
|
|
110
|
-
* @param {
|
|
104
|
+
* @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.
|
|
111
105
|
* @returns {Promise<void>} - A promise that resolves when the logout process is complete.
|
|
112
106
|
*/
|
|
113
|
-
logout(
|
|
107
|
+
logout(params?: URLHandlerParams & LogoutParams): Promise<void>;
|
|
114
108
|
/**
|
|
115
109
|
* Refreshes the access token using the refresh token.
|
|
116
110
|
*
|
|
117
111
|
* @returns {Promise<void>} - A promise that resolves when the token refresh is complete.
|
|
118
112
|
*
|
|
119
|
-
* @throws {Error} Throws an error if
|
|
113
|
+
* @throws {Error} Throws an error if the refresh fails.
|
|
120
114
|
*/
|
|
121
115
|
refresh(): Promise<void>;
|
|
122
116
|
/**
|
|
@@ -133,7 +127,23 @@ export declare abstract class BaseFlow<Options extends SDKOptions, URLHandlerOpt
|
|
|
133
127
|
*
|
|
134
128
|
* @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.
|
|
135
129
|
*/
|
|
136
|
-
|
|
130
|
+
tokenExchange(params?: Record<string, string>): Promise<void>;
|
|
131
|
+
/**
|
|
132
|
+
* Constructs the authorization URL for initiating the authorization flow.
|
|
133
|
+
*
|
|
134
|
+
* @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.
|
|
135
|
+
* @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.
|
|
136
|
+
*/
|
|
137
|
+
getAuthorizationUrl(params?: ExtraRequestArgs): Promise<URL>;
|
|
138
|
+
protected waitToInitialize(): Promise<void>;
|
|
139
|
+
/**
|
|
140
|
+
* Sends a token request to the specified URL with the given data.
|
|
141
|
+
*
|
|
142
|
+
* @param {string} url - The URL to send the request to.
|
|
143
|
+
* @param {Record<string, string>} [data={}] - The data to include in the request body.
|
|
144
|
+
* @returns {Promise<HttpClientResponse<Session>>} - A promise that resolves to the response from the request.
|
|
145
|
+
*/
|
|
146
|
+
sendTokenRequest(url: string, data?: Record<string, string>): Promise<HttpClientResponse<Session>>;
|
|
137
147
|
/**
|
|
138
148
|
* Subscribes a callback function to an event.
|
|
139
149
|
*
|
|
@@ -151,27 +161,4 @@ export declare abstract class BaseFlow<Options extends SDKOptions, URLHandlerOpt
|
|
|
151
161
|
* @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.
|
|
152
162
|
*/
|
|
153
163
|
protected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void;
|
|
154
|
-
/**
|
|
155
|
-
* Constructs the authorization URL for initiating the authorization flow.
|
|
156
|
-
*
|
|
157
|
-
* @param {ExtraRequestArgs} [options={}] - Additional options to include in the authorization URL.
|
|
158
|
-
* @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.
|
|
159
|
-
*/
|
|
160
|
-
protected getAuthorizationUrl(options?: ExtraRequestArgs): Promise<URL>;
|
|
161
|
-
/**
|
|
162
|
-
* Handles URL redirections for authentication and authorization processes.
|
|
163
|
-
*
|
|
164
|
-
* @param {string | URL} url - The URL to handle.
|
|
165
|
-
* @param {URLHandlerOptions} [options] - Additional options for URL handling.
|
|
166
|
-
* @returns {Promise<unknown>} - A promise that resolves when the URL handling is complete.
|
|
167
|
-
*/
|
|
168
|
-
protected abstract urlHandler(url: string | URL, options?: URLHandlerOptions): Promise<unknown>;
|
|
169
|
-
/**
|
|
170
|
-
* Sends a token request to the specified URL with the given data.
|
|
171
|
-
*
|
|
172
|
-
* @param {string | URL} url - The URL to send the request to.
|
|
173
|
-
* @param {Record<string, string>} [data={}] - The data to include in the request body.
|
|
174
|
-
* @returns {Promise<Response>} - A promise that resolves to the response from the request.
|
|
175
|
-
*/
|
|
176
|
-
protected sendTokenRequest(url: string | URL, data?: Record<string, string>): Promise<Response>;
|
|
177
164
|
}
|
package/dist/flows/BaseFlow.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var S=Object.defineProperty;var _=t=>{throw TypeError(t)};var R=(t,e,s)=>e in t?S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var o=(t,e,s)=>R(t,typeof e!="symbol"?e+"":e,s),k=(t,e,s)=>e.has(t)||_("Cannot "+s);var r=(t,e,s)=>(k(t,e,"read from private field"),s?s.call(t):e.get(t)),c=(t,e,s)=>e.has(t)?_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),d=(t,e,s,i)=>(k(t,e,"write to private field"),i?i.call(t,s):e.set(t,s),s),E=(t,e,s)=>(k(t,e,"access private method"),s);import{jwt as y}from"../utils/jwt.mjs";import{timestamp as P}from"../utils/date.mjs";import{Metadata as x}from"../utils/Metadata.mjs";import{Session as v}from"../utils/Session.mjs";import{State as U}from"../utils/State.mjs";import"../utils/base64Url.mjs";import"../utils/crypto.mjs";const p={accessTokenExpired:new Set,init:new Set,loggedIn:new Set,loginInitiated:new Set,logoutInitiated:new Set,sessionLoaded:new Set,tokenRefreshed:new Set,tokenRefreshFailed:new Set,tokenRevoked:new Set,tokenRevokeFailed:new Set};var a,n,l,I;class b{constructor(e,s,i){c(this,l);c(this,a,!1);c(this,n,null);o(this,"httpClient");o(this,"storage");o(this,"metadata");o(this,"session",null);o(this,"options");if(!e.issuer)throw new Error("Missing option: issuer");if(!e.clientId)throw new Error("Missing option: clientId");if(!e.redirectUri)throw new Error("Missing option: redirectUri");if(!e.urlHandler)throw new Error("Missing option: urlHandler");if(!e.callbackHandler)throw new Error("Missing option: callbackHandler");if(e.scopes&&!Array.isArray(e.scopes))throw new Error("Invalid option: scopes");e.scopes||(e.scopes=["openid"]),e.responseType||(e.responseType="code"),e.responseMode||(e.responseMode="query"),e.storageTokenName||(e.storageTokenName="sty.session"),this.options=e,this.storage=s,this.httpClient=i,this.metadata=new x(this,new URL("/.well-known/openid-configuration",e.issuer).toString()),E(this,l,I).call(this)}get idTokenClaims(){var e;return(e=this.session)==null?void 0:e.claims}get accessToken(){var e;return(e=this.session)==null?void 0:e.access_token}get refreshToken(){var e;return(e=this.session)==null?void 0:e.refresh_token}get accessTokenExpired(){var e,s;return!((e=this.session)!=null&&e.access_token)||!((s=this.session)!=null&&s.expires_at)||this.session.expires_at<=P()}get accessTokenExpirationDate(){var e;return(e=this.session)==null?void 0:e.expires_at}get isAuthenticated(){return r(this,n)?r(this,n):(d(this,n,new Promise(async e=>{await this.waitToInitialize();try{this.refreshToken&&this.accessTokenExpired&&await this.refresh()}catch{}setTimeout(()=>{e(!this.accessTokenExpired),d(this,n,null)})})),r(this,n))}async logout(e){if(typeof this.options.urlHandler!="function")throw new Error("URL handler is not defined. Please provide a valid URL handler function in the SDK options.");await this.waitToInitialize();const s=this.session;if(!(s!=null&&s.id_token))return;await this.storage.delete(this.options.storageTokenName),this.session=null;const i=new URL(await this.metadata.endSessionEndpoint);i.searchParams.append("id_token_hint",s==null?void 0:s.id_token),e!=null&&e.postLogoutRedirectUri&&i.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]);try{await this.options.urlHandler(i.toString(),e)}catch{}}async refresh(){var s,i;if(await this.waitToInitialize(),typeof((s=this.session)==null?void 0:s.refresh_token)!="string")return;const e=this.session;try{const h=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:(i=this.session)==null?void 0:i.refresh_token});Object.assign(this.session,await h.json()),this.session.id_token&&(this.session.claims=y.decode(this.session.id_token)),await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.refreshToken&&this.idTokenClaims&&this.dispatchEvent("tokenRefreshed",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}catch{this.session=null,await this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}])}}async revoke(){await this.waitToInitialize();const e=this.session;let s=!0;try{e!=null&&e.refresh_token?await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"refresh_token",token:e.refresh_token}):e!=null&&e.access_token&&await this.sendTokenRequest(await this.metadata.revocationEndpoint,{client_id:this.options.clientId,token_type_hint:"access_token",token:e.access_token})}catch{s=!1}finally{this.session=null,await this.storage.delete(this.options.storageTokenName),e!=null&&e.refresh_token?this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.refresh_token,tokenTypeHint:"refresh_token"}]):e!=null&&e.access_token&&this.dispatchEvent(s?"tokenRevoked":"tokenRevokeFailed",[{token:e.access_token,tokenTypeHint:"access_token"}])}}async tokenExchange(e={}){var h,w,f,u,T,m;if(await this.waitToInitialize(),this.session=new v,Object.assign(this.session,e),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(!this.session.code)throw new Error("Invalid or missing code");let s;try{const g=await this.storage.get(`sty.${this.session.state}`);if(!g)throw new Error;s=U.fromSerializedData(g),await this.storage.delete(`sty.${this.session.state}`)}catch{throw new Error("Invalid or missing state")}const i=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"authorization_code",client_id:this.options.clientId,redirect_uri:this.options.redirectUri,code_verifier:s.codeVerifier,code:this.session.code});if(Object.assign(this.session,await i.json()),this.session.id_token&&(this.session.claims=y.decode(this.session.id_token)),this.session.error)throw new Error(`${this.session.error}: ${this.session.error_description}`);if(this.session.scope!==((h=this.options.scopes)==null?void 0:h.join(" ")))throw new Error("Invalid scope");if(((w=this.session.claims)==null?void 0:w.nonce)!==s.nonce)throw new Error("Invalid nonce");if(((f=this.session.claims)==null?void 0:f.iss)!==await this.metadata.issuer)throw new Error("Invalid iss");if(Array.isArray((u=this.session.claims)==null?void 0:u.aud)?((T=this.session.claims)==null?void 0:T.aud[0])!==this.options.clientId:((m=this.session.claims)==null?void 0:m.aud)!==this.options.clientId)throw new Error("Invalid aud");await this.storage.set(this.options.storageTokenName,JSON.stringify(this.session)),this.accessToken&&this.idTokenClaims&&this.dispatchEvent("loggedIn",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}])}async getAuthorizationUrl(e={}){var i;const s=new URL(await this.metadata.authorizationEndpoint);return s.searchParams.append("client_id",this.options.clientId),s.searchParams.append("redirect_uri",this.options.redirectUri),s.searchParams.append("response_type",this.options.responseType||"code"),s.searchParams.append("response_mode",this.options.responseMode||"fragment"),s.searchParams.append("scope",((i=this.options.scopes)==null?void 0:i.join(" "))||""),s.searchParams.append("code_challenge_method","S256"),e.prompt&&s.searchParams.append("prompt",e.prompt),e.acrValues&&s.searchParams.append("acr_values",e.acrValues.join(" ")),e.loginHint&&s.searchParams.append("login_hint",e.loginHint),e.uiLocales&&s.searchParams.append("ui_locales",e.uiLocales.join(" ")),s}async waitToInitialize(){for(;!r(this,a);)await new Promise(e=>setTimeout(e,10))}async sendTokenRequest(e,s={}){return this.httpClient.request(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}subscribeToEvent(e,s){return p[e].add(s),{dispose:()=>{p[e].delete(s)}}}dispatchEvent(e,s){for(const i of p[e])i(...s)}}a=new WeakMap,n=new WeakMap,l=new WeakSet,I=async function(){this.session=v.load(await this.storage.get(this.options.storageTokenName)),setTimeout(()=>{this.dispatchEvent("init",[]),this.session&&this.accessToken&&this.idTokenClaims&&this.dispatchEvent("sessionLoaded",[{accessToken:this.accessToken,refreshToken:this.refreshToken,claims:this.idTokenClaims}]),this.accessToken&&this.accessTokenExpired&&this.dispatchEvent("accessTokenExpired",[{accessToken:this.accessToken,refreshToken:this.refreshToken}]),d(this,a,!0)})};export{b as BaseFlow};
|
|
2
2
|
//# sourceMappingURL=BaseFlow.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseFlow.mjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { KyInstance } from 'ky';\nimport type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutOptions } from '../types';\nimport { isBrowser } from '../utils/constants';\nimport { jwt } from '../utils/jwt';\nimport { fetch } from '../utils/fetch';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../Metadata';\nimport { Session } from '../Session';\nimport { State } from '../State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerOptions - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions, URLHandlerOptions extends ExtraRequestArgs> {\n\t/**\n\t * A promise that resolves to indicate whether authentication has been verified.\n\t *\n\t * @type {Promise<boolean> | null}\n\t */\n\tprotected isAuthPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {KyInstance}\n\t */\n\tprotected httpClient!: KyInstance;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\tprotected options: Options;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tprotected storage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tprotected metadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tprotected session: Session | null = null;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.isAuthPromise) {\n\t\t\treturn this.isAuthPromise;\n\t\t}\n\n\t\t// eslint-disable-next-line no-async-promise-executor\n\t\tthis.isAuthPromise = new Promise(async (resolve) => {\n\t\t\ttry {\n\t\t\t\tif (this.refreshToken && this.accessTokenExpired) {\n\t\t\t\t\tawait this.refresh();\n\t\t\t\t}\n\t\t\t} catch {}\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tresolve(!!this.session?.access_token || !!this.session?.refresh_token);\n\t\t\t\tthis.isAuthPromise = null;\n\t\t\t});\n\t\t});\n\n\t\treturn this.isAuthPromise;\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage) {\n\t\tif (!options.issuer) {\n\t\t\tthrow Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow Error('Missing option: redirectUri');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.httpClient = fetch.create({ retry: 0 });\n\t\tthis.options = options as Options;\n\t\tthis.storage = storage;\n\t\tthis.metadata = new Metadata(`${options.issuer}/.well-known/openid-configuration`);\n\t\tthis.session = Session.load(this.storage.get(this.options.storageTokenName as string));\n\n\t\tsetTimeout(() => {\n\t\t\tthis.dispatchEvent('init', []);\n\n\t\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\n\t\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerOptions} [options] - Additional options for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(options?: URLHandlerOptions): Promise<void>;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerOptions} [options] - Additional options for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(options?: URLHandlerOptions): Promise<void>;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerOptions & LogoutOptions} [options] - Additional options for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(options?: URLHandlerOptions & LogoutOptions): Promise<void> {\n\t\tif (!isBrowser) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\tthis.storage.delete(this.options.storageTokenName as string);\n\t\tthis.session = null;\n\n\t\tif (session?.id_token) {\n\t\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\t\tif (options?.postLogoutRedirectUri) {\n\t\t\t\turl.searchParams.append('post_logout_redirect_uri', options.postLogoutRedirectUri);\n\t\t\t}\n\n\t\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims as IdTokenClaims }]);\n\n\t\t\ttry {\n\t\t\t\tawait this.urlHandler(url, options as URLHandlerOptions);\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if no refresh token is available or if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\tthrow Error('No refresh token available');\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tthis.storage.set(this.options.storageTokenName as string, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tthis.storage.delete(this.options.storageTokenName as string);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token as string }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tthis.storage.delete(this.options.storageTokenName as string);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token as string, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token as string, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync exchangeCodeForTokens(params: Record<string, string> = {}): Promise<void> {\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tthis.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow Error('Invalid aud');\n\t\t}\n\n\t\tthis.storage.set(this.options.storageTokenName as string, JSON.stringify(this.session));\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [options={}] - Additional options to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tprotected async getAuthorizationUrl(options: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') as string);\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (options.prompt) {\n\t\t\turl.searchParams.append('prompt', options.prompt);\n\t\t}\n\t\tif (options.acrValues) {\n\t\t\turl.searchParams.append('acr_values', options.acrValues.join(' '));\n\t\t}\n\t\tif (options.loginHint) {\n\t\t\turl.searchParams.append('login_hint', options.loginHint);\n\t\t}\n\t\tif (options.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', options.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\t/**\n\t * Handles URL redirections for authentication and authorization processes.\n\t *\n\t * @param {string | URL} url - The URL to handle.\n\t * @param {URLHandlerOptions} [options] - Additional options for URL handling.\n\t * @returns {Promise<unknown>} - A promise that resolves when the URL handling is complete.\n\t */\n\tprotected abstract urlHandler(url: string | URL, options?: URLHandlerOptions): Promise<unknown>;\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string | URL} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<Response>} - A promise that resolves to the response from the request.\n\t */\n\tprotected async sendTokenRequest(url: string | URL, data: Record<string, string> = {}): Promise<Response> {\n\t\treturn await this.httpClient.post(url, {\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data),\n\t\t});\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","options","storage","__publicField","fetch","Metadata","Session","_a","timestamp","resolve","_b","isBrowser","session","url","request","jwt","success","params","state","serializedState","State","_c","_d","_e","_f","eventName","callbackFn","args","eventFn","data"],"mappings":"2gBAWA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,EAQO,MAAeC,CAAiF,CA2HtG,YAAYC,EAAkBC,EAAqB,CArHzCC,EAAA,qBAAyC,MAOzCA,EAAA,mBAOAA,EAAA,gBAOAA,EAAA,gBAOAA,EAAA,iBAOAA,EAAA,e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XY,EAAI,aAAa,OAAO,aAAcZ,EAAQ,SAAS,EAEpDA,EAAQ,WACXY,EAAI,aAAa,OAAO,aAAcZ,EAAQ,UAAU,KAAK,GAAG,CAAC,EAG3DY,CACR,CAkBA,MAAgB,iBAAiBA,EAAmBgB,EAA+B,GAAuB,CACzG,OAAO,MAAM,KAAK,WAAW,KAAKhB,EAAK,CACtC,QAAS,CAAE,eAAgB,mCAAoC,EAC/D,KAAM,IAAI,gBAAgBgB,CAAI,CAAA,CAC9B,CACF,CACD"}
|
|
1
|
+
{"version":3,"file":"BaseFlow.mjs","sources":["../../src/flows/BaseFlow.ts"],"sourcesContent":["import type { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutParams, SDKHttpClient, HttpClientResponse } from '../types';\nimport { jwt } from '../utils/jwt';\nimport { timestamp } from '../utils/date';\nimport { Metadata } from '../utils/Metadata';\nimport { Session } from '../utils/Session';\nimport { State } from '../utils/State';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst eventCallbacks: Record<keyof EventFunctions, Set<(...args: Array<any>) => Promise<void> | void>> = {\n\taccessTokenExpired: new Set(),\n\tinit: new Set(),\n\tloggedIn: new Set(),\n\tloginInitiated: new Set(),\n\tlogoutInitiated: new Set(),\n\tsessionLoaded: new Set(),\n\ttokenRefreshed: new Set(),\n\ttokenRefreshFailed: new Set(),\n\ttokenRevoked: new Set(),\n\ttokenRevokeFailed: new Set(),\n};\n\n/**\n * An abstract base class that provides common functionality for different OIDC flows.\n *\n * @template Options - The options type extending `SDKOptions` used for configuring the flow.\n * @template URLHandlerParams - The options type extending `ExtraRequestArgs` used for URL handling.\n */\nexport abstract class BaseFlow<Options extends SDKOptions = SDKOptions, URLHandlerParams extends ExtraRequestArgs = ExtraRequestArgs> {\n\t/**\n\t * @ignore\n\t */\n\t#initialized = false;\n\n\t/**\n\t * @ignore\n\t */\n\t#isAuthenticatedPromise: Promise<boolean> | null = null;\n\n\t/**\n\t * An instance of the HTTP client used for making requests.\n\t *\n\t * @type {SDKHttpClient}\n\t */\n\thttpClient: SDKHttpClient;\n\n\t/**\n\t * The storage mechanism used to persist session data.\n\t *\n\t * @type {SDKStorage}\n\t */\n\tstorage: SDKStorage;\n\n\t/**\n\t * Metadata information about the authorization server.\n\t *\n\t * @type {Metadata}\n\t */\n\tmetadata: Metadata;\n\n\t/**\n\t * The current session data.\n\t *\n\t * @type {Session | null}\n\t */\n\tsession: Session | null = null;\n\n\t/**\n\t * The configuration options for the flow.\n\t *\n\t * @type {Options}\n\t */\n\toptions: Options;\n\n\t/**\n\t * Retrieves the ID token claims from the current session.\n\t *\n\t * @type {IdTokenClaims | null | undefined}\n\t */\n\tget idTokenClaims(): IdTokenClaims | null | undefined {\n\t\treturn this.session?.claims;\n\t}\n\n\t/**\n\t * Retrieves the access token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget accessToken(): string | null | undefined {\n\t\treturn this.session?.access_token;\n\t}\n\n\t/**\n\t * Retrieves the refresh token from the current session.\n\t *\n\t * @type {string | null | undefined}\n\t */\n\tget refreshToken(): string | null | undefined {\n\t\treturn this.session?.refresh_token;\n\t}\n\n\t/**\n\t * Determines if the access token has expired.\n\t *\n\t * @type {boolean}\n\t */\n\tget accessTokenExpired(): boolean {\n\t\treturn !this.session?.access_token || !this.session?.expires_at || this.session.expires_at <= timestamp();\n\t}\n\n\t/**\n\t * Retrieves the access token expiration date.\n\t *\n\t * @type {number | null | undefined}\n\t */\n\tget accessTokenExpirationDate(): number | null | undefined {\n\t\treturn this.session?.expires_at;\n\t}\n\n\t/**\n\t * Checks if the user is authenticated by evaluating the presence of access or refresh tokens.\n\t *\n\t * @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.\n\t */\n\tget isAuthenticated(): Promise<boolean> {\n\t\tif (this.#isAuthenticatedPromise) {\n\t\t\treturn this.#isAuthenticatedPromise;\n\t\t}\n\n\t\t// eslint-disable-next-line no-async-promise-executor, @typescript-eslint/no-misused-promises\n\t\tthis.#isAuthenticatedPromise = new Promise(async (resolve) => {\n\t\t\tawait this.waitToInitialize();\n\n\t\t\ttry {\n\t\t\t\tif (this.refreshToken && this.accessTokenExpired) {\n\t\t\t\t\tawait this.refresh();\n\t\t\t\t}\n\t\t\t} catch {}\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tresolve(!this.accessTokenExpired);\n\t\t\t\tthis.#isAuthenticatedPromise = null;\n\t\t\t});\n\t\t});\n\n\t\treturn this.#isAuthenticatedPromise;\n\t}\n\n\t/**\n\t * Constructs a new instance of the `BaseFlow` class.\n\t *\n\t * @param {Options} options - Configuration options for the flow.\n\t * @param {SDKStorage} storage - Storage mechanism for session data.\n\t *\n\t * @throws {Error} Throws an error if required options are missing or invalid.\n\t */\n\tconstructor(options: Options, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.issuer) {\n\t\t\tthrow new Error('Missing option: issuer');\n\t\t}\n\t\tif (!options.clientId) {\n\t\t\tthrow new Error('Missing option: clientId');\n\t\t}\n\t\tif (!options.redirectUri) {\n\t\t\tthrow new Error('Missing option: redirectUri');\n\t\t}\n\t\tif (!options.urlHandler) {\n\t\t\tthrow new Error('Missing option: urlHandler');\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\tthrow new Error('Missing option: callbackHandler');\n\t\t}\n\t\tif (options.scopes && !Array.isArray(options.scopes)) {\n\t\t\tthrow new Error('Invalid option: scopes');\n\t\t}\n\n\t\tif (!options.scopes) {\n\t\t\toptions.scopes = ['openid'];\n\t\t}\n\t\tif (!options.responseType) {\n\t\t\toptions.responseType = 'code';\n\t\t}\n\t\tif (!options.responseMode) {\n\t\t\toptions.responseMode = 'query';\n\t\t}\n\t\tif (!options.storageTokenName) {\n\t\t\toptions.storageTokenName = 'sty.session';\n\t\t}\n\n\t\tthis.options = options;\n\t\tthis.storage = storage;\n\t\tthis.httpClient = httpClient;\n\t\tthis.metadata = new Metadata(this, new URL('/.well-known/openid-configuration', options.issuer).toString());\n\n\t\tvoid this.#init();\n\t}\n\n\t/**\n\t * Initializes the flow by loading the session from storage and setting up event listeners.\n\t * @ignore\n\t */\n\tasync #init() {\n\t\tthis.session = Session.load(await this.storage.get(this.options.storageTokenName!));\n\n\t\tsetTimeout(() => {\n\t\t\tthis.dispatchEvent('init', []);\n\n\t\t\tif (this.session && this.accessToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('sessionLoaded', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\n\t\t\tif (this.accessToken && this.accessTokenExpired) {\n\t\t\t\tthis.dispatchEvent('accessTokenExpired', [{ accessToken: this.accessToken, refreshToken: this.refreshToken }]);\n\t\t\t}\n\n\t\t\tthis.#initialized = true;\n\t\t});\n\t}\n\n\t/**\n\t * Initiates the login process. Subclasses should implement this method to handle the specific login flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during login.\n\t * @returns {Promise<void>} - A promise that resolves when the login process is complete.\n\t */\n\tabstract login(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Registers a new user. Subclasses should implement this method to handle the specific registration flow.\n\t *\n\t * @param {URLHandlerParams} [params] - Additional params for handling URLs during registration.\n\t * @returns {Promise<void>} - A promise that resolves when the registration process is complete.\n\t */\n\tabstract register(params?: URLHandlerParams): unknown;\n\n\t/**\n\t * Logs out the current user and optionally redirects to a post-logout URI.\n\t *\n\t * @param {URLHandlerParams & LogoutParams} [params] - Additional params for handling URLs during logout.\n\t * @returns {Promise<void>} - A promise that resolves when the logout process is complete.\n\t */\n\tasync logout(params?: URLHandlerParams & LogoutParams): Promise<void> {\n\t\tif (typeof this.options.urlHandler !== 'function') {\n\t\t\tthrow new Error('URL handler is not defined. Please provide a valid URL handler function in the SDK options.');\n\t\t}\n\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\n\t\tif (!session?.id_token) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.storage.delete(this.options.storageTokenName!);\n\t\tthis.session = null;\n\n\t\tconst url = new URL(await this.metadata.endSessionEndpoint);\n\n\t\turl.searchParams.append('id_token_hint', session?.id_token);\n\n\t\tif (params?.postLogoutRedirectUri) {\n\t\t\turl.searchParams.append('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\t\t}\n\n\t\tthis.dispatchEvent('logoutInitiated', [{ idToken: session.id_token, claims: session.claims! }]);\n\n\t\ttry {\n\t\t\tawait this.options.urlHandler(url.toString(), params as URLHandlerParams);\n\t\t} catch {}\n\t}\n\n\t/**\n\t * Refreshes the access token using the refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token refresh is complete.\n\t *\n\t * @throws {Error} Throws an error if the refresh fails.\n\t */\n\tasync refresh(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tif (typeof this.session?.refresh_token !== 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\tconst session = this.session;\n\n\t\ttry {\n\t\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\trefresh_token: this.session?.refresh_token,\n\t\t\t});\n\n\t\t\tObject.assign(this.session, await request.json());\n\n\t\t\tif (this.session.id_token) {\n\t\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t\t}\n\n\t\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\t\tif (this.accessToken && this.refreshToken && this.idTokenClaims) {\n\t\t\t\tthis.dispatchEvent('tokenRefreshed', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tthis.dispatchEvent('tokenRefreshFailed', [{ refreshToken: session.refresh_token! }]);\n\t\t}\n\t}\n\n\t/**\n\t * Revokes the current access or refresh token.\n\t *\n\t * @returns {Promise<void>} - A promise that resolves when the token revocation is complete.\n\t */\n\tasync revoke(): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tconst session = this.session;\n\t\tlet success = true;\n\n\t\ttry {\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'refresh_token',\n\t\t\t\t\ttoken: session.refresh_token,\n\t\t\t\t});\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tawait this.sendTokenRequest(await this.metadata.revocationEndpoint, {\n\t\t\t\t\tclient_id: this.options.clientId,\n\t\t\t\t\ttoken_type_hint: 'access_token',\n\t\t\t\t\ttoken: session.access_token,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\tsuccess = false;\n\t\t} finally {\n\t\t\tthis.session = null;\n\t\t\tawait this.storage.delete(this.options.storageTokenName!);\n\n\t\t\tif (session?.refresh_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.refresh_token, tokenTypeHint: 'refresh_token' }]);\n\t\t\t} else if (session?.access_token) {\n\t\t\t\tthis.dispatchEvent(success ? 'tokenRevoked' : 'tokenRevokeFailed', [{ token: session.access_token, tokenTypeHint: 'access_token' }]);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Exchanges an authorization code for access and refresh tokens.\n\t *\n\t * @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.\n\t * @returns {Promise<void>} - A promise that resolves when the token exchange is complete.\n\t *\n\t * @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.\n\t */\n\tasync tokenExchange(params: Record<string, string> = {}): Promise<void> {\n\t\tawait this.waitToInitialize();\n\n\t\tthis.session = new Session();\n\n\t\tObject.assign(this.session, params);\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (!this.session.code) {\n\t\t\tthrow new Error('Invalid or missing code');\n\t\t}\n\n\t\tlet state: State;\n\n\t\ttry {\n\t\t\tconst serializedState = await this.storage.get(`sty.${this.session.state}`);\n\n\t\t\tif (!serializedState) {\n\t\t\t\tthrow new Error();\n\t\t\t}\n\n\t\t\tstate = State.fromSerializedData(serializedState);\n\n\t\t\tawait this.storage.delete(`sty.${this.session.state}`);\n\t\t} catch {\n\t\t\tthrow new Error('Invalid or missing state');\n\t\t}\n\n\t\tconst request = await this.sendTokenRequest(await this.metadata.tokenEndpoint, {\n\t\t\tgrant_type: 'authorization_code',\n\t\t\tclient_id: this.options.clientId,\n\t\t\tredirect_uri: this.options.redirectUri,\n\t\t\tcode_verifier: state.codeVerifier,\n\t\t\tcode: this.session.code,\n\t\t});\n\n\t\tObject.assign(this.session, await request.json());\n\n\t\tif (this.session.id_token) {\n\t\t\tthis.session.claims = jwt.decode<IdTokenClaims>(this.session.id_token);\n\t\t}\n\n\t\tif (this.session.error) {\n\t\t\tthrow new Error(`${this.session.error}: ${this.session.error_description}`);\n\t\t}\n\t\tif (this.session.scope !== this.options.scopes?.join(' ')) {\n\t\t\tthrow new Error('Invalid scope');\n\t\t}\n\t\tif (this.session.claims?.nonce !== state.nonce) {\n\t\t\tthrow new Error('Invalid nonce');\n\t\t}\n\t\tif (this.session.claims?.iss !== (await this.metadata.issuer)) {\n\t\t\tthrow new Error('Invalid iss');\n\t\t}\n\t\tif (Array.isArray(this.session.claims?.aud) ? this.session.claims?.aud[0] !== this.options.clientId : this.session.claims?.aud !== this.options.clientId) {\n\t\t\tthrow new Error('Invalid aud');\n\t\t}\n\n\t\tawait this.storage.set(this.options.storageTokenName!, JSON.stringify(this.session));\n\n\t\tif (this.accessToken && this.idTokenClaims) {\n\t\t\tthis.dispatchEvent('loggedIn', [{ accessToken: this.accessToken, refreshToken: this.refreshToken, claims: this.idTokenClaims }]);\n\t\t}\n\t}\n\n\t/**\n\t * Constructs the authorization URL for initiating the authorization flow.\n\t *\n\t * @param {ExtraRequestArgs} [params={}] - Additional params to include in the authorization URL.\n\t * @returns {Promise<URL>} - A promise that resolves to the constructed authorization URL.\n\t */\n\tasync getAuthorizationUrl(params: ExtraRequestArgs = {}): Promise<URL> {\n\t\tconst url = new URL(await this.metadata.authorizationEndpoint);\n\n\t\turl.searchParams.append('client_id', this.options.clientId);\n\t\turl.searchParams.append('redirect_uri', this.options.redirectUri);\n\t\turl.searchParams.append('response_type', this.options.responseType || 'code');\n\t\turl.searchParams.append('response_mode', this.options.responseMode || 'fragment');\n\t\turl.searchParams.append('scope', this.options.scopes?.join(' ') || '');\n\t\turl.searchParams.append('code_challenge_method', 'S256');\n\n\t\tif (params.prompt) {\n\t\t\turl.searchParams.append('prompt', params.prompt);\n\t\t}\n\t\tif (params.acrValues) {\n\t\t\turl.searchParams.append('acr_values', params.acrValues.join(' '));\n\t\t}\n\t\tif (params.loginHint) {\n\t\t\turl.searchParams.append('login_hint', params.loginHint);\n\t\t}\n\t\tif (params.uiLocales) {\n\t\t\turl.searchParams.append('ui_locales', params.uiLocales.join(' '));\n\t\t}\n\n\t\treturn url;\n\t}\n\n\tprotected async waitToInitialize(): Promise<void> {\n\t\twhile (!this.#initialized) {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 10));\n\t\t}\n\t}\n\n\t/**\n\t * Sends a token request to the specified URL with the given data.\n\t *\n\t * @param {string} url - The URL to send the request to.\n\t * @param {Record<string, string>} [data={}] - The data to include in the request body.\n\t * @returns {Promise<HttpClientResponse<Session>>} - A promise that resolves to the response from the request.\n\t */\n\tasync sendTokenRequest(url: string, data: Record<string, string> = {}): Promise<HttpClientResponse<Session>> {\n\t\treturn this.httpClient.request<Session>(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/x-www-form-urlencoded' },\n\t\t\tbody: new URLSearchParams(data).toString(),\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes a callback function to an event.\n\t *\n\t * @param {T} eventName - The name of the event to subscribe to.\n\t * @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.\n\t * @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.\n\t */\n\tsubscribeToEvent<T extends keyof EventFunctions>(\n\t\teventName: T,\n\t\tcallbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void,\n\t): { dispose: () => void } {\n\t\teventCallbacks[eventName].add(callbackFn);\n\n\t\treturn {\n\t\t\tdispose: () => {\n\t\t\t\teventCallbacks[eventName].delete(callbackFn);\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Dispatches an event to all subscribed callback functions.\n\t *\n\t * @param {T} eventName - The name of the event to dispatch.\n\t * @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.\n\t */\n\tprotected dispatchEvent<T extends keyof EventFunctions>(eventName: T, args: Parameters<EventFunctions[T]>): void {\n\t\tfor (const eventFn of eventCallbacks[eventName]) {\n\t\t\tvoid eventFn(...args);\n\t\t}\n\t}\n}\n"],"names":["eventCallbacks","BaseFlow","options","storage","httpClient","__privateAdd","_BaseFlow_instances","_initialized","_isAuthenticatedPromise","__publicField","Metadata","__privateMethod","init_fn","_a","_b","timestamp","__privateGet","__privateSet","resolve","params","session","url","request","jwt","success","Session","state","serializedState","State","_c","_d","_e","_f","data","eventName","callbackFn","args","eventFn"],"mappings":"ozBAQA,MAAMA,EAAmG,CACxG,uBAAwB,IACxB,SAAU,IACV,aAAc,IACd,mBAAoB,IACpB,oBAAqB,IACrB,kBAAmB,IACnB,mBAAoB,IACpB,uBAAwB,IACxB,iBAAkB,IAClB,sBAAuB,GACxB,cAQO,MAAeC,CAAgH,CAgIrI,YAAYC,EAAkBC,EAAqBC,EAA2B,CAhIxEC,EAAA,KAAAC,GAIND,EAAA,KAAAE,EAAe,IAKfF,EAAA,KAAAG,EAAmD,MAOnDC,EAAA,mBAOAA,EAAA,gBAOAA,EAAA,iBA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e,GAAA,CACpB,CAAA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../utils/handlers.cjs"),l=require("../utils/NativeFlowHandler.cjs"),t=require("./BaseFlow.cjs");require("../utils/State.cjs");require("../utils/crypto.cjs");require("../utils/base64Url.cjs");require("../utils/date.cjs");require("../utils/errors.cjs");require("../utils/jwt.cjs");require("../utils/Metadata.cjs");require("../utils/Session.cjs");class n extends t.BaseFlow{constructor(e,r,i){e.urlHandler||(e.urlHandler=a.redirectUrlHandler),e.callbackHandler||(e.callbackHandler=a.redirectCallbackHandler),super(e,r,i)}login(e={}){return this.dispatchEvent("loginInitiated",[]),new l.NativeFlowHandler(this,e)}register(e={}){return e.prompt="create",this.login(e)}async handleCallback(e){var r;if(typeof this.options.callbackHandler!="function")throw new Error("Callback handler is not defined. Please provide a valid callback handler function in the SDK options.");e||(e=(r=globalThis.window)==null?void 0:r.location.href),await this.tokenExchange(await this.options.callbackHandler(e,this.options.responseMode||"fragment"))}}exports.NativeFlow=n;
|
|
2
|
+
//# sourceMappingURL=NativeFlow.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeFlow.cjs","sources":["../../src/flows/NativeFlow.ts"],"sourcesContent":["import type { SDKOptions, NativeParams, SDKStorage, SDKHttpClient } from '../types';\nimport { redirectUrlHandler, redirectCallbackHandler } from '../utils/handlers';\nimport { NativeFlowHandler } from '../utils/NativeFlowHandler';\nimport { BaseFlow } from './BaseFlow';\n\nexport class NativeFlow extends BaseFlow<SDKOptions, NativeParams> {\n\tconstructor(options: SDKOptions, storage: SDKStorage, httpClient: SDKHttpClient) {\n\t\tif (!options.urlHandler) {\n\t\t\toptions.urlHandler = redirectUrlHandler;\n\t\t}\n\t\tif (!options.callbackHandler) {\n\t\t\toptions.callbackHandler = redirectCallbackHandler;\n\t\t}\n\n\t\tsuper(options, storage, httpClient);\n\t}\n\n\t/**\n\t * Initiates the login process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tlogin(params: NativeParams = {}): NativeFlowHandler {\n\t\tthis.dispatchEvent('loginInitiated', []);\n\n\t\treturn new NativeFlowHandler(this, params);\n\t}\n\n\t/**\n\t * Initiates the registration process via native UI.\n\t * @param {NativeParams} [params={}] Optional parameters for native configuration.\n\t * @returns {NativeFlowHandler} Returns with a native login handler.\n\t */\n\tregister(params: NativeParams = {}): NativeFlowHandler {\n\t\tparams.prompt = 'create';\n\n\t\treturn this.login(params);\n\t}\n\n\t/**\n\t * Handles the callback after login or registration via a redirect.\n\t * @param {string} [url] The URL to handle the callback from. Defaults to the current window location.\n\t * @returns {Promise<void>} A promise that resolves when the callback is handled.\n\t */\n\tasync handleCallback(url?: string): Promise<void> {\n\t\tif (typeof this.options.callbackHandler !== 'function') {\n\t\t\tthrow new Error('Callback handler is not defined. Please provide a valid callback handler function in the SDK options.');\n\t\t}\n\n\t\tif (!url) {\n\t\t\turl = globalThis.window?.location.href;\n\t\t}\n\n\t\tawait this.tokenExchange((await this.options.callbackHandler(url, this.options.responseMode || 'fragment')) as Record<string, string>);\n\t}\n}\n"],"names":["NativeFlow","BaseFlow","options","storage","httpClient","redirectUrlHandler","redirectCallbackHandler","params","NativeFlowHandler","url","_a"],"mappings":"ybAKO,MAAMA,UAAmBC,EAAAA,QAAmC,CAClE,YAAYC,EAAqBC,EAAqBC,EAA2B,CAC3EF,EAAQ,aACZA,EAAQ,WAAaG,EAAAA,oBAEjBH,EAAQ,kBACZA,EAAQ,gBAAkBI,EAAAA,yBAG3B,MAAMJ,EAASC,EAASC,CAAU,CAAA,CAQnC,MAAMG,EAAuB,GAAuB,CACnD,YAAK,cAAc,iBAAkB,EAAE,EAEhC,IAAIC,EAAAA,kBAAkB,KAAMD,CAAM,CAAA,CAQ1C,SAASA,EAAuB,GAAuB,CACtD,OAAAA,EAAO,OAAS,SAET,KAAK,MAAMA,CAAM,CAAA,CAQzB,MAAM,eAAeE,EAA6B,OACjD,GAAI,OAAO,KAAK,QAAQ,iBAAoB,WAC3C,MAAM,IAAI,MAAM,uGAAuG,EAGnHA,IACJA,GAAMC,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,MAGnC,MAAM,KAAK,cAAe,MAAM,KAAK,QAAQ,gBAAgBD,EAAK,KAAK,QAAQ,cAAgB,UAAU,CAA4B,CAAA,CAEvI"}
|