@strivacity/sdk-core 1.0.0
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 +6 -0
- package/LICENSE +21 -0
- package/README.md +54 -0
- package/dist/Metadata.cjs +2 -0
- package/dist/Metadata.cjs.map +1 -0
- package/dist/Metadata.d.ts +74 -0
- package/dist/Metadata.mjs +2 -0
- package/dist/Metadata.mjs.map +1 -0
- package/dist/Session.cjs +2 -0
- package/dist/Session.cjs.map +1 -0
- package/dist/Session.d.ts +82 -0
- package/dist/Session.mjs +2 -0
- package/dist/Session.mjs.map +1 -0
- package/dist/State.cjs +2 -0
- package/dist/State.cjs.map +1 -0
- package/dist/State.d.ts +43 -0
- package/dist/State.mjs +2 -0
- package/dist/State.mjs.map +1 -0
- package/dist/flows/BaseFlow.cjs +2 -0
- package/dist/flows/BaseFlow.cjs.map +1 -0
- package/dist/flows/BaseFlow.d.ts +177 -0
- package/dist/flows/BaseFlow.mjs +2 -0
- package/dist/flows/BaseFlow.mjs.map +1 -0
- package/dist/flows/PopupFlow.cjs +2 -0
- package/dist/flows/PopupFlow.cjs.map +1 -0
- package/dist/flows/PopupFlow.d.ts +31 -0
- package/dist/flows/PopupFlow.mjs +2 -0
- package/dist/flows/PopupFlow.mjs.map +1 -0
- package/dist/flows/RedirectFlow.cjs +2 -0
- package/dist/flows/RedirectFlow.cjs.map +1 -0
- package/dist/flows/RedirectFlow.d.ts +32 -0
- package/dist/flows/RedirectFlow.mjs +2 -0
- package/dist/flows/RedirectFlow.mjs.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/dist/storages/LocalStorage.cjs +2 -0
- package/dist/storages/LocalStorage.cjs.map +1 -0
- package/dist/storages/LocalStorage.d.ts +23 -0
- package/dist/storages/LocalStorage.mjs +2 -0
- package/dist/storages/LocalStorage.mjs.map +1 -0
- package/dist/storages/SessionStorage.cjs +2 -0
- package/dist/storages/SessionStorage.cjs.map +1 -0
- package/dist/storages/SessionStorage.d.ts +23 -0
- package/dist/storages/SessionStorage.mjs +2 -0
- package/dist/storages/SessionStorage.mjs.map +1 -0
- package/dist/types.cjs +2 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.ts +861 -0
- package/dist/types.mjs +2 -0
- package/dist/types.mjs.map +1 -0
- package/dist/utils/base64Url.cjs +2 -0
- package/dist/utils/base64Url.cjs.map +1 -0
- package/dist/utils/base64Url.d.ts +27 -0
- package/dist/utils/base64Url.mjs +2 -0
- package/dist/utils/base64Url.mjs.map +1 -0
- package/dist/utils/constants.cjs +2 -0
- package/dist/utils/constants.cjs.map +1 -0
- package/dist/utils/constants.d.ts +6 -0
- package/dist/utils/constants.mjs +2 -0
- package/dist/utils/constants.mjs.map +1 -0
- package/dist/utils/crypto.cjs +2 -0
- package/dist/utils/crypto.cjs.map +1 -0
- package/dist/utils/crypto.d.ts +32 -0
- package/dist/utils/crypto.mjs +2 -0
- package/dist/utils/crypto.mjs.map +1 -0
- package/dist/utils/date.cjs +2 -0
- package/dist/utils/date.cjs.map +1 -0
- package/dist/utils/date.d.ts +6 -0
- package/dist/utils/date.mjs +2 -0
- package/dist/utils/date.mjs.map +1 -0
- package/dist/utils/fetch.cjs +2 -0
- package/dist/utils/fetch.cjs.map +1 -0
- package/dist/utils/fetch.d.ts +2 -0
- package/dist/utils/fetch.mjs +2 -0
- package/dist/utils/fetch.mjs.map +1 -0
- package/dist/utils/handlers.cjs +2 -0
- package/dist/utils/handlers.cjs.map +1 -0
- package/dist/utils/handlers.d.ts +34 -0
- package/dist/utils/handlers.mjs +2 -0
- package/dist/utils/handlers.mjs.map +1 -0
- package/dist/utils/jwt.cjs +2 -0
- package/dist/utils/jwt.cjs.map +1 -0
- package/dist/utils/jwt.d.ts +34 -0
- package/dist/utils/jwt.mjs +2 -0
- package/dist/utils/jwt.mjs.map +1 -0
- package/package.json +49 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Strivacity Inc. <info@strivacity.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# @strivacity/sdk-core
|
|
2
|
+
|
|
3
|
+
### Install
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @strivacity/sdk-core
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
### Usage
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import { initFlow } from '@strivacity/sdk-core';
|
|
13
|
+
|
|
14
|
+
const sdk = initFlow({
|
|
15
|
+
issuer: 'https://<YOUR_DOMAIN>',
|
|
16
|
+
scopes: ['openid', 'profile'],
|
|
17
|
+
clientId: '<YOUR_CLIENT_ID>',
|
|
18
|
+
redirectUri: '<YOUR_REDIRECT_URI>',
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
await sdk.login();
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### API Documentation
|
|
25
|
+
|
|
26
|
+
#### `initFlow(options: SDKOptions & { mode?: 'popup' | 'redirect' }): PopupFlow | RedirectFlow`
|
|
27
|
+
|
|
28
|
+
The `initFlow` function initializes and returns an instance of either `PopupFlow` or `RedirectFlow`, based on the specified `mode`.
|
|
29
|
+
|
|
30
|
+
**Parameters:**
|
|
31
|
+
|
|
32
|
+
- `options`: An object containing configuration options for the SDK.
|
|
33
|
+
|
|
34
|
+
**Type:** `SDKOptions & { mode?: 'popup' | 'redirect' }`
|
|
35
|
+
|
|
36
|
+
**Properties:**
|
|
37
|
+
|
|
38
|
+
- `issuer` (string): The issuer URL of the OpenID Provider.
|
|
39
|
+
- `clientId` (string): The client identifier for the application.
|
|
40
|
+
- `redirectUri` (string): The URI to redirect to after authentication.
|
|
41
|
+
- `scopes` (Array<string>): The scopes to request during authentication.
|
|
42
|
+
- `responseType` (ResponseType): The response type requested from the OpenID Provider.
|
|
43
|
+
- `responseMode` (ResponseMode): The response mode to use.
|
|
44
|
+
- `storageTokenName` (string): The name of the token in storage.
|
|
45
|
+
- `storage` (SDKStorageType): A custom storage implementation.
|
|
46
|
+
|
|
47
|
+
**Mode:**
|
|
48
|
+
|
|
49
|
+
- `popup`: Uses a popup window for authentication. Returns an instance of `PopupFlow`.
|
|
50
|
+
- `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)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var n=Object.defineProperty;var i=(a,t,e)=>t in a?n(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var r=(a,t,e)=>i(a,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./utils/fetch.cjs");class s{constructor(t){r(this,"data",null);this.metadataUrl=t}get issuer(){return this.getMetadataProperty("issuer")}get authorizationEndpoint(){return this.getMetadataProperty("authorization_endpoint")}get tokenEndpoint(){return this.getMetadataProperty("token_endpoint")}get userinfoEndpoint(){return this.getMetadataProperty("userinfo_endpoint")}get endSessionEndpoint(){return this.getMetadataProperty("end_session_endpoint")}get revocationEndpoint(){return this.getMetadataProperty("revocation_endpoint")}get jwksUri(){return this.getMetadataProperty("jwks_uri")}async fetchMetadata(){this.data=await o.fetch.get(this.metadataUrl).json()}async getMetadataProperty(t){var e;return(e=this.data)!=null&&e[t]?Promise.resolve(this.data[t]):(await this.fetchMetadata(),Promise.resolve(this.data[t]))}}exports.Metadata=s;
|
|
2
|
+
//# sourceMappingURL=Metadata.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Metadata.cjs","sources":["../src/Metadata.ts"],"sourcesContent":["import type { MetadataOptions } from './types';\nimport { fetch } from './utils/fetch';\n\n/**\n * Class responsible for fetching and handling metadata for authentication endpoints.\n */\nexport class Metadata {\n\t/**\n\t * Holds the metadata options once fetched, or null if not yet fetched.\n\t * @protected\n\t */\n\tprotected data: MetadataOptions | null = null;\n\n\t/**\n\t * Retrieves the issuer metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the issuer string.\n\t */\n\tget issuer(): Promise<string> {\n\t\treturn this.getMetadataProperty('issuer');\n\t}\n\n\t/**\n\t * Retrieves the authorization endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the authorization endpoint URL.\n\t */\n\tget authorizationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('authorization_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the token endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the token endpoint URL.\n\t */\n\tget tokenEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('token_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the user info endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the user info endpoint URL.\n\t */\n\tget userinfoEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('userinfo_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the end session endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the end session endpoint URL.\n\t */\n\tget endSessionEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('end_session_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the revocation endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the revocation endpoint URL.\n\t */\n\tget revocationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('revocation_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the JWKS URI metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the JWKS URI.\n\t */\n\tget jwksUri(): Promise<string> {\n\t\treturn this.getMetadataProperty('jwks_uri');\n\t}\n\n\t/**\n\t * Creates an instance of the Metadata class.\n\t *\n\t * @param {string} metadataUrl The URL to fetch metadata from.\n\t */\n\tconstructor(protected metadataUrl: string) {}\n\n\t/**\n\t * Fetches and updates the metadata from the specified URL.\n\t *\n\t * @returns {Promise<void>} A promise that resolves once the metadata is fetched.\n\t */\n\tasync fetchMetadata(): Promise<void> {\n\t\tthis.data = await fetch.get(this.metadataUrl).json<MetadataOptions>();\n\t}\n\n\t/**\n\t * Retrieves a specific metadata property.\n\t *\n\t * @template K The key of the metadata property.\n\t * @param {K} key The metadata property key to retrieve.\n\t * @returns {Promise<MetadataOptions[K]>} A promise that resolves to the value of the specified metadata property.\n\t */\n\tasync getMetadataProperty<K extends keyof MetadataOptions>(key: K): Promise<MetadataOptions[K]> {\n\t\tif (this.data?.[key]) {\n\t\t\treturn Promise.resolve(this.data[key]);\n\t\t}\n\n\t\tawait this.fetchMetadata();\n\n\t\treturn Promise.resolve((this.data as MetadataOptions)[key]);\n\t}\n}\n"],"names":["Metadata","metadataUrl","__publicField","fetch","key","_a"],"mappings":"yRAMO,MAAMA,CAAS,CA2ErB,YAAsBC,EAAqB,CAtEjCC,EAAA,YAA+B,MAsEnB,KAAA,YAAAD,CAAsB,CA/D5C,IAAI,QAA0B,CACtB,OAAA,KAAK,oBAAoB,QAAQ,CACzC,CAOA,IAAI,uBAAyC,CACrC,OAAA,KAAK,oBAAoB,wBAAwB,CACzD,CAOA,IAAI,eAAiC,CAC7B,OAAA,KAAK,oBAAoB,gBAAgB,CACjD,CAOA,IAAI,kBAAoC,CAChC,OAAA,KAAK,oBAAoB,mBAAmB,CACpD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,sBAAsB,CACvD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,qBAAqB,CACtD,CAOA,IAAI,SAA2B,CACvB,OAAA,KAAK,oBAAoB,UAAU,CAC3C,CAcA,MAAM,eAA+B,CACpC,KAAK,KAAO,MAAME,QAAM,IAAI,KAAK,WAAW,EAAE,MAC/C,CASA,MAAM,oBAAqDC,EAAqC,OAC3F,OAAAC,EAAA,KAAK,OAAL,MAAAA,EAAYD,GACR,QAAQ,QAAQ,KAAK,KAAKA,CAAG,CAAC,GAGtC,MAAM,KAAK,gBAEJ,QAAQ,QAAS,KAAK,KAAyBA,CAAG,CAAC,EAC3D,CACD"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { MetadataOptions } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Class responsible for fetching and handling metadata for authentication endpoints.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Metadata {
|
|
6
|
+
protected metadataUrl: string;
|
|
7
|
+
/**
|
|
8
|
+
* Holds the metadata options once fetched, or null if not yet fetched.
|
|
9
|
+
* @protected
|
|
10
|
+
*/
|
|
11
|
+
protected data: MetadataOptions | null;
|
|
12
|
+
/**
|
|
13
|
+
* Retrieves the issuer metadata.
|
|
14
|
+
*
|
|
15
|
+
* @returns {Promise<string>} A promise that resolves to the issuer string.
|
|
16
|
+
*/
|
|
17
|
+
get issuer(): Promise<string>;
|
|
18
|
+
/**
|
|
19
|
+
* Retrieves the authorization endpoint metadata.
|
|
20
|
+
*
|
|
21
|
+
* @returns {Promise<string>} A promise that resolves to the authorization endpoint URL.
|
|
22
|
+
*/
|
|
23
|
+
get authorizationEndpoint(): Promise<string>;
|
|
24
|
+
/**
|
|
25
|
+
* Retrieves the token endpoint metadata.
|
|
26
|
+
*
|
|
27
|
+
* @returns {Promise<string>} A promise that resolves to the token endpoint URL.
|
|
28
|
+
*/
|
|
29
|
+
get tokenEndpoint(): Promise<string>;
|
|
30
|
+
/**
|
|
31
|
+
* Retrieves the user info endpoint metadata.
|
|
32
|
+
*
|
|
33
|
+
* @returns {Promise<string>} A promise that resolves to the user info endpoint URL.
|
|
34
|
+
*/
|
|
35
|
+
get userinfoEndpoint(): Promise<string>;
|
|
36
|
+
/**
|
|
37
|
+
* Retrieves the end session endpoint metadata.
|
|
38
|
+
*
|
|
39
|
+
* @returns {Promise<string>} A promise that resolves to the end session endpoint URL.
|
|
40
|
+
*/
|
|
41
|
+
get endSessionEndpoint(): Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Retrieves the revocation endpoint metadata.
|
|
44
|
+
*
|
|
45
|
+
* @returns {Promise<string>} A promise that resolves to the revocation endpoint URL.
|
|
46
|
+
*/
|
|
47
|
+
get revocationEndpoint(): Promise<string>;
|
|
48
|
+
/**
|
|
49
|
+
* Retrieves the JWKS URI metadata.
|
|
50
|
+
*
|
|
51
|
+
* @returns {Promise<string>} A promise that resolves to the JWKS URI.
|
|
52
|
+
*/
|
|
53
|
+
get jwksUri(): Promise<string>;
|
|
54
|
+
/**
|
|
55
|
+
* Creates an instance of the Metadata class.
|
|
56
|
+
*
|
|
57
|
+
* @param {string} metadataUrl The URL to fetch metadata from.
|
|
58
|
+
*/
|
|
59
|
+
constructor(metadataUrl: string);
|
|
60
|
+
/**
|
|
61
|
+
* Fetches and updates the metadata from the specified URL.
|
|
62
|
+
*
|
|
63
|
+
* @returns {Promise<void>} A promise that resolves once the metadata is fetched.
|
|
64
|
+
*/
|
|
65
|
+
fetchMetadata(): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* Retrieves a specific metadata property.
|
|
68
|
+
*
|
|
69
|
+
* @template K The key of the metadata property.
|
|
70
|
+
* @param {K} key The metadata property key to retrieve.
|
|
71
|
+
* @returns {Promise<MetadataOptions[K]>} A promise that resolves to the value of the specified metadata property.
|
|
72
|
+
*/
|
|
73
|
+
getMetadataProperty<K extends keyof MetadataOptions>(key: K): Promise<MetadataOptions[K]>;
|
|
74
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var n=Object.defineProperty;var i=(a,t,e)=>t in a?n(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var r=(a,t,e)=>i(a,typeof t!="symbol"?t+"":t,e);import{fetch as o}from"./utils/fetch.mjs";class p{constructor(t){r(this,"data",null);this.metadataUrl=t}get issuer(){return this.getMetadataProperty("issuer")}get authorizationEndpoint(){return this.getMetadataProperty("authorization_endpoint")}get tokenEndpoint(){return this.getMetadataProperty("token_endpoint")}get userinfoEndpoint(){return this.getMetadataProperty("userinfo_endpoint")}get endSessionEndpoint(){return this.getMetadataProperty("end_session_endpoint")}get revocationEndpoint(){return this.getMetadataProperty("revocation_endpoint")}get jwksUri(){return this.getMetadataProperty("jwks_uri")}async fetchMetadata(){this.data=await o.get(this.metadataUrl).json()}async getMetadataProperty(t){var e;return(e=this.data)!=null&&e[t]?Promise.resolve(this.data[t]):(await this.fetchMetadata(),Promise.resolve(this.data[t]))}}export{p as Metadata};
|
|
2
|
+
//# sourceMappingURL=Metadata.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Metadata.mjs","sources":["../src/Metadata.ts"],"sourcesContent":["import type { MetadataOptions } from './types';\nimport { fetch } from './utils/fetch';\n\n/**\n * Class responsible for fetching and handling metadata for authentication endpoints.\n */\nexport class Metadata {\n\t/**\n\t * Holds the metadata options once fetched, or null if not yet fetched.\n\t * @protected\n\t */\n\tprotected data: MetadataOptions | null = null;\n\n\t/**\n\t * Retrieves the issuer metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the issuer string.\n\t */\n\tget issuer(): Promise<string> {\n\t\treturn this.getMetadataProperty('issuer');\n\t}\n\n\t/**\n\t * Retrieves the authorization endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the authorization endpoint URL.\n\t */\n\tget authorizationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('authorization_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the token endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the token endpoint URL.\n\t */\n\tget tokenEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('token_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the user info endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the user info endpoint URL.\n\t */\n\tget userinfoEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('userinfo_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the end session endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the end session endpoint URL.\n\t */\n\tget endSessionEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('end_session_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the revocation endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the revocation endpoint URL.\n\t */\n\tget revocationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('revocation_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the JWKS URI metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the JWKS URI.\n\t */\n\tget jwksUri(): Promise<string> {\n\t\treturn this.getMetadataProperty('jwks_uri');\n\t}\n\n\t/**\n\t * Creates an instance of the Metadata class.\n\t *\n\t * @param {string} metadataUrl The URL to fetch metadata from.\n\t */\n\tconstructor(protected metadataUrl: string) {}\n\n\t/**\n\t * Fetches and updates the metadata from the specified URL.\n\t *\n\t * @returns {Promise<void>} A promise that resolves once the metadata is fetched.\n\t */\n\tasync fetchMetadata(): Promise<void> {\n\t\tthis.data = await fetch.get(this.metadataUrl).json<MetadataOptions>();\n\t}\n\n\t/**\n\t * Retrieves a specific metadata property.\n\t *\n\t * @template K The key of the metadata property.\n\t * @param {K} key The metadata property key to retrieve.\n\t * @returns {Promise<MetadataOptions[K]>} A promise that resolves to the value of the specified metadata property.\n\t */\n\tasync getMetadataProperty<K extends keyof MetadataOptions>(key: K): Promise<MetadataOptions[K]> {\n\t\tif (this.data?.[key]) {\n\t\t\treturn Promise.resolve(this.data[key]);\n\t\t}\n\n\t\tawait this.fetchMetadata();\n\n\t\treturn Promise.resolve((this.data as MetadataOptions)[key]);\n\t}\n}\n"],"names":["Metadata","metadataUrl","__publicField","fetch","key","_a"],"mappings":"8MAMO,MAAMA,CAAS,CA2ErB,YAAsBC,EAAqB,CAtEjCC,EAAA,YAA+B,MAsEnB,KAAA,YAAAD,CAAsB,CA/D5C,IAAI,QAA0B,CACtB,OAAA,KAAK,oBAAoB,QAAQ,CACzC,CAOA,IAAI,uBAAyC,CACrC,OAAA,KAAK,oBAAoB,wBAAwB,CACzD,CAOA,IAAI,eAAiC,CAC7B,OAAA,KAAK,oBAAoB,gBAAgB,CACjD,CAOA,IAAI,kBAAoC,CAChC,OAAA,KAAK,oBAAoB,mBAAmB,CACpD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,sBAAsB,CACvD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,qBAAqB,CACtD,CAOA,IAAI,SAA2B,CACvB,OAAA,KAAK,oBAAoB,UAAU,CAC3C,CAcA,MAAM,eAA+B,CACpC,KAAK,KAAO,MAAME,EAAM,IAAI,KAAK,WAAW,EAAE,MAC/C,CASA,MAAM,oBAAqDC,EAAqC,OAC3F,OAAAC,EAAA,KAAK,OAAL,MAAAA,EAAYD,GACR,QAAQ,QAAQ,KAAK,KAAKA,CAAG,CAAC,GAGtC,MAAM,KAAK,gBAEJ,QAAQ,QAAS,KAAK,KAAyBA,CAAG,CAAC,EAC3D,CACD"}
|
package/dist/Session.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var i=Object.defineProperty;var u=(l,e,r)=>e in l?i(l,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):l[e]=r;var t=(l,e,r)=>u(l,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./utils/date.cjs");class s{constructor(){t(this,"state",null);t(this,"code",null);t(this,"error",null);t(this,"error_description",null);t(this,"id_token",null);t(this,"access_token",null);t(this,"refresh_token",null);t(this,"token_type","bearer");t(this,"scope",null);t(this,"expires_at",null);t(this,"claims",null)}get expires_in(){return this.expires_at?this.expires_at-n.timestamp():0}set expires_in(e){e!==null&&!isNaN(e)&&(this.expires_at=Math.floor(e)+n.timestamp())}static load(e){if(!e)return null;let r=new s;try{Object.assign(r,JSON.parse(e))}catch{r=null}return r}}exports.Session=s;
|
|
2
|
+
//# sourceMappingURL=Session.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Session.cjs","sources":["../src/Session.ts"],"sourcesContent":["import type { IdTokenClaims } from './types';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing a user's authentication session, storing tokens and related information.\n */\nexport class Session {\n\t/**\n\t * The state parameter used in the authentication request.\n\t * @type {string | null}\n\t */\n\tstate: string | null = null;\n\n\t/**\n\t * The authorization code returned by the authorization server.\n\t * @type {string | null}\n\t */\n\tcode: string | null = null;\n\n\t/**\n\t * The error returned during the authentication process, if any.\n\t * @type {string | null}\n\t */\n\terror: string | null = null;\n\n\t/**\n\t * A description of the error returned during authentication.\n\t * @type {string | null}\n\t */\n\terror_description: string | null = null;\n\n\t/**\n\t * The ID token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\tid_token: string | null = null;\n\n\t/**\n\t * The access token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\taccess_token: string | null = null;\n\n\t/**\n\t * The refresh token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\trefresh_token: string | null = null;\n\n\t/**\n\t * The type of token issued, defaulting to 'bearer'.\n\t * @type {string}\n\t */\n\ttoken_type = 'bearer';\n\n\t/**\n\t * The scope of the issued token.\n\t * @type {string | null}\n\t */\n\tscope: string | null = null;\n\n\t/**\n\t * The expiration timestamp of the access token, represented in seconds since the epoch.\n\t * @type {number | null}\n\t */\n\texpires_at: number | null = null;\n\n\t/**\n\t * The claims associated with the ID token.\n\t * @type {IdTokenClaims | null}\n\t */\n\tclaims: IdTokenClaims | null = null;\n\n\t/**\n\t * Returns the number of seconds until the access token expires.\n\t * If `expires_at` is not set, returns 0.\n\t *\n\t * @returns {number} The number of seconds until the token expires.\n\t */\n\tget expires_in(): number {\n\t\tif (!this.expires_at) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn this.expires_at - timestamp();\n\t}\n\n\t/**\n\t * Sets the expiration time based on a duration in seconds.\n\t * This also updates the `expires_at` timestamp.\n\t *\n\t * @param {number | null} value The number of seconds until the token expires.\n\t */\n\tset expires_in(value: number | null) {\n\t\tif (value !== null && !isNaN(value)) {\n\t\t\tthis.expires_at = Math.floor(value) + timestamp();\n\t\t}\n\t}\n\n\t/**\n\t * Loads a serialized session from a JSON string.\n\t *\n\t * @param {string | null} serializedSession The JSON string representing a session.\n\t * @returns {Session | null} A new session instance populated with the data from the string, or null if parsing fails.\n\t */\n\tstatic load(serializedSession: string | null): Session | null {\n\t\tif (!serializedSession) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet session: Session | null = new Session();\n\n\t\ttry {\n\t\t\tObject.assign(session, JSON.parse(serializedSession));\n\t\t} catch {\n\t\t\tsession = null;\n\t\t}\n\n\t\treturn session;\n\t}\n}\n"],"names":["Session","__publicField","timestamp","value","serializedSession","session"],"mappings":"wRAMO,MAAMA,CAAQ,CAAd,cAKNC,EAAA,aAAuB,MAMvBA,EAAA,YAAsB,MAMtBA,EAAA,aAAuB,MAMvBA,EAAA,yBAAmC,MAMnCA,EAAA,gBAA0B,MAM1BA,EAAA,oBAA8B,MAM9BA,EAAA,qBAA+B,MAM/BA,EAAA,kBAAa,UAMbA,EAAA,aAAuB,MAMvBA,EAAA,kBAA4B,MAM5BA,EAAA,cAA+B,MAQ/B,IAAI,YAAqB,CACpB,OAAC,KAAK,WAIH,KAAK,WAAaC,EAAAA,YAHjB,CAIT,CAQA,IAAI,WAAWC,EAAsB,CAChCA,IAAU,MAAQ,CAAC,MAAMA,CAAK,IACjC,KAAK,WAAa,KAAK,MAAMA,CAAK,EAAID,EAAAA,YAExC,CAQA,OAAO,KAAKE,EAAkD,CAC7D,GAAI,CAACA,EACG,OAAA,KAGJ,IAAAC,EAA0B,IAAIL,EAE9B,GAAA,CACH,OAAO,OAAOK,EAAS,KAAK,MAAMD,CAAiB,CAAC,CAAA,MAC7C,CACGC,EAAA,IACX,CAEO,OAAAA,CACR,CACD"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { IdTokenClaims } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Class representing a user's authentication session, storing tokens and related information.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Session {
|
|
6
|
+
/**
|
|
7
|
+
* The state parameter used in the authentication request.
|
|
8
|
+
* @type {string | null}
|
|
9
|
+
*/
|
|
10
|
+
state: string | null;
|
|
11
|
+
/**
|
|
12
|
+
* The authorization code returned by the authorization server.
|
|
13
|
+
* @type {string | null}
|
|
14
|
+
*/
|
|
15
|
+
code: string | null;
|
|
16
|
+
/**
|
|
17
|
+
* The error returned during the authentication process, if any.
|
|
18
|
+
* @type {string | null}
|
|
19
|
+
*/
|
|
20
|
+
error: string | null;
|
|
21
|
+
/**
|
|
22
|
+
* A description of the error returned during authentication.
|
|
23
|
+
* @type {string | null}
|
|
24
|
+
*/
|
|
25
|
+
error_description: string | null;
|
|
26
|
+
/**
|
|
27
|
+
* The ID token issued by the authorization server.
|
|
28
|
+
* @type {string | null}
|
|
29
|
+
*/
|
|
30
|
+
id_token: string | null;
|
|
31
|
+
/**
|
|
32
|
+
* The access token issued by the authorization server.
|
|
33
|
+
* @type {string | null}
|
|
34
|
+
*/
|
|
35
|
+
access_token: string | null;
|
|
36
|
+
/**
|
|
37
|
+
* The refresh token issued by the authorization server.
|
|
38
|
+
* @type {string | null}
|
|
39
|
+
*/
|
|
40
|
+
refresh_token: string | null;
|
|
41
|
+
/**
|
|
42
|
+
* The type of token issued, defaulting to 'bearer'.
|
|
43
|
+
* @type {string}
|
|
44
|
+
*/
|
|
45
|
+
token_type: string;
|
|
46
|
+
/**
|
|
47
|
+
* The scope of the issued token.
|
|
48
|
+
* @type {string | null}
|
|
49
|
+
*/
|
|
50
|
+
scope: string | null;
|
|
51
|
+
/**
|
|
52
|
+
* The expiration timestamp of the access token, represented in seconds since the epoch.
|
|
53
|
+
* @type {number | null}
|
|
54
|
+
*/
|
|
55
|
+
expires_at: number | null;
|
|
56
|
+
/**
|
|
57
|
+
* The claims associated with the ID token.
|
|
58
|
+
* @type {IdTokenClaims | null}
|
|
59
|
+
*/
|
|
60
|
+
claims: IdTokenClaims | null;
|
|
61
|
+
/**
|
|
62
|
+
* Returns the number of seconds until the access token expires.
|
|
63
|
+
* If `expires_at` is not set, returns 0.
|
|
64
|
+
*
|
|
65
|
+
* @returns {number} The number of seconds until the token expires.
|
|
66
|
+
*/
|
|
67
|
+
get expires_in(): number;
|
|
68
|
+
/**
|
|
69
|
+
* Sets the expiration time based on a duration in seconds.
|
|
70
|
+
* This also updates the `expires_at` timestamp.
|
|
71
|
+
*
|
|
72
|
+
* @param {number | null} value The number of seconds until the token expires.
|
|
73
|
+
*/
|
|
74
|
+
set expires_in(value: number | null);
|
|
75
|
+
/**
|
|
76
|
+
* Loads a serialized session from a JSON string.
|
|
77
|
+
*
|
|
78
|
+
* @param {string | null} serializedSession The JSON string representing a session.
|
|
79
|
+
* @returns {Session | null} A new session instance populated with the data from the string, or null if parsing fails.
|
|
80
|
+
*/
|
|
81
|
+
static load(serializedSession: string | null): Session | null;
|
|
82
|
+
}
|
package/dist/Session.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var i=Object.defineProperty;var o=(l,e,r)=>e in l?i(l,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):l[e]=r;var t=(l,e,r)=>o(l,typeof e!="symbol"?e+"":e,r);import{timestamp as n}from"./utils/date.mjs";class s{constructor(){t(this,"state",null);t(this,"code",null);t(this,"error",null);t(this,"error_description",null);t(this,"id_token",null);t(this,"access_token",null);t(this,"refresh_token",null);t(this,"token_type","bearer");t(this,"scope",null);t(this,"expires_at",null);t(this,"claims",null)}get expires_in(){return this.expires_at?this.expires_at-n():0}set expires_in(e){e!==null&&!isNaN(e)&&(this.expires_at=Math.floor(e)+n())}static load(e){if(!e)return null;let r=new s;try{Object.assign(r,JSON.parse(e))}catch{r=null}return r}}export{s as Session};
|
|
2
|
+
//# sourceMappingURL=Session.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Session.mjs","sources":["../src/Session.ts"],"sourcesContent":["import type { IdTokenClaims } from './types';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing a user's authentication session, storing tokens and related information.\n */\nexport class Session {\n\t/**\n\t * The state parameter used in the authentication request.\n\t * @type {string | null}\n\t */\n\tstate: string | null = null;\n\n\t/**\n\t * The authorization code returned by the authorization server.\n\t * @type {string | null}\n\t */\n\tcode: string | null = null;\n\n\t/**\n\t * The error returned during the authentication process, if any.\n\t * @type {string | null}\n\t */\n\terror: string | null = null;\n\n\t/**\n\t * A description of the error returned during authentication.\n\t * @type {string | null}\n\t */\n\terror_description: string | null = null;\n\n\t/**\n\t * The ID token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\tid_token: string | null = null;\n\n\t/**\n\t * The access token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\taccess_token: string | null = null;\n\n\t/**\n\t * The refresh token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\trefresh_token: string | null = null;\n\n\t/**\n\t * The type of token issued, defaulting to 'bearer'.\n\t * @type {string}\n\t */\n\ttoken_type = 'bearer';\n\n\t/**\n\t * The scope of the issued token.\n\t * @type {string | null}\n\t */\n\tscope: string | null = null;\n\n\t/**\n\t * The expiration timestamp of the access token, represented in seconds since the epoch.\n\t * @type {number | null}\n\t */\n\texpires_at: number | null = null;\n\n\t/**\n\t * The claims associated with the ID token.\n\t * @type {IdTokenClaims | null}\n\t */\n\tclaims: IdTokenClaims | null = null;\n\n\t/**\n\t * Returns the number of seconds until the access token expires.\n\t * If `expires_at` is not set, returns 0.\n\t *\n\t * @returns {number} The number of seconds until the token expires.\n\t */\n\tget expires_in(): number {\n\t\tif (!this.expires_at) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn this.expires_at - timestamp();\n\t}\n\n\t/**\n\t * Sets the expiration time based on a duration in seconds.\n\t * This also updates the `expires_at` timestamp.\n\t *\n\t * @param {number | null} value The number of seconds until the token expires.\n\t */\n\tset expires_in(value: number | null) {\n\t\tif (value !== null && !isNaN(value)) {\n\t\t\tthis.expires_at = Math.floor(value) + timestamp();\n\t\t}\n\t}\n\n\t/**\n\t * Loads a serialized session from a JSON string.\n\t *\n\t * @param {string | null} serializedSession The JSON string representing a session.\n\t * @returns {Session | null} A new session instance populated with the data from the string, or null if parsing fails.\n\t */\n\tstatic load(serializedSession: string | null): Session | null {\n\t\tif (!serializedSession) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet session: Session | null = new Session();\n\n\t\ttry {\n\t\t\tObject.assign(session, JSON.parse(serializedSession));\n\t\t} catch {\n\t\t\tsession = null;\n\t\t}\n\n\t\treturn session;\n\t}\n}\n"],"names":["Session","__publicField","timestamp","value","serializedSession","session"],"mappings":"iNAMO,MAAMA,CAAQ,CAAd,cAKNC,EAAA,aAAuB,MAMvBA,EAAA,YAAsB,MAMtBA,EAAA,aAAuB,MAMvBA,EAAA,yBAAmC,MAMnCA,EAAA,gBAA0B,MAM1BA,EAAA,oBAA8B,MAM9BA,EAAA,qBAA+B,MAM/BA,EAAA,kBAAa,UAMbA,EAAA,aAAuB,MAMvBA,EAAA,kBAA4B,MAM5BA,EAAA,cAA+B,MAQ/B,IAAI,YAAqB,CACpB,OAAC,KAAK,WAIH,KAAK,WAAaC,IAHjB,CAIT,CAQA,IAAI,WAAWC,EAAsB,CAChCA,IAAU,MAAQ,CAAC,MAAMA,CAAK,IACjC,KAAK,WAAa,KAAK,MAAMA,CAAK,EAAID,IAExC,CAQA,OAAO,KAAKE,EAAkD,CAC7D,GAAI,CAACA,EACG,OAAA,KAGJ,IAAAC,EAA0B,IAAIL,EAE9B,GAAA,CACH,OAAO,OAAOK,EAAS,KAAK,MAAMD,CAAiB,CAAC,CAAA,MAC7C,CACGC,EAAA,IACX,CAEO,OAAAA,CACR,CACD"}
|
package/dist/State.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var o=Object.defineProperty;var d=(n,e,t)=>e in n?o(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var r=(n,e,t)=>d(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./utils/crypto.cjs"),s=require("./utils/date.cjs");require("./utils/base64Url.cjs");class i{constructor(){r(this,"id");r(this,"createdAt");r(this,"codeVerifier");r(this,"codeChallenge");r(this,"nonce")}static async create(){const e=new i;return e.id=c.Crypto.generateState(),e.createdAt=s.timestamp(),e.codeVerifier=c.Crypto.generateCodeVerifier(),e.codeChallenge=await c.Crypto.generateCodeChallenge(e.codeVerifier),e.nonce=c.Crypto.generateNonce(),e}static fromSerializedData(e){const t=new i,a=JSON.parse(e);return t.id=a.id,t.createdAt=a.createdAt,t.codeVerifier=a.codeVerifier,t.codeChallenge=a.codeChallenge,t.nonce=a.nonce,t}}exports.State=i;
|
|
2
|
+
//# sourceMappingURL=State.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"State.cjs","sources":["../src/State.ts"],"sourcesContent":["import { Crypto } from './utils/crypto';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing an OAuth state, including code verifier and nonce for PKCE flows.\n */\nexport class State {\n\t/**\n\t * The unique identifier for the state.\n\t * @type {string}\n\t */\n\tid!: string;\n\n\t/**\n\t * The timestamp when the state was created, represented in seconds since the epoch.\n\t * @type {number}\n\t */\n\tcreatedAt!: number;\n\n\t/**\n\t * The code verifier used in the PKCE (Proof Key for Code Exchange) flow.\n\t * @type {string}\n\t */\n\tcodeVerifier!: string;\n\n\t/**\n\t * The code challenge derived from the code verifier for the PKCE flow.\n\t * @type {string}\n\t */\n\tcodeChallenge!: string;\n\n\t/**\n\t * The nonce value used to associate a client session with an ID token for replay protection.\n\t * @type {string}\n\t */\n\tnonce!: string;\n\n\t/**\n\t * Creates a new instance of `State` with generated values for PKCE and nonce.\n\t *\n\t * @returns {Promise<State>} A promise that resolves to a new `State` instance.\n\t */\n\tstatic async create(): Promise<State> {\n\t\tconst instance = new State();\n\n\t\tinstance.id = Crypto.generateState();\n\t\tinstance.createdAt = timestamp();\n\t\tinstance.codeVerifier = Crypto.generateCodeVerifier();\n\t\tinstance.codeChallenge = await Crypto.generateCodeChallenge(instance.codeVerifier);\n\t\tinstance.nonce = Crypto.generateNonce();\n\n\t\treturn instance as State;\n\t}\n\n\t/**\n\t * Deserializes a `State` instance from a JSON string.\n\t *\n\t * @param {string} serializedData The serialized state data as a JSON string.\n\t * @returns {State} A new `State` instance populated with the deserialized data.\n\t */\n\tstatic fromSerializedData(serializedData: string): State {\n\t\tconst instance = new State();\n\t\tconst data = JSON.parse(serializedData);\n\n\t\tinstance.id = data.id;\n\t\tinstance.createdAt = data.createdAt;\n\t\tinstance.codeVerifier = data.codeVerifier;\n\t\tinstance.codeChallenge = data.codeChallenge;\n\t\tinstance.nonce = data.nonce;\n\n\t\treturn instance;\n\t}\n}\n"],"names":["State","__publicField","instance","Crypto","timestamp","serializedData","data"],"mappings":"yVAMO,MAAMA,CAAM,CAAZ,cAKNC,EAAA,WAMAA,EAAA,kBAMAA,EAAA,qBAMAA,EAAA,sBAMAA,EAAA,cAOA,aAAa,QAAyB,CAC/B,MAAAC,EAAW,IAAIF,EAEZ,OAAAE,EAAA,GAAKC,SAAO,gBACrBD,EAAS,UAAYE,EAAAA,YACZF,EAAA,aAAeC,SAAO,uBAC/BD,EAAS,cAAgB,MAAMC,EAAAA,OAAO,sBAAsBD,EAAS,YAAY,EACxEA,EAAA,MAAQC,SAAO,gBAEjBD,CACR,CAQA,OAAO,mBAAmBG,EAA+B,CAClD,MAAAH,EAAW,IAAIF,EACfM,EAAO,KAAK,MAAMD,CAAc,EAEtC,OAAAH,EAAS,GAAKI,EAAK,GACnBJ,EAAS,UAAYI,EAAK,UAC1BJ,EAAS,aAAeI,EAAK,aAC7BJ,EAAS,cAAgBI,EAAK,cAC9BJ,EAAS,MAAQI,EAAK,MAEfJ,CACR,CACD"}
|
package/dist/State.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Class representing an OAuth state, including code verifier and nonce for PKCE flows.
|
|
3
|
+
*/
|
|
4
|
+
export declare class State {
|
|
5
|
+
/**
|
|
6
|
+
* The unique identifier for the state.
|
|
7
|
+
* @type {string}
|
|
8
|
+
*/
|
|
9
|
+
id: string;
|
|
10
|
+
/**
|
|
11
|
+
* The timestamp when the state was created, represented in seconds since the epoch.
|
|
12
|
+
* @type {number}
|
|
13
|
+
*/
|
|
14
|
+
createdAt: number;
|
|
15
|
+
/**
|
|
16
|
+
* The code verifier used in the PKCE (Proof Key for Code Exchange) flow.
|
|
17
|
+
* @type {string}
|
|
18
|
+
*/
|
|
19
|
+
codeVerifier: string;
|
|
20
|
+
/**
|
|
21
|
+
* The code challenge derived from the code verifier for the PKCE flow.
|
|
22
|
+
* @type {string}
|
|
23
|
+
*/
|
|
24
|
+
codeChallenge: string;
|
|
25
|
+
/**
|
|
26
|
+
* The nonce value used to associate a client session with an ID token for replay protection.
|
|
27
|
+
* @type {string}
|
|
28
|
+
*/
|
|
29
|
+
nonce: string;
|
|
30
|
+
/**
|
|
31
|
+
* Creates a new instance of `State` with generated values for PKCE and nonce.
|
|
32
|
+
*
|
|
33
|
+
* @returns {Promise<State>} A promise that resolves to a new `State` instance.
|
|
34
|
+
*/
|
|
35
|
+
static create(): Promise<State>;
|
|
36
|
+
/**
|
|
37
|
+
* Deserializes a `State` instance from a JSON string.
|
|
38
|
+
*
|
|
39
|
+
* @param {string} serializedData The serialized state data as a JSON string.
|
|
40
|
+
* @returns {State} A new `State` instance populated with the deserialized data.
|
|
41
|
+
*/
|
|
42
|
+
static fromSerializedData(serializedData: string): State;
|
|
43
|
+
}
|
package/dist/State.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var o=Object.defineProperty;var d=(n,e,r)=>e in n?o(n,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):n[e]=r;var t=(n,e,r)=>d(n,typeof e!="symbol"?e+"":e,r);import{Crypto as c}from"./utils/crypto.mjs";import{timestamp as l}from"./utils/date.mjs";import"./utils/base64Url.mjs";class i{constructor(){t(this,"id");t(this,"createdAt");t(this,"codeVerifier");t(this,"codeChallenge");t(this,"nonce")}static async create(){const e=new i;return e.id=c.generateState(),e.createdAt=l(),e.codeVerifier=c.generateCodeVerifier(),e.codeChallenge=await c.generateCodeChallenge(e.codeVerifier),e.nonce=c.generateNonce(),e}static fromSerializedData(e){const r=new i,a=JSON.parse(e);return r.id=a.id,r.createdAt=a.createdAt,r.codeVerifier=a.codeVerifier,r.codeChallenge=a.codeChallenge,r.nonce=a.nonce,r}}export{i as State};
|
|
2
|
+
//# sourceMappingURL=State.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"State.mjs","sources":["../src/State.ts"],"sourcesContent":["import { Crypto } from './utils/crypto';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing an OAuth state, including code verifier and nonce for PKCE flows.\n */\nexport class State {\n\t/**\n\t * The unique identifier for the state.\n\t * @type {string}\n\t */\n\tid!: string;\n\n\t/**\n\t * The timestamp when the state was created, represented in seconds since the epoch.\n\t * @type {number}\n\t */\n\tcreatedAt!: number;\n\n\t/**\n\t * The code verifier used in the PKCE (Proof Key for Code Exchange) flow.\n\t * @type {string}\n\t */\n\tcodeVerifier!: string;\n\n\t/**\n\t * The code challenge derived from the code verifier for the PKCE flow.\n\t * @type {string}\n\t */\n\tcodeChallenge!: string;\n\n\t/**\n\t * The nonce value used to associate a client session with an ID token for replay protection.\n\t * @type {string}\n\t */\n\tnonce!: string;\n\n\t/**\n\t * Creates a new instance of `State` with generated values for PKCE and nonce.\n\t *\n\t * @returns {Promise<State>} A promise that resolves to a new `State` instance.\n\t */\n\tstatic async create(): Promise<State> {\n\t\tconst instance = new State();\n\n\t\tinstance.id = Crypto.generateState();\n\t\tinstance.createdAt = timestamp();\n\t\tinstance.codeVerifier = Crypto.generateCodeVerifier();\n\t\tinstance.codeChallenge = await Crypto.generateCodeChallenge(instance.codeVerifier);\n\t\tinstance.nonce = Crypto.generateNonce();\n\n\t\treturn instance as State;\n\t}\n\n\t/**\n\t * Deserializes a `State` instance from a JSON string.\n\t *\n\t * @param {string} serializedData The serialized state data as a JSON string.\n\t * @returns {State} A new `State` instance populated with the deserialized data.\n\t */\n\tstatic fromSerializedData(serializedData: string): State {\n\t\tconst instance = new State();\n\t\tconst data = JSON.parse(serializedData);\n\n\t\tinstance.id = data.id;\n\t\tinstance.createdAt = data.createdAt;\n\t\tinstance.codeVerifier = data.codeVerifier;\n\t\tinstance.codeChallenge = data.codeChallenge;\n\t\tinstance.nonce = data.nonce;\n\n\t\treturn instance;\n\t}\n}\n"],"names":["State","__publicField","instance","Crypto","timestamp","serializedData","data"],"mappings":"2RAMO,MAAMA,CAAM,CAAZ,cAKNC,EAAA,WAMAA,EAAA,kBAMAA,EAAA,qBAMAA,EAAA,sBAMAA,EAAA,cAOA,aAAa,QAAyB,CAC/B,MAAAC,EAAW,IAAIF,EAEZ,OAAAE,EAAA,GAAKC,EAAO,gBACrBD,EAAS,UAAYE,IACZF,EAAA,aAAeC,EAAO,uBAC/BD,EAAS,cAAgB,MAAMC,EAAO,sBAAsBD,EAAS,YAAY,EACxEA,EAAA,MAAQC,EAAO,gBAEjBD,CACR,CAQA,OAAO,mBAAmBG,EAA+B,CAClD,MAAAH,EAAW,IAAIF,EACfM,EAAO,KAAK,MAAMD,CAAc,EAEtC,OAAAH,EAAS,GAAKI,EAAK,GACnBJ,EAAS,UAAYI,EAAK,UAC1BJ,EAAS,aAAeI,EAAK,aAC7BJ,EAAS,cAAgBI,EAAK,cAC9BJ,EAAS,MAAQI,EAAK,MAEfJ,CACR,CACD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var f=Object.defineProperty;var m=(o,e,s)=>e in o?f(o,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):o[e]=s;var i=(o,e,s)=>m(o,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("../utils/constants.cjs"),p=require("../utils/jwt.cjs"),g=require("../utils/fetch.cjs"),w=require("../utils/date.cjs"),T=require("../Metadata.cjs"),u=require("../Session.cjs"),y=require("../State.cjs");require("../utils/base64Url.cjs");require("../utils/crypto.cjs");const r={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};class E{constructor(e,s){i(this,"isAuthPromise",null);i(this,"httpClient");i(this,"options");i(this,"storage");i(this,"metadata");i(this,"session",null);if(!e.issuer)throw Error("Missing option: issuer");if(!e.clientId)throw Error("Missing option: clientId");if(!e.redirectUri)throw Error("Missing option: redirectUri");if(e.scopes&&!Array.isArray(e.scopes))throw 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.httpClient=g.fetch.create({retry:0}),this.options=e,this.storage=s,this.metadata=new T.Metadata(`${e.issuer}/.well-known/openid-configuration`),this.session=u.Session.load(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}])})}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;return!((e=this.session)!=null&&e.expires_at)||this.session.expires_at<=w.timestamp()}get accessTokenExpirationDate(){var e;return(e=this.session)==null?void 0:e.expires_at}get isAuthenticated(){return this.isAuthPromise?this.isAuthPromise:(this.isAuthPromise=new Promise(async e=>{try{this.refreshToken&&this.accessTokenExpired&&await this.refresh()}catch{}setTimeout(()=>{var s,t;e(!!((s=this.session)!=null&&s.access_token)||!!((t=this.session)!=null&&t.refresh_token)),this.isAuthPromise=null})}),this.isAuthPromise)}async logout(e){if(!_.isBrowser)return;const s=this.session;if(this.storage.delete(this.options.storageTokenName),this.session=null,s!=null&&s.id_token){const t=new URL(await this.metadata.endSessionEndpoint);t.searchParams.append("id_token_hint",s==null?void 0:s.id_token),e!=null&&e.postLogoutRedirectUri&&t.searchParams.append("post_logout_redirect_uri",e.postLogoutRedirectUri),this.dispatchEvent("logoutInitiated",[{idToken:s.id_token,claims:s.claims}]);try{await this.urlHandler(t,e)}catch{}}}async refresh(){var s,t;if(typeof((s=this.session)==null?void 0:s.refresh_token)!="string")throw Error("No refresh token available");const e=this.session;try{const n=await this.sendTokenRequest(await this.metadata.tokenEndpoint,{grant_type:"refresh_token",client_id:this.options.clientId,refresh_token:(t=this.session)==null?void 0:t.refresh_token});Object.assign(this.session,await n.json()),this.session.id_token&&(this.session.claims=p.jwt.decode(this.session.id_token)),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,this.storage.delete(this.options.storageTokenName),this.dispatchEvent("tokenRefreshFailed",[{refreshToken:e.refresh_token}])}}async revoke(){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,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 exchangeCodeForTokens(e={}){var n,a,h,c,d,l;if(this.session=new u.Session,Object.assign(this.session,e),this.session.error)throw Error(`${this.session.error}: ${this.session.error_description}`);if(!this.session.code)throw Error("Invalid or missing code");let s;try{const k=this.storage.get(`sty.${this.session.state}`);if(!k)throw Error();s=y.State.fromSerializedData(k),this.storage.delete(`sty.${this.session.state}`)}catch{throw Error("Invalid or missing state")}const t=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 t.json()),this.session.id_token&&(this.session.claims=p.jwt.decode(this.session.id_token)),this.session.scope!==((n=this.options.scopes)==null?void 0:n.join(" ")))throw Error("Invalid scope");if(((a=this.session.claims)==null?void 0:a.nonce)!==s.nonce)throw Error("Invalid nonce");if(((h=this.session.claims)==null?void 0:h.iss)!==await this.metadata.issuer)throw Error("Invalid iss");if(Array.isArray((c=this.session.claims)==null?void 0:c.aud)?((d=this.session.claims)==null?void 0:d.aud[0])!==this.options.clientId:((l=this.session.claims)==null?void 0:l.aud)!==this.options.clientId)throw Error("Invalid aud");this.storage.set(this.options.storageTokenName,JSON.stringify(this.session))}subscribeToEvent(e,s){return r[e].add(s),{dispose:()=>{r[e].delete(s)}}}dispatchEvent(e,s){for(const t of r[e])t(...s)}async getAuthorizationUrl(e={}){var t;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",(t=this.options.scopes)==null?void 0:t.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 sendTokenRequest(e,s={}){return await this.httpClient.post(e,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s)})}}exports.BaseFlow=E;
|
|
2
|
+
//# sourceMappingURL=BaseFlow.cjs.map
|
|
@@ -0,0 +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":"+g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MAAM,EAC5EA,EAAI,aAAa,OAAO,gBAAiB,KAAK,QAAQ,cAAgB,UAAU,EAC5EA,EAAA,aAAa,OAAO,SAASN,EAAA,KAAK,QAAQ,SAAb,YAAAA,EAAqB,KAAK,IAAc,EACrEM,EAAA,aAAa,OAAO,wBAAyB,MAAM,EAEnDZ,EAAQ,QACXY,EAAI,aAAa,OAAO,SAAUZ,EAAQ,MAAM,EAE7CA,EAAQ,WACXY,EAAI,aAAa,OAAO,aAAcZ,EAAQ,UAAU,KAAK,GAAG,CAAC,EAE9DA,EAAQ,WACXY,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"}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { KyInstance } from 'ky';
|
|
2
|
+
import { IdTokenClaims, SDKOptions, SDKStorage, EventFunctions, ExtraRequestArgs, LogoutOptions } from '../types';
|
|
3
|
+
import { Metadata } from '../Metadata';
|
|
4
|
+
import { Session } from '../Session';
|
|
5
|
+
/**
|
|
6
|
+
* An abstract base class that provides common functionality for different OIDC flows.
|
|
7
|
+
*
|
|
8
|
+
* @template Options - The options type extending `SDKOptions` used for configuring the flow.
|
|
9
|
+
* @template URLHandlerOptions - The options type extending `ExtraRequestArgs` used for URL handling.
|
|
10
|
+
*/
|
|
11
|
+
export declare abstract class BaseFlow<Options extends SDKOptions, URLHandlerOptions extends ExtraRequestArgs> {
|
|
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;
|
|
18
|
+
/**
|
|
19
|
+
* An instance of the HTTP client used for making requests.
|
|
20
|
+
*
|
|
21
|
+
* @type {KyInstance}
|
|
22
|
+
*/
|
|
23
|
+
protected httpClient: KyInstance;
|
|
24
|
+
/**
|
|
25
|
+
* The configuration options for the flow.
|
|
26
|
+
*
|
|
27
|
+
* @type {Options}
|
|
28
|
+
*/
|
|
29
|
+
protected options: Options;
|
|
30
|
+
/**
|
|
31
|
+
* The storage mechanism used to persist session data.
|
|
32
|
+
*
|
|
33
|
+
* @type {SDKStorage}
|
|
34
|
+
*/
|
|
35
|
+
protected storage: SDKStorage;
|
|
36
|
+
/**
|
|
37
|
+
* Metadata information about the authorization server.
|
|
38
|
+
*
|
|
39
|
+
* @type {Metadata}
|
|
40
|
+
*/
|
|
41
|
+
protected metadata: Metadata;
|
|
42
|
+
/**
|
|
43
|
+
* The current session data.
|
|
44
|
+
*
|
|
45
|
+
* @type {Session | null}
|
|
46
|
+
*/
|
|
47
|
+
protected session: Session | null;
|
|
48
|
+
/**
|
|
49
|
+
* Retrieves the ID token claims from the current session.
|
|
50
|
+
*
|
|
51
|
+
* @type {IdTokenClaims | null | undefined}
|
|
52
|
+
*/
|
|
53
|
+
get idTokenClaims(): IdTokenClaims | null | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* Retrieves the access token from the current session.
|
|
56
|
+
*
|
|
57
|
+
* @type {string | null | undefined}
|
|
58
|
+
*/
|
|
59
|
+
get accessToken(): string | null | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Retrieves the refresh token from the current session.
|
|
62
|
+
*
|
|
63
|
+
* @type {string | null | undefined}
|
|
64
|
+
*/
|
|
65
|
+
get refreshToken(): string | null | undefined;
|
|
66
|
+
/**
|
|
67
|
+
* Determines if the access token has expired.
|
|
68
|
+
*
|
|
69
|
+
* @type {boolean}
|
|
70
|
+
*/
|
|
71
|
+
get accessTokenExpired(): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Retrieves the access token expiration date.
|
|
74
|
+
*
|
|
75
|
+
* @type {number | null | undefined}
|
|
76
|
+
*/
|
|
77
|
+
get accessTokenExpirationDate(): number | null | undefined;
|
|
78
|
+
/**
|
|
79
|
+
* Checks if the user is authenticated by evaluating the presence of access or refresh tokens.
|
|
80
|
+
*
|
|
81
|
+
* @returns {Promise<boolean>} - A promise that resolves to `true` if the user is authenticated, otherwise `false`.
|
|
82
|
+
*/
|
|
83
|
+
get isAuthenticated(): Promise<boolean>;
|
|
84
|
+
/**
|
|
85
|
+
* Constructs a new instance of the `BaseFlow` class.
|
|
86
|
+
*
|
|
87
|
+
* @param {Options} options - Configuration options for the flow.
|
|
88
|
+
* @param {SDKStorage} storage - Storage mechanism for session data.
|
|
89
|
+
*
|
|
90
|
+
* @throws {Error} Throws an error if required options are missing or invalid.
|
|
91
|
+
*/
|
|
92
|
+
constructor(options: Options, storage: SDKStorage);
|
|
93
|
+
/**
|
|
94
|
+
* Initiates the login process. Subclasses should implement this method to handle the specific login flow.
|
|
95
|
+
*
|
|
96
|
+
* @param {URLHandlerOptions} [options] - Additional options for handling URLs during login.
|
|
97
|
+
* @returns {Promise<void>} - A promise that resolves when the login process is complete.
|
|
98
|
+
*/
|
|
99
|
+
abstract login(options?: URLHandlerOptions): Promise<void>;
|
|
100
|
+
/**
|
|
101
|
+
* Registers a new user. Subclasses should implement this method to handle the specific registration flow.
|
|
102
|
+
*
|
|
103
|
+
* @param {URLHandlerOptions} [options] - Additional options for handling URLs during registration.
|
|
104
|
+
* @returns {Promise<void>} - A promise that resolves when the registration process is complete.
|
|
105
|
+
*/
|
|
106
|
+
abstract register(options?: URLHandlerOptions): Promise<void>;
|
|
107
|
+
/**
|
|
108
|
+
* Logs out the current user and optionally redirects to a post-logout URI.
|
|
109
|
+
*
|
|
110
|
+
* @param {URLHandlerOptions & LogoutOptions} [options] - Additional options for handling URLs during logout.
|
|
111
|
+
* @returns {Promise<void>} - A promise that resolves when the logout process is complete.
|
|
112
|
+
*/
|
|
113
|
+
logout(options?: URLHandlerOptions & LogoutOptions): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Refreshes the access token using the refresh token.
|
|
116
|
+
*
|
|
117
|
+
* @returns {Promise<void>} - A promise that resolves when the token refresh is complete.
|
|
118
|
+
*
|
|
119
|
+
* @throws {Error} Throws an error if no refresh token is available or if the refresh fails.
|
|
120
|
+
*/
|
|
121
|
+
refresh(): Promise<void>;
|
|
122
|
+
/**
|
|
123
|
+
* Revokes the current access or refresh token.
|
|
124
|
+
*
|
|
125
|
+
* @returns {Promise<void>} - A promise that resolves when the token revocation is complete.
|
|
126
|
+
*/
|
|
127
|
+
revoke(): Promise<void>;
|
|
128
|
+
/**
|
|
129
|
+
* Exchanges an authorization code for access and refresh tokens.
|
|
130
|
+
*
|
|
131
|
+
* @param {Record<string, string>} [params={}] - Parameters containing the authorization code and other required values.
|
|
132
|
+
* @returns {Promise<void>} - A promise that resolves when the token exchange is complete.
|
|
133
|
+
*
|
|
134
|
+
* @throws {Error} Throws an error if the authorization code is invalid or if there are issues with state, nonce, or tokens.
|
|
135
|
+
*/
|
|
136
|
+
exchangeCodeForTokens(params?: Record<string, string>): Promise<void>;
|
|
137
|
+
/**
|
|
138
|
+
* Subscribes a callback function to an event.
|
|
139
|
+
*
|
|
140
|
+
* @param {T} eventName - The name of the event to subscribe to.
|
|
141
|
+
* @param {(...params: Parameters<EventFunctions[T]>) => Promise<void> | void} callbackFn - The callback function to execute when the event is dispatched.
|
|
142
|
+
* @returns {{ dispose: () => void }} - An object with a `dispose` method to remove the subscription.
|
|
143
|
+
*/
|
|
144
|
+
subscribeToEvent<T extends keyof EventFunctions>(eventName: T, callbackFn: (...params: Parameters<EventFunctions[T]>) => Promise<void> | void): {
|
|
145
|
+
dispose: () => void;
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Dispatches an event to all subscribed callback functions.
|
|
149
|
+
*
|
|
150
|
+
* @param {T} eventName - The name of the event to dispatch.
|
|
151
|
+
* @param {Parameters<EventFunctions[T]>} args - The arguments to pass to the callback functions.
|
|
152
|
+
*/
|
|
153
|
+
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
|
+
}
|