-
Notifications
You must be signed in to change notification settings - Fork 413
/
Copy pathedge-client.ts
281 lines (252 loc) · 9.43 KB
/
edge-client.ts
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
import * as oauth from 'oauth4webapi';
import * as jose from 'jose';
import { Auth0Request } from '../http';
import {
CallbackExtras,
OpenIDCallbackChecks,
TokenEndpointResponse,
AbstractClient,
EndSessionParameters,
Telemetry
} from './abstract-client';
import { ApplicationError, DiscoveryError, IdentityProviderError, UserInfoError } from '../utils/errors';
import { AccessTokenError, AccessTokenErrorCode } from '../../utils/errors';
import urlJoin from 'url-join';
import { Config } from '../config';
const encodeBase64 = (input: string) => {
const unencoded = new TextEncoder().encode(input);
const CHUNK_SIZE = 0x8000;
const arr = [];
for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
// @ts-expect-error Argument of type 'Uint8Array' is not assignable to parameter of type 'number[]'.
arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
}
return btoa(arr.join(''));
};
export class EdgeClient extends AbstractClient {
private client?: oauth.Client;
private as?: oauth.AuthorizationServer;
private httpOptions: () => oauth.HttpRequestOptions;
constructor(protected config: Config, protected telemetry: Telemetry) {
super(config, telemetry);
if (config.authorizationParams.response_type !== 'code') {
throw new Error('This SDK only supports `response_type=code` when used in an Edge runtime.');
}
this.httpOptions = () => {
const headers = new Headers();
if (config.enableTelemetry) {
const { name, version } = telemetry;
headers.set('User-Agent', `${name}/${version}`);
headers.set(
'Auth0-Client',
encodeBase64(
JSON.stringify({
name,
version,
env: {
edge: true
}
})
)
);
}
return {
signal: AbortSignal.timeout(this.config.httpTimeout),
headers
};
};
}
private async getClient(): Promise<[oauth.AuthorizationServer, oauth.Client]> {
if (this.as) {
return [this.as, this.client as oauth.Client];
}
const issuer = new URL(this.config.issuerBaseURL);
try {
this.as = await oauth
.discoveryRequest(issuer, this.httpOptions())
.then((response) => oauth.processDiscoveryResponse(issuer, response));
} catch (e) {
throw new DiscoveryError(e, this.config.issuerBaseURL);
}
if (this.config.pushedAuthorizationRequests && !this.as.pushed_authorization_request_endpoint) {
throw new TypeError(
'pushed_authorization_request_endpoint must be configured on the issuer to use pushedAuthorizationRequests'
);
}
this.client = {
client_id: this.config.clientID,
...(!this.config.clientAssertionSigningKey && { client_secret: this.config.clientSecret }),
token_endpoint_auth_method: this.config.clientAuthMethod,
id_token_signed_response_alg: this.config.idTokenSigningAlg,
[oauth.clockTolerance]: this.config.clockTolerance
};
return [this.as, this.client];
}
async authorizationUrl(parameters: Record<string, unknown>): Promise<string> {
const [as, client] = await this.getClient();
if (this.config.pushedAuthorizationRequests) {
const response = await oauth.pushedAuthorizationRequest(as, client, parameters as Record<string, string>);
const result = await oauth.processPushedAuthorizationResponse(as, client, response);
if (oauth.isOAuth2Error(result)) {
throw new IdentityProviderError({
message: result.error_description || result.error,
error: result.error,
error_description: result.error_description
});
}
parameters = { request_uri: result.request_uri };
}
const authorizationUrl = new URL(as.authorization_endpoint as string);
authorizationUrl.searchParams.set('client_id', this.config.clientID);
Object.entries(parameters).forEach(([key, value]) => {
if (value === null || value === undefined) {
return;
}
authorizationUrl.searchParams.set(key, String(value));
});
return authorizationUrl.toString();
}
async callbackParams(req: Auth0Request, expectedState: string) {
const [as, client] = await this.getClient();
const url =
req.getMethod().toUpperCase() === 'GET' ? new URL(req.getUrl()) : new URLSearchParams(await req.getBody());
let result: ReturnType<typeof oauth.validateAuthResponse>;
try {
result = oauth.validateAuthResponse(as, client, url, expectedState);
} catch (e) {
throw new ApplicationError(e);
}
if (oauth.isOAuth2Error(result)) {
throw new IdentityProviderError({
message: result.error_description || result.error,
error: result.error,
error_description: result.error_description
});
}
return result;
}
async callback(
redirectUri: string,
parameters: URLSearchParams,
checks: OpenIDCallbackChecks,
extras: CallbackExtras
): Promise<TokenEndpointResponse> {
const [as, client] = await this.getClient();
const { clientAssertionSigningKey, clientAssertionSigningAlg } = this.config;
let clientPrivateKey = clientAssertionSigningKey as CryptoKey | undefined;
/* c8 ignore next 3 */
if (clientPrivateKey && !(clientPrivateKey instanceof CryptoKey)) {
clientPrivateKey = await jose.importPKCS8<CryptoKey>(clientPrivateKey, clientAssertionSigningAlg || 'RS256');
}
const response = await oauth.authorizationCodeGrantRequest(
as,
client,
parameters,
redirectUri,
checks.code_verifier as string,
{
additionalParameters: extras.exchangeBody,
...(clientPrivateKey && { clientPrivateKey }),
...this.httpOptions()
}
);
const result = await oauth.processAuthorizationCodeOpenIDResponse(
as,
client,
response,
checks.nonce,
checks.max_age
);
if (oauth.isOAuth2Error(result)) {
throw new IdentityProviderError({
message: result.error_description || /* c8 ignore next */ result.error,
error: result.error,
error_description: result.error_description
});
}
return result;
}
async endSessionUrl(parameters: EndSessionParameters): Promise<string> {
const [as] = await this.getClient();
const issuerUrl = new URL(as.issuer);
if (
this.config.idpLogout &&
(this.config.auth0Logout || (issuerUrl.hostname.match('\\.auth0\\.com$') && this.config.auth0Logout !== false))
) {
const { post_logout_redirect_uri, ...extraParams } = parameters;
const auth0LogoutUrl: URL = new URL(urlJoin(as.issuer, '/v2/logout'));
post_logout_redirect_uri && auth0LogoutUrl.searchParams.set('returnTo', post_logout_redirect_uri);
auth0LogoutUrl.searchParams.set('client_id', this.config.clientID);
Object.entries(extraParams).forEach(([key, value]: [string, string]) => {
if (value === null || value === undefined) {
return;
}
auth0LogoutUrl.searchParams.set(key, value);
});
return auth0LogoutUrl.toString();
}
if (!as.end_session_endpoint) {
throw new Error('RP Initiated Logout is not supported on your Authorization Server.');
}
const oidcLogoutUrl = new URL(as.end_session_endpoint);
Object.entries(parameters).forEach(([key, value]: [string, string]) => {
if (value === null || value === undefined) {
return;
}
oidcLogoutUrl.searchParams.set(key, value);
});
oidcLogoutUrl.searchParams.set('client_id', this.config.clientID);
return oidcLogoutUrl.toString();
}
async userinfo(accessToken: string): Promise<Record<string, unknown>> {
const [as, client] = await this.getClient();
const response = await oauth.userInfoRequest(as, client, accessToken, this.httpOptions());
try {
return await oauth.processUserInfoResponse(as, client, oauth.skipSubjectCheck, response);
} catch (e) {
throw new UserInfoError(e.message);
}
}
async refresh(refreshToken: string, extras: { exchangeBody: Record<string, any> }): Promise<TokenEndpointResponse> {
const [as, client] = await this.getClient();
const res = await oauth.refreshTokenGrantRequest(as, client, refreshToken, {
additionalParameters: extras.exchangeBody,
...this.httpOptions()
});
const result = await oauth.processRefreshTokenResponse(as, client, res);
if (oauth.isOAuth2Error(result)) {
throw new AccessTokenError(
AccessTokenErrorCode.FAILED_REFRESH_GRANT,
'The request to refresh the access token failed.',
new IdentityProviderError({
message: result.error_description || /* c8 ignore next */ result.error,
error: result.error,
error_description: result.error_description
})
);
}
return result;
}
generateRandomCodeVerifier(): string {
return oauth.generateRandomCodeVerifier();
}
generateRandomNonce(): string {
return oauth.generateRandomNonce();
}
calculateCodeChallenge(codeVerifier: string): Promise<string> {
return oauth.calculatePKCECodeChallenge(codeVerifier);
}
async getIssuerMetadata(): Promise<oauth.AuthorizationServer> {
const [as] = await this.getClient();
return as;
}
}
export const clientGetter = (telemetry: Telemetry): ((config: Config) => Promise<EdgeClient>) => {
let client: EdgeClient;
return async (config) => {
if (!client) {
client = new EdgeClient(config, telemetry);
}
return client;
};
};