-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathauth.ts
More file actions
577 lines (498 loc) · 20 KB
/
auth.ts
File metadata and controls
577 lines (498 loc) · 20 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import { CITADEL_SERVER_MAP, STORAGE_SERVER_MAP, STORAGE_SERVER_SOCKET_URL_MAP } from "@toruslabs/constants";
import { AUTH_CONNECTION, AUTH_CONNECTION_TYPE, constructURL, getTimeout, UX_MODE } from "@toruslabs/customauth";
import { add0x, Hex } from "@toruslabs/metadata-helpers";
import { AuthSessionManager, StorageManager } from "@toruslabs/session-manager";
import { klona } from "klona/json";
import {
AUTH_ACTIONS,
AUTH_ACTIONS_TYPE,
AUTH_DASHBOARD_DEVELOPMENT_URL,
AUTH_DASHBOARD_PRODUCTION_URL,
AUTH_DASHBOARD_STAGING_URL,
AUTH_DASHBOARD_TESTING_URL,
AUTH_SERVICE_DEVELOPMENT_URL,
AUTH_SERVICE_PRODUCTION_URL,
AUTH_SERVICE_STAGING_URL,
AUTH_SERVICE_TESTING_URL,
type AuthFlowResult,
AuthOptions,
AuthRequestPayload,
AuthSessionData,
AuthUserInfo,
BaseLoginParams,
BUILD_ENV,
DEFAULT_SESSION_TIME,
generateRecordId,
jsonToBase64,
LoginParams,
POPUP_TIMEOUT,
SDK_MODE,
SocialMfaModParams,
WEB3AUTH_NETWORK,
} from "../utils";
import { log } from "../utils/logger";
import { AuthProvider } from "./AuthProvider";
import { InitializationError, LoginError } from "./errors";
import PopupHandler from "./PopupHandler";
import { getHashQueryParams, isAuthFlowError, version } from "./utils";
export class Auth {
state: AuthSessionData = {};
options: AuthOptions;
private sessionManager: AuthSessionManager<AuthSessionData>;
private _storageBaseKey = "auth_store";
private dappState: string;
private addVersionInUrls = true;
private authProvider: AuthProvider;
private authProviderPromise: Promise<void>;
constructor(options: AuthOptions) {
if (!options.clientId) throw InitializationError.invalidParams("clientId is required");
if (!options.network) options.network = WEB3AUTH_NETWORK.SAPPHIRE_MAINNET;
if (!options.buildEnv) options.buildEnv = BUILD_ENV.PRODUCTION;
if (!options.sdkMode) options.sdkMode = SDK_MODE.DEFAULT;
if (options.buildEnv === BUILD_ENV.DEVELOPMENT || options.buildEnv === BUILD_ENV.TESTING || options.sdkUrl) this.addVersionInUrls = false;
if (!options.sdkUrl) {
if (options.buildEnv === BUILD_ENV.DEVELOPMENT) {
options.sdkUrl = AUTH_SERVICE_DEVELOPMENT_URL;
options.dashboardUrl = AUTH_DASHBOARD_DEVELOPMENT_URL;
} else if (options.buildEnv === BUILD_ENV.STAGING) {
options.sdkUrl = AUTH_SERVICE_STAGING_URL;
options.dashboardUrl = AUTH_DASHBOARD_STAGING_URL;
} else if (options.buildEnv === BUILD_ENV.TESTING) {
options.sdkUrl = AUTH_SERVICE_TESTING_URL;
options.dashboardUrl = AUTH_DASHBOARD_TESTING_URL;
} else {
options.sdkUrl = AUTH_SERVICE_PRODUCTION_URL;
options.dashboardUrl = AUTH_DASHBOARD_PRODUCTION_URL;
}
}
if (!options.redirectUrl && typeof window !== "undefined") {
options.redirectUrl = `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
}
if (!options.uxMode) options.uxMode = UX_MODE.REDIRECT;
if (typeof options.replaceUrlOnRedirect !== "boolean") options.replaceUrlOnRedirect = true;
if (typeof options.includeUserDataInToken !== "boolean") options.includeUserDataInToken = true;
if (!options.originData) options.originData = {};
if (!options.whiteLabel) options.whiteLabel = {};
if (!options.authConnectionConfig) options.authConnectionConfig = [];
if (!options.mfaSettings) options.mfaSettings = {};
if (!options.citadelServerUrl) options.citadelServerUrl = CITADEL_SERVER_MAP[options.buildEnv];
if (!options.storageServerUrl) options.storageServerUrl = STORAGE_SERVER_MAP[options.buildEnv];
if (!options.sessionSocketUrl) options.sessionSocketUrl = STORAGE_SERVER_SOCKET_URL_MAP[options.buildEnv];
if (!options.sessionTime) options.sessionTime = DEFAULT_SESSION_TIME;
this.options = options;
}
get privKey(): string {
return this.state.privKey ? this.state.privKey.padStart(64, "0") : "";
}
get coreKitKey(): string {
return this.state.coreKitKey ? this.state.coreKitKey.padStart(64, "0") : "";
}
get ed25519PrivKey(): string {
return this.state.ed25519PrivKey ? this.state.ed25519PrivKey.padStart(128, "0") : "";
}
get coreKitEd25519Key(): string {
return this.state.coreKitEd25519PrivKey ? this.state.coreKitEd25519PrivKey.padStart(128, "0") : "";
}
get authSessionManager(): AuthSessionManager<AuthSessionData> {
return this.sessionManager;
}
get sessionId(): string {
return this.state.sessionId || "";
}
get sessionNamespace(): string {
return this.options.sessionNamespace || "";
}
get appState(): string {
return this.state?.userInfo?.appState || this.dappState || "";
}
get baseUrl(): string {
// testing and develop don't have versioning
if (!this.addVersionInUrls) return this.options.sdkUrl;
return `${this.options.sdkUrl}/v${version.split(".")[0]}`;
}
private get dashboardUrl(): string {
// testing and develop don't have versioning
if (!this.addVersionInUrls) return `${this.options.dashboardUrl}`;
return `${this.options.dashboardUrl}/v${version.split(".")[0]}`;
}
async init(): Promise<void> {
// get sessionNamespace from the redirect result.
const params = getHashQueryParams(this.options.replaceUrlOnRedirect);
if (params.sessionNamespace) this.options.sessionNamespace = params.sessionNamespace;
const storageKey =
this.options.sessionKey || (this.options.sessionNamespace ? `${this._storageBaseKey}_${this.options.sessionNamespace}` : this._storageBaseKey);
// We dont need to set the sessionTime here, because the session would be created by auth service.
this.sessionManager = new AuthSessionManager({
storageKeyPrefix: storageKey,
apiClientConfig: { baseURL: this.options.citadelServerUrl },
storage: this.options.storage,
accessTokenProvider: this.options.accessTokenProvider,
cookieOptions: this.options.cookieOptions,
});
if (this.options.network === WEB3AUTH_NETWORK.TESTNET || this.options.network === WEB3AUTH_NETWORK.SAPPHIRE_DEVNET) {
// using console log because it shouldn't be affected by loglevel config
// eslint-disable-next-line no-console
console.log(
`%c WARNING! You are on ${this.options.network}. Please set network: 'mainnet' or 'sapphire_mainnet' in production`,
"color: #FF0000"
);
}
if (this.options.buildEnv !== BUILD_ENV.PRODUCTION) {
// using console log because it shouldn't be affected by loglevel config
// eslint-disable-next-line no-console
console.log(`%c WARNING! You are using build env ${this.options.buildEnv}. Please set buildEnv: 'production' in production`, "color: #FF0000");
}
if (params.error) {
this.dappState = params.state;
throw LoginError.loginFailed(params.error);
}
if (params.sessionId) {
await this.sessionManager.setTokens({
sessionId: add0x(params.sessionId),
accessToken: params.accessToken || "",
refreshToken: params.refreshToken || "",
idToken: params.idToken || "",
});
}
// Get session id from the auth session manager
const sessionId = await this.sessionManager.getSessionId();
if (sessionId) {
const data = await this._authorizeSession();
// Fill state with correct info from session
// If session is invalid all the data is unset here.
if (data && Object.keys(data).length > 0) {
this.updateState(data);
}
}
if (this.options.sdkMode === SDK_MODE.IFRAME) {
this.authProvider = new AuthProvider({ sdkUrl: this.baseUrl, whiteLabel: this.options.whiteLabel });
if (!this.state.sessionId) {
this.authProviderPromise = this.authProvider.init({ network: this.options.network, clientId: this.options.clientId });
if (params.nonce) {
await this.authProviderPromise;
await this.postLoginInitiatedMessage(JSON.parse(params.loginParams), params.nonce);
}
}
}
}
async login(params: LoginParams): Promise<{ privKey: string } | null> {
if (!params.authConnection && (!params.authConnectionId || !params.groupedAuthConnectionId))
throw LoginError.invalidLoginParams(`AuthConnection is required`);
const loginParams: LoginParams = { ...params };
const dataObject: AuthRequestPayload = {
actionType: AUTH_ACTIONS.LOGIN,
options: this.options,
params: loginParams,
};
const result = await this.authHandler(`${this.baseUrl}/start`, dataObject, getTimeout(params.authConnection as AUTH_CONNECTION_TYPE));
if (!result) return null;
if (isAuthFlowError(result)) {
this.dappState = result.state;
throw LoginError.loginFailed(result.error);
}
await this.sessionManager.setTokens({
sessionId: add0x(result.sessionId),
accessToken: result.accessToken,
refreshToken: result.refreshToken,
idToken: result.idToken,
});
await this.refreshSession();
return { privKey: this.privKey };
}
async postLoginInitiatedMessage(params: LoginParams, nonce?: string): Promise<void> {
if (this.options.sdkMode !== SDK_MODE.IFRAME) throw LoginError.invalidLoginParams("Cannot perform this action in default mode.");
// This is to ensure that the auth provider is initialized before calling postLoginInitiatedMessage
// This is setup in the init method, if there is no active session.
if (this.authProviderPromise) await this.authProviderPromise;
// if there is an active session, we dont load the auth provider in the init method.
// so we need to initialize it here, if user logged out and then login in again.
if (!this.authProvider?.initialized) {
await this.authProvider.init({ network: this.options.network, clientId: this.options.clientId });
}
const result = await this.authProvider.postLoginInitiatedMessage({ actionType: AUTH_ACTIONS.LOGIN, params, options: this.options }, nonce);
await this.sessionManager.setTokens({
sessionId: add0x(result.sessionId),
accessToken: result.accessToken,
refreshToken: result.refreshToken,
idToken: result.idToken,
});
this.options.sessionNamespace = result.sessionNamespace;
await this.refreshSession();
}
async postLoginCancelledMessage(nonce: string): Promise<void> {
if (this.options.sdkMode !== SDK_MODE.IFRAME) throw LoginError.invalidLoginParams("Cannot perform this action in default mode.");
if (this.authProviderPromise) await this.authProviderPromise;
if (!this.authProvider?.initialized) throw InitializationError.notInitialized();
this.authProvider.postLoginCancelledMessage(nonce);
}
async logout(): Promise<void> {
if (!this.sessionId) throw LoginError.userNotLoggedIn();
await this.sessionManager.logout();
this.clearState();
}
async enableMFA(params: Partial<LoginParams>): Promise<boolean> {
if (!this.sessionId) throw LoginError.userNotLoggedIn();
await this.refreshSession();
if (this.state.userInfo.isMfaEnabled) throw LoginError.mfaAlreadyEnabled();
const dataObject: AuthRequestPayload = {
actionType: AUTH_ACTIONS.ENABLE_MFA,
options: { ...this.options, sdkMode: SDK_MODE.DEFAULT },
params: {
...params,
authConnection: this.state.userInfo.authConnection,
authConnectionId: this.state.userInfo.authConnectionId,
groupedAuthConnectionId: this.state.userInfo.groupedAuthConnectionId,
extraLoginOptions: {
login_hint: this.state.userInfo.userId,
},
mfaLevel: "mandatory",
},
sessionId: this.sessionId,
accessToken: await this.getAccessToken(),
};
const result = await this.authHandler(`${this.baseUrl}/start`, dataObject, POPUP_TIMEOUT);
if (!result) return false;
if (isAuthFlowError(result)) {
this.dappState = result.state;
throw LoginError.loginFailed(result.error);
}
await this.sessionManager.setTokens({
sessionId: add0x(result.sessionId),
accessToken: result.accessToken,
refreshToken: result.refreshToken,
idToken: result.idToken,
});
await this.refreshSession();
return Boolean(this.state.userInfo?.isMfaEnabled);
}
async manageMFA(params: Partial<LoginParams>): Promise<void> {
if (!this.sessionId) throw LoginError.userNotLoggedIn();
await this.refreshSession();
if (!this.state.userInfo.isMfaEnabled) throw LoginError.mfaNotEnabled();
// in case of redirect mode, redirect url will be dapp specified
// in case of popup mode, redirect url will be sdk specified
const defaultParams = {
dappUrl: `${window.location.origin}${window.location.pathname}`,
};
const loginId = StorageManager.generateRandomSessionKey();
const recordId = generateRecordId();
const dataObject: AuthRequestPayload = {
actionType: AUTH_ACTIONS.MANAGE_MFA,
// manage mfa always opens in a new tab, so need to fix the uxMode to redirect.
options: {
...this.options,
uxMode: UX_MODE.REDIRECT,
sdkMode: SDK_MODE.DEFAULT,
redirectUrl: `${this.dashboardUrl}/wallet/account`,
},
params: {
...defaultParams,
...params,
authConnection: this.state.userInfo.authConnection,
authConnectionId: this.state.userInfo.authConnectionId,
groupedAuthConnectionId: this.state.userInfo.groupedAuthConnectionId,
extraLoginOptions: {
login_hint: this.state.userInfo.userId,
},
appState: jsonToBase64({ loginId, recordId }),
},
sessionId: this.sessionId,
accessToken: await this.getAccessToken(),
};
this.storeAuthPayload(loginId, dataObject, dataObject.options.sessionTime, true);
const configParams: BaseLoginParams = {
loginId,
recordId,
sessionNamespace: this.options.sessionNamespace,
storageServerUrl: this.options.storageServerUrl,
};
const loginUrl = constructURL({
baseURL: `${this.baseUrl}/start`,
hash: { b64Params: jsonToBase64(configParams) },
});
window.open(loginUrl, "_blank");
}
async manageSocialFactor(actionType: AUTH_ACTIONS_TYPE, params: SocialMfaModParams & Pick<LoginParams, "appState">): Promise<boolean> {
if (!this.sessionId) throw LoginError.userNotLoggedIn();
await this.refreshSession();
const dataObject: AuthRequestPayload = {
actionType,
options: { ...this.options, sdkMode: SDK_MODE.DEFAULT },
params: {
...params,
},
sessionId: this.sessionId,
accessToken: await this.getAccessToken(),
};
const result = await this.authHandler(`${this.baseUrl}/start`, dataObject);
if (!result) return false;
if (isAuthFlowError(result)) return false;
return true;
}
async addAuthenticatorFactor(params: Pick<LoginParams, "appState">): Promise<boolean> {
if (!this.sessionId) throw LoginError.userNotLoggedIn();
await this.refreshSession();
const dataObject: AuthRequestPayload = {
actionType: AUTH_ACTIONS.ADD_AUTHENTICATOR_FACTOR,
options: { ...this.options, sdkMode: SDK_MODE.DEFAULT },
params: {
...params,
authConnection: AUTH_CONNECTION.AUTHENTICATOR,
},
sessionId: this.sessionId,
accessToken: await this.getAccessToken(),
};
const result = await this.authHandler(`${this.baseUrl}/start`, dataObject);
if (!result) return false;
if (isAuthFlowError(result)) return false;
return true;
}
async addPasskeyFactor(params: Pick<LoginParams, "appState">): Promise<boolean> {
if (!this.sessionId) throw LoginError.userNotLoggedIn();
await this.refreshSession();
const dataObject: AuthRequestPayload = {
actionType: AUTH_ACTIONS.ADD_PASSKEY_FACTOR,
options: { ...this.options, sdkMode: SDK_MODE.DEFAULT },
params: {
...params,
authConnection: AUTH_CONNECTION.PASSKEYS,
},
sessionId: this.sessionId,
accessToken: await this.getAccessToken(),
};
const result = await this.authHandler(`${this.baseUrl}/start`, dataObject);
if (!result) return false;
if (isAuthFlowError(result)) return false;
return true;
}
async cleanup() {
if (this.authProvider) this.authProvider.cleanup();
}
async getUserInfo(): Promise<AuthUserInfo> {
if (!this.sessionId) {
throw LoginError.userNotLoggedIn();
}
return {
...this.state.userInfo,
idToken: await this.sessionManager.getIdToken(),
};
}
async getAccessToken(): Promise<string> {
if (!this.sessionId) {
throw LoginError.userNotLoggedIn();
}
const token = await this.sessionManager.getAccessToken();
if (!token) throw LoginError.userNotLoggedIn();
return token;
}
async refreshSession(): Promise<void> {
const data = await this._authorizeSession();
if (!data || Object.keys(data).length === 0) {
try {
await this.sessionManager.logout();
} catch {
// session may already be invalid on the server, ignore cleanup errors
}
this.clearState();
throw LoginError.userNotLoggedIn();
}
this.updateState(data);
}
private async storeAuthPayload(loginId: Hex, payload: AuthRequestPayload, timeout = 600, skipAwait = false): Promise<void> {
if (!this.sessionManager) throw InitializationError.notInitialized();
const authRequestStorageManager = new StorageManager<AuthRequestPayload>({
sessionServerBaseUrl: payload.options.storageServerUrl,
sessionNamespace: payload.options.sessionNamespace,
sessionTime: timeout, // each login key must be used with 10 mins (might be used at the end of popup redirect)
sessionId: loginId,
allowedOrigin: this.options.sdkUrl,
});
const promise = authRequestStorageManager.createSession(klona(payload));
if (payload.options.uxMode === UX_MODE.REDIRECT && !skipAwait) {
await promise;
}
}
private async _authorizeSession(): Promise<AuthSessionData | null> {
try {
const result = await this.sessionManager.authorize();
return result;
} catch (err) {
log.error("authorization failed", err);
return null;
}
}
private clearState() {
this.updateState({
privKey: "",
coreKitKey: "",
coreKitEd25519PrivKey: "",
ed25519PrivKey: "",
walletKey: "",
oAuthPrivateKey: "",
tKey: "",
metadataNonce: "",
keyMode: undefined,
userInfo: {
name: "",
profileImage: "",
dappShare: "",
idToken: "",
oAuthIdToken: "",
oAuthAccessToken: "",
appState: "",
email: "",
authConnectionId: "",
userId: "",
groupedAuthConnectionId: "",
authConnection: "",
isMfaEnabled: false,
},
authToken: "",
sessionId: "",
signatures: [],
});
}
private updateState(data: Partial<AuthSessionData>) {
this.state = { ...this.state, ...data };
}
private async authHandler(url: string, dataObject: AuthRequestPayload, popupTimeout = 1000 * 10): Promise<AuthFlowResult | null> {
const loginId = StorageManager.generateRandomSessionKey();
const recordId = generateRecordId();
await this.storeAuthPayload(loginId, dataObject);
const configParams: BaseLoginParams = {
loginId,
recordId,
sessionNamespace: this.options.sessionNamespace,
storageServerUrl: this.options.storageServerUrl,
};
if (this.options.uxMode === UX_MODE.REDIRECT) {
const loginUrl = constructURL({
baseURL: url,
hash: { b64Params: jsonToBase64(configParams) },
});
window.location.href = loginUrl;
return null;
}
const loginUrl = constructURL({
baseURL: url,
hash: { b64Params: jsonToBase64(configParams) },
});
const currentWindow = new PopupHandler({
url: loginUrl,
timeout: popupTimeout,
serverUrl: this.options.storageServerUrl,
socketUrl: this.options.sessionSocketUrl,
});
return new Promise((resolve, reject) => {
currentWindow.on("close", () => {
reject(LoginError.popupClosed());
});
currentWindow.listenOnChannel(loginId).then(resolve).catch(reject);
try {
currentWindow.open();
} catch (error) {
reject(error);
}
});
}
}