@logto/client 2.3.3 → 3.0.0-alpha.1
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/lib/adapter/defaults.cjs +28 -0
- package/lib/adapter/defaults.d.ts +10 -0
- package/lib/adapter/defaults.js +25 -0
- package/lib/adapter/index.d.ts +3 -3
- package/lib/adapter/types.d.ts +35 -7
- package/lib/client.cjs +383 -0
- package/lib/client.d.ts +153 -0
- package/lib/client.js +381 -0
- package/lib/index.cjs +11 -381
- package/lib/index.d.ts +6 -149
- package/lib/index.js +10 -382
- package/lib/mock.d.ts +0 -1
- package/lib/shim.cjs +66 -0
- package/lib/shim.d.ts +13 -0
- package/lib/shim.js +7 -0
- package/lib/utils/requester.cjs +1 -0
- package/lib/utils/requester.js +1 -0
- package/package.json +14 -6
- package/lib/remote-jwk-set.cjs +0 -62
- package/lib/remote-jwk-set.d.ts +0 -10
- package/lib/remote-jwk-set.js +0 -60
- /package/lib/{remote-jwk-set.test.d.ts → adapter/defaults.test.d.ts} +0 -0
package/lib/client.d.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { type IdTokenClaims, type UserInfoResponse, type InteractionMode, type AccessTokenClaims, type OidcConfigResponse } from '@logto/js';
|
|
2
|
+
import { type Nullable } from '@silverhand/essentials';
|
|
3
|
+
import { ClientAdapterInstance, type ClientAdapter, type JwtVerifier } from './adapter/index.js';
|
|
4
|
+
import type { AccessToken, LogtoConfig, LogtoSignInSessionItem } from './types/index.js';
|
|
5
|
+
/**
|
|
6
|
+
* The Logto base client class that provides the essential methods for
|
|
7
|
+
* interacting with the Logto server.
|
|
8
|
+
*
|
|
9
|
+
* It also provides an adapter object that allows the customizations of the
|
|
10
|
+
* client behavior for different environments.
|
|
11
|
+
*
|
|
12
|
+
* NOTE: Usually, you would use the `LogtoClient` class instead of `StandardLogtoClient` since it
|
|
13
|
+
* provides the default JWT verifier. However, if you want to avoid the use of `jose` package
|
|
14
|
+
* which is useful for certain environments that don't support native modules like `crypto`, you
|
|
15
|
+
* can use `StandardLogtoClient` and provide your own JWT verifier.
|
|
16
|
+
*/
|
|
17
|
+
export declare class StandardLogtoClient {
|
|
18
|
+
#private;
|
|
19
|
+
readonly logtoConfig: LogtoConfig;
|
|
20
|
+
/**
|
|
21
|
+
* Get the OIDC configuration from the discovery endpoint. This method will
|
|
22
|
+
* only fetch the configuration once and cache the result.
|
|
23
|
+
*/
|
|
24
|
+
readonly getOidcConfig: () => Promise<OidcConfigResponse>;
|
|
25
|
+
/**
|
|
26
|
+
* Get the access token from the storage with refresh strategy.
|
|
27
|
+
*
|
|
28
|
+
* - If the access token has expired, it will try to fetch a new one using the Refresh Token.
|
|
29
|
+
* - If there's an ongoing Promise to fetch the access token, it will return the Promise.
|
|
30
|
+
*
|
|
31
|
+
* If you want to get the access token claims, use {@link getAccessTokenClaims} instead.
|
|
32
|
+
*
|
|
33
|
+
* @param resource The resource that the access token is granted for. If not
|
|
34
|
+
* specified, the access token will be used for OpenID Connect or the default
|
|
35
|
+
* resource, as specified in the Logto Console.
|
|
36
|
+
* @returns The access token string.
|
|
37
|
+
* @throws LogtoClientError if the user is not authenticated.
|
|
38
|
+
*/
|
|
39
|
+
readonly getAccessToken: (this: unknown, resource?: string | undefined, organizationId?: string | undefined) => Promise<string>;
|
|
40
|
+
/**
|
|
41
|
+
* Get the access token for the specified organization from the storage with refresh strategy.
|
|
42
|
+
*
|
|
43
|
+
* Scope {@link UserScope.Organizations} is required in the config to use organization-related
|
|
44
|
+
* methods.
|
|
45
|
+
*
|
|
46
|
+
* @param organizationId The ID of the organization that the access token is granted for.
|
|
47
|
+
* @returns The access token string.
|
|
48
|
+
* @throws LogtoClientError if the user is not authenticated.
|
|
49
|
+
* @remarks
|
|
50
|
+
* It uses the same refresh strategy as {@link getAccessToken}.
|
|
51
|
+
*/
|
|
52
|
+
readonly getOrganizationToken: (this: unknown, organizationId: string) => Promise<string>;
|
|
53
|
+
/**
|
|
54
|
+
* Handle the sign-in callback by parsing the authorization code from the
|
|
55
|
+
* callback URI and exchanging it for the tokens.
|
|
56
|
+
*
|
|
57
|
+
* @param callbackUri The callback URI, including the search params, that the user is redirected to after the sign-in flow is completed.
|
|
58
|
+
* The origin and pathname of this URI must match the origin and pathname of the redirect URI specified in {@link signIn}.
|
|
59
|
+
* In many cases you'll probably end up passing `window.location.href` as the argument to this function.
|
|
60
|
+
* @throws LogtoClientError if the sign-in session is not found.
|
|
61
|
+
*/
|
|
62
|
+
readonly handleSignInCallback: (this: unknown, callbackUri: string) => Promise<void>;
|
|
63
|
+
readonly adapter: ClientAdapterInstance;
|
|
64
|
+
readonly jwtVerifier: JwtVerifier;
|
|
65
|
+
protected readonly accessTokenMap: Map<string, AccessToken>;
|
|
66
|
+
constructor(logtoConfig: LogtoConfig, adapter: ClientAdapter, buildJwtVerifier: (client: StandardLogtoClient) => JwtVerifier);
|
|
67
|
+
/**
|
|
68
|
+
* Check if the user is authenticated by checking if the ID token exists.
|
|
69
|
+
*/
|
|
70
|
+
isAuthenticated(): Promise<boolean>;
|
|
71
|
+
/**
|
|
72
|
+
* Get the Refresh Token from the storage.
|
|
73
|
+
*/
|
|
74
|
+
getRefreshToken(): Promise<Nullable<string>>;
|
|
75
|
+
/**
|
|
76
|
+
* Get the ID Token from the storage. If you want to get the ID Token claims,
|
|
77
|
+
* use {@link getIdTokenClaims} instead.
|
|
78
|
+
*/
|
|
79
|
+
getIdToken(): Promise<Nullable<string>>;
|
|
80
|
+
/**
|
|
81
|
+
* Get the ID Token claims.
|
|
82
|
+
*/
|
|
83
|
+
getIdTokenClaims(): Promise<IdTokenClaims>;
|
|
84
|
+
/**
|
|
85
|
+
* Get the access token claims for the specified resource.
|
|
86
|
+
*
|
|
87
|
+
* @param resource The resource that the access token is granted for. If not
|
|
88
|
+
* specified, the access token will be used for OpenID Connect or the default
|
|
89
|
+
* resource, as specified in the Logto Console.
|
|
90
|
+
*/
|
|
91
|
+
getAccessTokenClaims(resource?: string): Promise<AccessTokenClaims>;
|
|
92
|
+
/**
|
|
93
|
+
* Get the organization token claims for the specified organization.
|
|
94
|
+
*
|
|
95
|
+
* @param organizationId The ID of the organization that the access token is granted for.
|
|
96
|
+
*/
|
|
97
|
+
getOrganizationTokenClaims(organizationId: string): Promise<AccessTokenClaims>;
|
|
98
|
+
/**
|
|
99
|
+
* Get the user information from the Userinfo Endpoint.
|
|
100
|
+
*
|
|
101
|
+
* Note the Userinfo Endpoint will return more claims than the ID Token. See
|
|
102
|
+
* {@link https://docs.logto.io/docs/recipes/integrate-logto/vanilla-js/#fetch-user-information | Fetch user information}
|
|
103
|
+
* for more information.
|
|
104
|
+
*
|
|
105
|
+
* @returns The user information.
|
|
106
|
+
* @throws LogtoClientError if the user is not authenticated.
|
|
107
|
+
*/
|
|
108
|
+
fetchUserInfo(): Promise<UserInfoResponse>;
|
|
109
|
+
/**
|
|
110
|
+
* Start the sign-in flow with the specified redirect URI. The URI must be
|
|
111
|
+
* registered in the Logto Console.
|
|
112
|
+
*
|
|
113
|
+
* The user will be redirected to that URI after the sign-in flow is completed,
|
|
114
|
+
* and the client will be able to get the authorization code from the URI.
|
|
115
|
+
* To fetch the tokens from the authorization code, use {@link handleSignInCallback}
|
|
116
|
+
* after the user is redirected in the callback URI.
|
|
117
|
+
*
|
|
118
|
+
* @param redirectUri The redirect URI that the user will be redirected to after the sign-in flow is completed.
|
|
119
|
+
* @param interactionMode The interaction mode to be used for the authorization request. Note it's not
|
|
120
|
+
* a part of the OIDC standard, but a Logto-specific extension. Defaults to `signIn`.
|
|
121
|
+
*
|
|
122
|
+
* @see {@link https://docs.logto.io/docs/recipes/integrate-logto/vanilla-js/#sign-in | Sign in} for more information.
|
|
123
|
+
* @see {@link InteractionMode}
|
|
124
|
+
*/
|
|
125
|
+
signIn(redirectUri: string, interactionMode?: InteractionMode): Promise<void>;
|
|
126
|
+
/**
|
|
127
|
+
* Check if the user is redirected from the sign-in page by checking if the
|
|
128
|
+
* current URL matches the redirect URI in the sign-in session.
|
|
129
|
+
*
|
|
130
|
+
* If there's no sign-in session, it will return `false`.
|
|
131
|
+
*
|
|
132
|
+
* @param url The current URL.
|
|
133
|
+
*/
|
|
134
|
+
isSignInRedirected(url: string): Promise<boolean>;
|
|
135
|
+
/**
|
|
136
|
+
* Start the sign-out flow with the specified redirect URI. The URI must be
|
|
137
|
+
* registered in the Logto Console.
|
|
138
|
+
*
|
|
139
|
+
* It will also revoke all the tokens and clean up the storage.
|
|
140
|
+
*
|
|
141
|
+
* The user will be redirected that URI after the sign-out flow is completed.
|
|
142
|
+
* If the `postLogoutRedirectUri` is not specified, the user will be redirected
|
|
143
|
+
* to a default page.
|
|
144
|
+
*/
|
|
145
|
+
signOut(postLogoutRedirectUri?: string): Promise<void>;
|
|
146
|
+
protected getSignInSession(): Promise<Nullable<LogtoSignInSessionItem>>;
|
|
147
|
+
protected setSignInSession(value: Nullable<LogtoSignInSessionItem>): Promise<void>;
|
|
148
|
+
private setIdToken;
|
|
149
|
+
private setRefreshToken;
|
|
150
|
+
private getAccessTokenByRefreshToken;
|
|
151
|
+
private saveAccessTokenMap;
|
|
152
|
+
private loadAccessTokenMap;
|
|
153
|
+
}
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { decodeIdToken, decodeAccessToken, fetchUserInfo, generateSignInUri, revoke, generateSignOutUri, fetchTokenByRefreshToken, fetchOidcConfig, UserScope, verifyAndParseCodeFromCallbackUri, fetchTokenByAuthorizationCode } from '@logto/js';
|
|
2
|
+
import { ClientAdapterInstance } from './adapter/index.js';
|
|
3
|
+
import { LogtoClientError } from './errors.js';
|
|
4
|
+
import { normalizeLogtoConfig, isLogtoSignInSessionItem, isLogtoAccessTokenMap } from './types/index.js';
|
|
5
|
+
import { buildAccessTokenKey, getDiscoveryEndpoint } from './utils/index.js';
|
|
6
|
+
import { memoize } from './utils/memoize.js';
|
|
7
|
+
import { once } from './utils/once.js';
|
|
8
|
+
import { PersistKey, CacheKey } from './adapter/types.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The Logto base client class that provides the essential methods for
|
|
12
|
+
* interacting with the Logto server.
|
|
13
|
+
*
|
|
14
|
+
* It also provides an adapter object that allows the customizations of the
|
|
15
|
+
* client behavior for different environments.
|
|
16
|
+
*
|
|
17
|
+
* NOTE: Usually, you would use the `LogtoClient` class instead of `StandardLogtoClient` since it
|
|
18
|
+
* provides the default JWT verifier. However, if you want to avoid the use of `jose` package
|
|
19
|
+
* which is useful for certain environments that don't support native modules like `crypto`, you
|
|
20
|
+
* can use `StandardLogtoClient` and provide your own JWT verifier.
|
|
21
|
+
*/
|
|
22
|
+
class StandardLogtoClient {
|
|
23
|
+
constructor(logtoConfig, adapter, buildJwtVerifier) {
|
|
24
|
+
/**
|
|
25
|
+
* Get the OIDC configuration from the discovery endpoint. This method will
|
|
26
|
+
* only fetch the configuration once and cache the result.
|
|
27
|
+
*/
|
|
28
|
+
this.getOidcConfig = once(this.#getOidcConfig);
|
|
29
|
+
/**
|
|
30
|
+
* Get the access token from the storage with refresh strategy.
|
|
31
|
+
*
|
|
32
|
+
* - If the access token has expired, it will try to fetch a new one using the Refresh Token.
|
|
33
|
+
* - If there's an ongoing Promise to fetch the access token, it will return the Promise.
|
|
34
|
+
*
|
|
35
|
+
* If you want to get the access token claims, use {@link getAccessTokenClaims} instead.
|
|
36
|
+
*
|
|
37
|
+
* @param resource The resource that the access token is granted for. If not
|
|
38
|
+
* specified, the access token will be used for OpenID Connect or the default
|
|
39
|
+
* resource, as specified in the Logto Console.
|
|
40
|
+
* @returns The access token string.
|
|
41
|
+
* @throws LogtoClientError if the user is not authenticated.
|
|
42
|
+
*/
|
|
43
|
+
this.getAccessToken = memoize(this.#getAccessToken);
|
|
44
|
+
/**
|
|
45
|
+
* Get the access token for the specified organization from the storage with refresh strategy.
|
|
46
|
+
*
|
|
47
|
+
* Scope {@link UserScope.Organizations} is required in the config to use organization-related
|
|
48
|
+
* methods.
|
|
49
|
+
*
|
|
50
|
+
* @param organizationId The ID of the organization that the access token is granted for.
|
|
51
|
+
* @returns The access token string.
|
|
52
|
+
* @throws LogtoClientError if the user is not authenticated.
|
|
53
|
+
* @remarks
|
|
54
|
+
* It uses the same refresh strategy as {@link getAccessToken}.
|
|
55
|
+
*/
|
|
56
|
+
this.getOrganizationToken = memoize(this.#getOrganizationToken);
|
|
57
|
+
/**
|
|
58
|
+
* Handle the sign-in callback by parsing the authorization code from the
|
|
59
|
+
* callback URI and exchanging it for the tokens.
|
|
60
|
+
*
|
|
61
|
+
* @param callbackUri The callback URI, including the search params, that the user is redirected to after the sign-in flow is completed.
|
|
62
|
+
* The origin and pathname of this URI must match the origin and pathname of the redirect URI specified in {@link signIn}.
|
|
63
|
+
* In many cases you'll probably end up passing `window.location.href` as the argument to this function.
|
|
64
|
+
* @throws LogtoClientError if the sign-in session is not found.
|
|
65
|
+
*/
|
|
66
|
+
this.handleSignInCallback = memoize(this.#handleSignInCallback);
|
|
67
|
+
this.accessTokenMap = new Map();
|
|
68
|
+
this.logtoConfig = normalizeLogtoConfig(logtoConfig);
|
|
69
|
+
this.adapter = new ClientAdapterInstance(adapter);
|
|
70
|
+
this.jwtVerifier = buildJwtVerifier(this);
|
|
71
|
+
void this.loadAccessTokenMap();
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Check if the user is authenticated by checking if the ID token exists.
|
|
75
|
+
*/
|
|
76
|
+
async isAuthenticated() {
|
|
77
|
+
return Boolean(await this.getIdToken());
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Get the Refresh Token from the storage.
|
|
81
|
+
*/
|
|
82
|
+
async getRefreshToken() {
|
|
83
|
+
return this.adapter.storage.getItem('refreshToken');
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Get the ID Token from the storage. If you want to get the ID Token claims,
|
|
87
|
+
* use {@link getIdTokenClaims} instead.
|
|
88
|
+
*/
|
|
89
|
+
async getIdToken() {
|
|
90
|
+
return this.adapter.storage.getItem('idToken');
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Get the ID Token claims.
|
|
94
|
+
*/
|
|
95
|
+
async getIdTokenClaims() {
|
|
96
|
+
const idToken = await this.getIdToken();
|
|
97
|
+
if (!idToken) {
|
|
98
|
+
throw new LogtoClientError('not_authenticated');
|
|
99
|
+
}
|
|
100
|
+
return decodeIdToken(idToken);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Get the access token claims for the specified resource.
|
|
104
|
+
*
|
|
105
|
+
* @param resource The resource that the access token is granted for. If not
|
|
106
|
+
* specified, the access token will be used for OpenID Connect or the default
|
|
107
|
+
* resource, as specified in the Logto Console.
|
|
108
|
+
*/
|
|
109
|
+
async getAccessTokenClaims(resource) {
|
|
110
|
+
const accessToken = await this.getAccessToken(resource);
|
|
111
|
+
return decodeAccessToken(accessToken);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Get the organization token claims for the specified organization.
|
|
115
|
+
*
|
|
116
|
+
* @param organizationId The ID of the organization that the access token is granted for.
|
|
117
|
+
*/
|
|
118
|
+
async getOrganizationTokenClaims(organizationId) {
|
|
119
|
+
const accessToken = await this.getOrganizationToken(organizationId);
|
|
120
|
+
return decodeAccessToken(accessToken);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Get the user information from the Userinfo Endpoint.
|
|
124
|
+
*
|
|
125
|
+
* Note the Userinfo Endpoint will return more claims than the ID Token. See
|
|
126
|
+
* {@link https://docs.logto.io/docs/recipes/integrate-logto/vanilla-js/#fetch-user-information | Fetch user information}
|
|
127
|
+
* for more information.
|
|
128
|
+
*
|
|
129
|
+
* @returns The user information.
|
|
130
|
+
* @throws LogtoClientError if the user is not authenticated.
|
|
131
|
+
*/
|
|
132
|
+
async fetchUserInfo() {
|
|
133
|
+
const { userinfoEndpoint } = await this.getOidcConfig();
|
|
134
|
+
const accessToken = await this.getAccessToken();
|
|
135
|
+
if (!accessToken) {
|
|
136
|
+
throw new LogtoClientError('fetch_user_info_failed');
|
|
137
|
+
}
|
|
138
|
+
return fetchUserInfo(userinfoEndpoint, accessToken, this.adapter.requester);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Start the sign-in flow with the specified redirect URI. The URI must be
|
|
142
|
+
* registered in the Logto Console.
|
|
143
|
+
*
|
|
144
|
+
* The user will be redirected to that URI after the sign-in flow is completed,
|
|
145
|
+
* and the client will be able to get the authorization code from the URI.
|
|
146
|
+
* To fetch the tokens from the authorization code, use {@link handleSignInCallback}
|
|
147
|
+
* after the user is redirected in the callback URI.
|
|
148
|
+
*
|
|
149
|
+
* @param redirectUri The redirect URI that the user will be redirected to after the sign-in flow is completed.
|
|
150
|
+
* @param interactionMode The interaction mode to be used for the authorization request. Note it's not
|
|
151
|
+
* a part of the OIDC standard, but a Logto-specific extension. Defaults to `signIn`.
|
|
152
|
+
*
|
|
153
|
+
* @see {@link https://docs.logto.io/docs/recipes/integrate-logto/vanilla-js/#sign-in | Sign in} for more information.
|
|
154
|
+
* @see {@link InteractionMode}
|
|
155
|
+
*/
|
|
156
|
+
async signIn(redirectUri, interactionMode) {
|
|
157
|
+
const { appId: clientId, prompt, resources, scopes } = this.logtoConfig;
|
|
158
|
+
const { authorizationEndpoint } = await this.getOidcConfig();
|
|
159
|
+
const [codeVerifier, state] = await Promise.all([
|
|
160
|
+
this.adapter.generateCodeVerifier(),
|
|
161
|
+
this.adapter.generateState(),
|
|
162
|
+
]);
|
|
163
|
+
const codeChallenge = await this.adapter.generateCodeChallenge(codeVerifier);
|
|
164
|
+
const signInUri = generateSignInUri({
|
|
165
|
+
authorizationEndpoint,
|
|
166
|
+
clientId,
|
|
167
|
+
redirectUri,
|
|
168
|
+
codeChallenge,
|
|
169
|
+
state,
|
|
170
|
+
scopes,
|
|
171
|
+
resources,
|
|
172
|
+
prompt,
|
|
173
|
+
interactionMode,
|
|
174
|
+
});
|
|
175
|
+
await Promise.all([
|
|
176
|
+
this.setSignInSession({ redirectUri, codeVerifier, state }),
|
|
177
|
+
this.setRefreshToken(null),
|
|
178
|
+
this.setIdToken(null),
|
|
179
|
+
]);
|
|
180
|
+
await this.adapter.navigate(signInUri, { redirectUri, for: 'sign-in' });
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Check if the user is redirected from the sign-in page by checking if the
|
|
184
|
+
* current URL matches the redirect URI in the sign-in session.
|
|
185
|
+
*
|
|
186
|
+
* If there's no sign-in session, it will return `false`.
|
|
187
|
+
*
|
|
188
|
+
* @param url The current URL.
|
|
189
|
+
*/
|
|
190
|
+
async isSignInRedirected(url) {
|
|
191
|
+
const signInSession = await this.getSignInSession();
|
|
192
|
+
if (!signInSession) {
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
const { redirectUri } = signInSession;
|
|
196
|
+
const { origin, pathname } = new URL(url);
|
|
197
|
+
return `${origin}${pathname}` === redirectUri;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Start the sign-out flow with the specified redirect URI. The URI must be
|
|
201
|
+
* registered in the Logto Console.
|
|
202
|
+
*
|
|
203
|
+
* It will also revoke all the tokens and clean up the storage.
|
|
204
|
+
*
|
|
205
|
+
* The user will be redirected that URI after the sign-out flow is completed.
|
|
206
|
+
* If the `postLogoutRedirectUri` is not specified, the user will be redirected
|
|
207
|
+
* to a default page.
|
|
208
|
+
*/
|
|
209
|
+
async signOut(postLogoutRedirectUri) {
|
|
210
|
+
const { appId: clientId } = this.logtoConfig;
|
|
211
|
+
const { endSessionEndpoint, revocationEndpoint } = await this.getOidcConfig();
|
|
212
|
+
const refreshToken = await this.getRefreshToken();
|
|
213
|
+
if (refreshToken) {
|
|
214
|
+
try {
|
|
215
|
+
await revoke(revocationEndpoint, clientId, refreshToken, this.adapter.requester);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
// Do nothing at this point, as we don't want to break the sign-out flow even if the revocation is failed
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const url = generateSignOutUri({
|
|
222
|
+
endSessionEndpoint,
|
|
223
|
+
postLogoutRedirectUri,
|
|
224
|
+
clientId,
|
|
225
|
+
});
|
|
226
|
+
this.accessTokenMap.clear();
|
|
227
|
+
await Promise.all([
|
|
228
|
+
this.setRefreshToken(null),
|
|
229
|
+
this.setIdToken(null),
|
|
230
|
+
this.adapter.storage.removeItem('accessToken'),
|
|
231
|
+
]);
|
|
232
|
+
await this.adapter.navigate(url, { redirectUri: postLogoutRedirectUri, for: 'sign-out' });
|
|
233
|
+
}
|
|
234
|
+
async getSignInSession() {
|
|
235
|
+
const jsonItem = await this.adapter.storage.getItem('signInSession');
|
|
236
|
+
if (!jsonItem) {
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
const item = JSON.parse(jsonItem);
|
|
240
|
+
if (!isLogtoSignInSessionItem(item)) {
|
|
241
|
+
throw new LogtoClientError('sign_in_session.invalid');
|
|
242
|
+
}
|
|
243
|
+
return item;
|
|
244
|
+
}
|
|
245
|
+
async setSignInSession(value) {
|
|
246
|
+
return this.adapter.setStorageItem(PersistKey.SignInSession, value && JSON.stringify(value));
|
|
247
|
+
}
|
|
248
|
+
async setIdToken(value) {
|
|
249
|
+
return this.adapter.setStorageItem(PersistKey.IdToken, value);
|
|
250
|
+
}
|
|
251
|
+
async setRefreshToken(value) {
|
|
252
|
+
return this.adapter.setStorageItem(PersistKey.RefreshToken, value);
|
|
253
|
+
}
|
|
254
|
+
async getAccessTokenByRefreshToken(resource, organizationId) {
|
|
255
|
+
const currentRefreshToken = await this.getRefreshToken();
|
|
256
|
+
if (!currentRefreshToken) {
|
|
257
|
+
throw new LogtoClientError('not_authenticated');
|
|
258
|
+
}
|
|
259
|
+
const accessTokenKey = buildAccessTokenKey(resource, organizationId);
|
|
260
|
+
const { appId: clientId } = this.logtoConfig;
|
|
261
|
+
const { tokenEndpoint } = await this.getOidcConfig();
|
|
262
|
+
const requestedAt = Math.round(Date.now() / 1000);
|
|
263
|
+
const { accessToken, refreshToken, idToken, scope, expiresIn } = await fetchTokenByRefreshToken({
|
|
264
|
+
clientId,
|
|
265
|
+
tokenEndpoint,
|
|
266
|
+
refreshToken: currentRefreshToken,
|
|
267
|
+
resource,
|
|
268
|
+
organizationId,
|
|
269
|
+
}, this.adapter.requester);
|
|
270
|
+
this.accessTokenMap.set(accessTokenKey, {
|
|
271
|
+
token: accessToken,
|
|
272
|
+
scope,
|
|
273
|
+
/** The `expiresAt` variable provides an approximate estimation of the actual `exp` property
|
|
274
|
+
* in the token claims. It is utilized by the client to determine if the cached access token
|
|
275
|
+
* has expired and when a new access token should be requested.
|
|
276
|
+
*/
|
|
277
|
+
expiresAt: requestedAt + expiresIn,
|
|
278
|
+
});
|
|
279
|
+
await this.saveAccessTokenMap();
|
|
280
|
+
if (refreshToken) {
|
|
281
|
+
await this.setRefreshToken(refreshToken);
|
|
282
|
+
}
|
|
283
|
+
if (idToken) {
|
|
284
|
+
await this.jwtVerifier.verifyIdToken(idToken);
|
|
285
|
+
await this.setIdToken(idToken);
|
|
286
|
+
}
|
|
287
|
+
return accessToken;
|
|
288
|
+
}
|
|
289
|
+
async saveAccessTokenMap() {
|
|
290
|
+
const data = {};
|
|
291
|
+
for (const [key, accessToken] of this.accessTokenMap.entries()) {
|
|
292
|
+
// eslint-disable-next-line @silverhand/fp/no-mutation
|
|
293
|
+
data[key] = accessToken;
|
|
294
|
+
}
|
|
295
|
+
await this.adapter.storage.setItem('accessToken', JSON.stringify(data));
|
|
296
|
+
}
|
|
297
|
+
async loadAccessTokenMap() {
|
|
298
|
+
const raw = await this.adapter.storage.getItem('accessToken');
|
|
299
|
+
if (!raw) {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
const json = JSON.parse(raw);
|
|
304
|
+
if (!isLogtoAccessTokenMap(json)) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
this.accessTokenMap.clear();
|
|
308
|
+
for (const [key, accessToken] of Object.entries(json)) {
|
|
309
|
+
this.accessTokenMap.set(key, accessToken);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
console.warn(error);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
async #getOidcConfig() {
|
|
317
|
+
return this.adapter.getWithCache(CacheKey.OpenidConfig, async () => {
|
|
318
|
+
return fetchOidcConfig(getDiscoveryEndpoint(this.logtoConfig.endpoint), this.adapter.requester);
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
async #getAccessToken(resource, organizationId) {
|
|
322
|
+
if (!(await this.isAuthenticated())) {
|
|
323
|
+
throw new LogtoClientError('not_authenticated');
|
|
324
|
+
}
|
|
325
|
+
const accessTokenKey = buildAccessTokenKey(resource, organizationId);
|
|
326
|
+
const accessToken = this.accessTokenMap.get(accessTokenKey);
|
|
327
|
+
if (accessToken && accessToken.expiresAt > Date.now() / 1000) {
|
|
328
|
+
return accessToken.token;
|
|
329
|
+
}
|
|
330
|
+
// Since the access token has expired, delete it from the map.
|
|
331
|
+
if (accessToken) {
|
|
332
|
+
this.accessTokenMap.delete(accessTokenKey);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Need to fetch a new access token using refresh token.
|
|
336
|
+
*/
|
|
337
|
+
return this.getAccessTokenByRefreshToken(resource, organizationId);
|
|
338
|
+
}
|
|
339
|
+
async #getOrganizationToken(organizationId) {
|
|
340
|
+
if (!this.logtoConfig.scopes?.includes(UserScope.Organizations)) {
|
|
341
|
+
throw new LogtoClientError('missing_scope_organizations');
|
|
342
|
+
}
|
|
343
|
+
return this.getAccessToken(undefined, organizationId);
|
|
344
|
+
}
|
|
345
|
+
async #handleSignInCallback(callbackUri) {
|
|
346
|
+
const signInSession = await this.getSignInSession();
|
|
347
|
+
if (!signInSession) {
|
|
348
|
+
throw new LogtoClientError('sign_in_session.not_found');
|
|
349
|
+
}
|
|
350
|
+
const { redirectUri, state, codeVerifier } = signInSession;
|
|
351
|
+
const code = verifyAndParseCodeFromCallbackUri(callbackUri, redirectUri, state);
|
|
352
|
+
// NOTE: Will add scope to accessTokenKey when needed. (Linear issue LOG-1589)
|
|
353
|
+
const accessTokenKey = buildAccessTokenKey();
|
|
354
|
+
const { appId: clientId } = this.logtoConfig;
|
|
355
|
+
const { tokenEndpoint } = await this.getOidcConfig();
|
|
356
|
+
const requestedAt = Math.round(Date.now() / 1000);
|
|
357
|
+
const { idToken, refreshToken, accessToken, scope, expiresIn } = await fetchTokenByAuthorizationCode({
|
|
358
|
+
clientId,
|
|
359
|
+
tokenEndpoint,
|
|
360
|
+
redirectUri,
|
|
361
|
+
codeVerifier,
|
|
362
|
+
code,
|
|
363
|
+
}, this.adapter.requester);
|
|
364
|
+
await this.jwtVerifier.verifyIdToken(idToken);
|
|
365
|
+
await this.setRefreshToken(refreshToken ?? null);
|
|
366
|
+
await this.setIdToken(idToken);
|
|
367
|
+
this.accessTokenMap.set(accessTokenKey, {
|
|
368
|
+
token: accessToken,
|
|
369
|
+
scope,
|
|
370
|
+
/** The `expiresAt` variable provides an approximate estimation of the actual `exp` property
|
|
371
|
+
* in the token claims. It is utilized by the client to determine if the cached access token
|
|
372
|
+
* has expired and when a new access token should be requested.
|
|
373
|
+
*/
|
|
374
|
+
expiresAt: requestedAt + expiresIn,
|
|
375
|
+
});
|
|
376
|
+
await this.saveAccessTokenMap();
|
|
377
|
+
await this.setSignInSession(null);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export { StandardLogtoClient };
|