-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathindex.ts
More file actions
340 lines (300 loc) · 10.5 KB
/
index.ts
File metadata and controls
340 lines (300 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
* @forgerock/javascript-sdk
*
* index.ts
*
* Copyright (c) 2020-2021 ForgeRock. All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import { ActionTypes } from '../config/enums';
import type { ConfigOptions } from '../config/index';
import Config from '../config/index';
import type { ConfigurablePaths } from '../config/interfaces';
import type { StringDict } from '../shared/interfaces';
import type { Noop } from '../shared/types';
import TokenStorage from '../token-storage';
import { isOkOr4xx } from '../util/http';
import PKCE from '../util/pkce';
import { withTimeout } from '../util/timeout';
import { getEndpointPath, resolve, stringify } from '../util/url';
import { ResponseType } from './enums';
import type {
AccessTokenResponse,
GetAuthorizationUrlOptions,
GetOAuth2TokensOptions,
OAuth2Tokens,
} from './interfaces';
import middlewareWrapper from '../util/middleware';
const allowedErrors = {
// AM error for consent requirement
AuthenticationConsentRequired: 'Authentication or consent required',
// Manual iframe error
AuthorizationTimeout: 'Authorization timed out',
// Chromium browser error
FailedToFetch: 'Failed to fetch',
// Mozilla browser error
NetworkError: 'NetworkError when attempting to fetch resource.',
// Webkit browser error
CORSError: 'Cross-origin redirection',
// prompt=none errors
InteractionNotAllowed: 'The request requires some interaction that is not allowed.',
};
/**
* OAuth 2.0 client.
*/
abstract class OAuth2Client {
public static async createAuthorizeUrl(options: GetAuthorizationUrlOptions): Promise<string> {
const { clientId, middleware, redirectUri, scope } = Config.get(options);
const requestParams: StringDict<string | undefined> = {
...options.query,
client_id: clientId,
redirect_uri: redirectUri,
response_type: options.responseType,
scope,
state: options.state,
...(options.prompt ? { prompt: options.prompt } : {}),
};
if (options.verifier) {
const challenge = await PKCE.createChallenge(options.verifier);
requestParams.code_challenge = challenge;
requestParams.code_challenge_method = 'S256';
}
const runMiddleware = middlewareWrapper(
{
url: new URL(this.getUrl('authorize', requestParams, options)),
init: {},
},
{ type: ActionTypes.Authorize },
);
const { url } = runMiddleware(middleware);
return url.toString();
}
/**
* Calls the authorize URL with an iframe. If successful,
* it returns the callback URL with authentication code,
* optionally using PKCE.
* Method renamed in v3.
* Original Name: getAuthorizeUrl
* New Name: getAuthCodeByIframe
*/
public static async getAuthCodeByIframe(options: GetAuthorizationUrlOptions): Promise<string> {
const url = await this.createAuthorizeUrl({ ...options, prompt: 'none' });
const { serverConfig } = Config.get(options);
return new Promise((resolve, reject) => {
const iframe = document.createElement('iframe');
// Define these here to avoid linter warnings
const noop: Noop = () => {
return;
};
let onLoad: Noop = noop;
let cleanUp: Noop = noop;
let timeout: number | ReturnType<typeof setTimeout> = 0;
cleanUp = (): void => {
clearTimeout(timeout);
iframe.removeEventListener('load', onLoad);
iframe.remove();
};
onLoad = (): void => {
if (iframe.contentWindow) {
const newHref = iframe.contentWindow.location.href;
if (this.containsAuthCode(newHref)) {
cleanUp();
resolve(newHref);
} else if (this.containsAuthError(newHref)) {
cleanUp();
resolve(newHref);
}
}
};
timeout = setTimeout(() => {
cleanUp();
reject(new Error(allowedErrors.AuthorizationTimeout));
}, serverConfig.timeout);
iframe.style.display = 'none';
iframe.addEventListener('load', onLoad);
document.body.appendChild(iframe);
iframe.src = url;
});
}
/**
* Exchanges an authorization code for OAuth tokens.
*/
public static async getOAuth2Tokens(options: GetOAuth2TokensOptions): Promise<OAuth2Tokens> {
const { clientId, redirectUri } = Config.get(options);
const requestParams: StringDict<string | undefined> = {
client_id: clientId,
code: options.authorizationCode,
grant_type: 'authorization_code',
redirect_uri: redirectUri,
};
if (options.verifier) {
requestParams.code_verifier = options.verifier;
}
const body = stringify(requestParams);
const init = {
body,
headers: new Headers({
'Content-Length': body.length.toString(),
'Content-Type': 'application/x-www-form-urlencoded',
}),
method: 'POST',
};
const response = await this.request('accessToken', undefined, false, init, options);
const responseClone = response.clone();
const responseBody = await this.getBody<unknown>(response);
if (response.status !== 200) {
const message =
typeof responseBody === 'string'
? `Expected 200, received ${response.status}`
: this.parseError(responseBody as StringDict<unknown>);
throw new Error(message);
}
const responseObject = responseBody as AccessTokenResponse;
if (!responseObject.access_token) {
throw new Error('Access token not found in response');
}
let tokenExpiry: number | undefined = undefined;
if (responseObject.expires_in) {
tokenExpiry = Date.now() + responseObject.expires_in * 1000;
}
return {
accessToken: responseObject.access_token,
idToken: responseObject.id_token,
refreshToken: responseObject.refresh_token,
tokenExpiry: tokenExpiry,
rawResponse: await responseClone.text(),
};
}
/**
* Gets OIDC user information.
*/
public static async getUserInfo(options?: ConfigOptions): Promise<unknown> {
const response = await this.request('userInfo', undefined, true, undefined, options);
if (response.status !== 200) {
throw new Error(`Failed to get user info; received ${response.status}`);
}
const json = await response.json();
return json;
}
/**
* Invokes the OIDC end session endpoint.
*/
public static async endSession(options?: ConfigOptions): Promise<Response> {
const tokens = await TokenStorage.get();
const idToken = tokens && tokens.idToken;
const query: StringDict<string | undefined> = {};
if (idToken) {
query.id_token_hint = idToken;
}
const response = await this.request('endSession', query, true, undefined, options);
if (!isOkOr4xx(response)) {
throw new Error(`Failed to end session; received ${response.status}`);
}
return response;
}
/**
* Immediately revokes the stored access token.
*/
public static async revokeToken(options?: ConfigOptions): Promise<Response> {
const { clientId } = Config.get(options);
const tokens = await TokenStorage.get();
const accessToken = tokens && tokens.accessToken;
const body: StringDict<string | undefined> = {
client_id: clientId,
};
// This is needed to support Token Vault; the SDK may not have the token locally
if (accessToken) {
body.token = accessToken;
}
const init: RequestInit = {
body: stringify(body),
credentials: 'include',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
method: 'POST',
};
const response = await this.request('revoke', undefined, false, init, options);
if (!isOkOr4xx(response)) {
throw new Error(`Failed to revoke token; received ${response.status}`);
}
return response;
}
private static async request(
endpoint: ConfigurablePaths,
query?: StringDict<string | undefined>,
includeToken?: boolean,
init?: RequestInit,
options?: ConfigOptions,
): Promise<Response> {
const { middleware, serverConfig } = Config.get(options);
const url = this.getUrl(endpoint, query, options);
const getActionType = (endpoint: ConfigurablePaths): ActionTypes => {
switch (endpoint) {
case 'accessToken':
return ActionTypes.ExchangeToken;
case 'endSession':
return ActionTypes.EndSession;
case 'revoke':
return ActionTypes.RevokeToken;
default:
return ActionTypes.UserInfo;
}
};
init = init || ({} as RequestInit);
if (includeToken) {
const tokens = await TokenStorage.get();
const accessToken = tokens && tokens.accessToken;
init.credentials = 'include';
init.headers = (init.headers || new Headers()) as Headers;
init.headers.set('Authorization', `Bearer ${accessToken}`);
}
const runMiddleware = middlewareWrapper(
{ url: new URL(url), init },
{ type: getActionType(endpoint) },
);
const req = runMiddleware(middleware);
return await withTimeout(fetch(req.url.toString(), req.init), serverConfig.timeout);
}
private static containsAuthCode(url: string | null): boolean {
return !!url && /code=([^&]+)/.test(url);
}
private static containsAuthError(url: string | null): boolean {
return !!url && /error=([^&]+)/.test(url);
}
private static async getBody<T>(response: Response): Promise<T | string> {
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.indexOf('application/json') > -1) {
return await response.json();
}
return await response.text();
}
private static parseError(json: StringDict<unknown>): string | undefined {
if (json) {
if (json.error && json.error_description) {
return `${json.error}: ${json.error_description}`;
}
if (json.code && json.message) {
return `${json.code}: ${json.message}`;
}
}
return undefined;
}
private static getUrl(
endpoint: ConfigurablePaths,
query?: StringDict<string | undefined>,
options?: ConfigOptions,
): string {
const { realmPath, serverConfig } = Config.get(options);
const path = getEndpointPath(endpoint, realmPath, serverConfig.paths);
let url = resolve(serverConfig.baseUrl, path);
if (query) {
url += `?${stringify(query)}`;
}
return url;
}
}
export default OAuth2Client;
export type { GetAuthorizationUrlOptions, GetOAuth2TokensOptions, OAuth2Tokens };
export { allowedErrors, ResponseType };