/
hooks.tsx
815 lines (783 loc) · 26.2 KB
/
hooks.tsx
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
/**
* Copyright Amazon.com, Inc. and its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
import { signOut } from "../common.js";
import { parseJwtPayload, setTimeoutWallClock } from "../util.js";
import { signInWithLink, requestSignInLink } from "../magic-link.js";
import {
fido2CreateCredential,
fido2DeleteCredential,
fido2ListCredentials,
fido2UpdateCredential,
StoredCredential,
authenticateWithFido2,
} from "../fido2.js";
import { authenticateWithSRP } from "../srp.js";
import { authenticateWithPlaintextPassword } from "../plaintext.js";
import { stepUpAuthenticationWithSmsOtp } from "../sms-otp-stepup.js";
import { configure } from "../config.js";
import { retrieveTokens, storeTokens, TokensFromStorage } from "../storage.js";
import { BusyState, IdleState, busyState } from "../model.js";
import { scheduleRefresh, refreshTokens } from "../refresh.js";
import {
CognitoAccessTokenPayload,
CognitoIdTokenPayload,
} from "../jwt-model.js";
import React, {
useState,
useEffect,
useContext,
useCallback,
useMemo,
useRef,
} from "react";
const PasswordlessContext = React.createContext<UsePasswordless | undefined>(
undefined
);
/** React hook that provides convenient access to the Passwordless lib's features */
export function usePasswordless() {
const context = useContext(PasswordlessContext);
if (!context) {
throw new Error(
"The PasswordlessContextProvider must be added above this consumer in the React component tree"
);
}
return context;
}
const LocalUserCacheContext = React.createContext<
UseLocalUserCache | undefined
>(undefined);
/** React hook that stores and gives access to the last 10 signed in users (from your configured storage) */
export function useLocalUserCache() {
const context = useContext(LocalUserCacheContext);
if (!context) {
throw new Error(
"The localUserCache must be enabled in the PasswordlessContextProvider: <PasswordlessContextProvider enableLocalUserCache={true}>"
);
}
return context;
}
export const PasswordlessContextProvider = (props: {
children: React.ReactNode;
enableLocalUserCache?: boolean;
}) => {
return (
<PasswordlessContext.Provider value={_usePasswordless()}>
{props.enableLocalUserCache ? (
<LocalUserCacheContextProvider>
{props.children}
</LocalUserCacheContextProvider>
) : (
props.children
)}
</PasswordlessContext.Provider>
);
};
const LocalUserCacheContextProvider = (props: {
children: React.ReactNode;
}) => {
return (
<LocalUserCacheContext.Provider value={_useLocalUserCache()}>
{props.children}
</LocalUserCacheContext.Provider>
);
};
/** A FIDO2 credential (e.g. Face ID or Touch), with convenient methods for updating and deleting */
type Fido2Credential = StoredCredential & {
/** Update the friendly name of the credential */
update: (update: { friendlyName: string }) => Promise<void>;
/** Delete the credential */
delete: () => Promise<void>;
/** The credential is currently being updated or deleted */
busy: boolean;
};
type UsePasswordless = ReturnType<typeof _usePasswordless>;
function _usePasswordless() {
const [signingInStatus, setSigninInStatus] = useState<BusyState | IdleState>(
"CHECKING_FOR_SIGNIN_LINK"
);
const [
initiallyRetrievingTokensFromStorage,
setInitiallyRetrievingTokensFromStorage,
] = useState(true);
const [tokens, _setTokens] = useState<TokensFromStorage>();
const [tokensParsed, setTokensParsed] = useState<{
idToken: CognitoIdTokenPayload;
accessToken: CognitoAccessTokenPayload;
expireAt: Date;
}>();
const setTokens: typeof _setTokens = useCallback((reactSetStateAction) => {
_setTokens((prevState) => {
const newTokens =
typeof reactSetStateAction === "function"
? reactSetStateAction(prevState)
: reactSetStateAction;
const { idToken, accessToken, expireAt } = newTokens ?? {};
if (idToken && accessToken && expireAt) {
setTokensParsed({
idToken: parseJwtPayload<CognitoIdTokenPayload>(idToken),
accessToken: parseJwtPayload<CognitoAccessTokenPayload>(accessToken),
expireAt,
});
} else {
setTokensParsed(undefined);
}
return newTokens;
});
}, []);
const [lastError, setLastError] = useState<Error>();
const [
userVerifyingPlatformAuthenticatorAvailable,
setUserVerifyingPlatformAuthenticatorAvailable,
] = useState<boolean>();
const [creatingCredential, setCreatingCredential] = useState(false);
const [fido2Credentials, setFido2Credentials] = useState<Fido2Credential[]>();
const updateFido2Credential = useCallback(
(update: { credentialId: string } & Partial<Fido2Credential>) =>
setFido2Credentials((state) => {
if (!state) return state;
const index = state.findIndex(
(i) => i.credentialId === update.credentialId
);
if (index === -1) return state;
// eslint-disable-next-line security/detect-object-injection
state[index] = { ...state[index], ...update };
return [...state];
}),
[]
);
const deleteFido2Credential = useCallback(
(credentialId: string) =>
setFido2Credentials(
(state) =>
state?.filter(
(remainingAuthenticator) =>
credentialId !== remainingAuthenticator.credentialId
)
),
[]
);
const [isSchedulingRefresh, setIsSchedulingRefresh] = useState<boolean>();
const [isRefreshingTokens, setIsRefreshingTokens] = useState<boolean>();
const [showAuthenticatorManager, setShowAuthenticatorManager] =
useState(false);
const [recheckSignInStatus, setRecheckSignInStatus] = useState(0);
// At component mount, attempt sign-in with link
// This is a no-op, if there's no secret hash in the location bar
useEffect(() => {
setLastError(undefined);
const signingIn = signInWithLink({
statusCb: setSigninInStatus,
tokensCb: (tokens) => storeTokens(tokens).then(() => setTokens(tokens)),
});
signingIn.signedIn.catch(setLastError);
return signingIn.abort;
}, [setTokens]);
const busy = busyState.includes(signingInStatus as BusyState);
// Schedule token refresh
const refreshToken = tokens?.refreshToken;
const expireAtTime = tokens?.expireAt?.getTime();
useEffect(() => {
if (refreshToken) {
const abort = new AbortController();
scheduleRefresh({
abort: abort.signal,
tokensCb: (newTokens) =>
newTokens &&
storeTokens(newTokens).then(() =>
setTokens((tokens) => ({ ...tokens, ...newTokens }))
),
isRefreshingCb: setIsRefreshingTokens,
})
.catch((err) => {
const { debug } = configure();
debug?.("Failed to schedule token refresh:", err);
})
.finally(() => setIsSchedulingRefresh(false));
return () => abort.abort();
}
}, [setTokens, refreshToken, expireAtTime]);
// If we have some tokens, but not all, attempt a refresh
// Should only happen in corner cases, e.g. a developer deleted some keys from storage
if (
tokens &&
(!tokens.idToken || !tokens.accessToken || !tokens.expireAt) &&
!isRefreshingTokens &&
!isSchedulingRefresh
) {
refreshTokens({
tokensCb: (newTokens) =>
newTokens &&
storeTokens(newTokens).then(() =>
setTokens((tokens) => ({ ...tokens, ...newTokens }))
),
isRefreshingCb: setIsRefreshingTokens,
}).catch(() => {
setTokens(undefined);
});
}
// At component mount, load tokens from storage
useEffect(() => {
retrieveTokens()
.then(setTokens)
.catch((err) => {
const { debug } = configure();
debug?.("Failed to retrieve tokens from storage:", err);
})
.finally(() => setInitiallyRetrievingTokensFromStorage(false));
}, [setTokens]);
// Give easy access to isUserVerifyingPlatformAuthenticatorAvailable
useEffect(() => {
if (typeof PublicKeyCredential !== "undefined") {
const cancel = new AbortController();
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()
.then((res) => {
if (!cancel.signal.aborted) {
setUserVerifyingPlatformAuthenticatorAvailable(res);
}
return () => cancel.abort();
})
.catch((err) => {
const { debug } = configure();
debug?.(
"Failed to determine if a user verifying platform authenticator is available:",
err
);
});
} else {
setUserVerifyingPlatformAuthenticatorAvailable(false);
}
}, []);
const toFido2Credential = useCallback(
(credential: StoredCredential) => {
return {
...credential,
busy: false,
update: async (update: { friendlyName: string }) => {
updateFido2Credential({
credentialId: credential.credentialId,
busy: true,
});
return fido2UpdateCredential({
...update,
credentialId: credential.credentialId,
})
.catch((err) => {
updateFido2Credential({
credentialId: credential.credentialId,
busy: false,
});
throw err;
})
.then(() =>
updateFido2Credential({
...update,
credentialId: credential.credentialId,
busy: false,
})
);
},
delete: async () => {
updateFido2Credential({
credentialId: credential.credentialId,
busy: true,
});
return fido2DeleteCredential({
credentialId: credential.credentialId,
})
.catch((err) => {
updateFido2Credential({
credentialId: credential.credentialId,
busy: false,
});
throw err;
})
.then(() => deleteFido2Credential(credential.credentialId));
},
};
},
[deleteFido2Credential, updateFido2Credential]
);
// Determine sign-in status
const signInStatus = useMemo(() => {
recheckSignInStatus; // dummy usage otherwise eslint complains we should remove it from the dep array
return tokensParsed && tokensParsed.expireAt.valueOf() >= Date.now()
? ("SIGNED_IN" as const)
: tokensParsed && (isSchedulingRefresh || isRefreshingTokens)
? ("REFRESHING_SIGN_IN" as const)
: busyState
.filter(
(state) =>
!["SIGNING_OUT", "CHECKING_FOR_SIGNIN_LINK"].includes(state)
)
.includes(signingInStatus as BusyState)
? ("SIGNING_IN" as const)
: initiallyRetrievingTokensFromStorage ||
signingInStatus === "CHECKING_FOR_SIGNIN_LINK"
? ("CHECKING" as const)
: signingInStatus === "SIGNING_OUT"
? ("SIGNING_OUT" as const)
: ("NOT_SIGNED_IN" as const);
}, [
tokensParsed,
isSchedulingRefresh,
isRefreshingTokens,
signingInStatus,
initiallyRetrievingTokensFromStorage,
recheckSignInStatus, // if this increments we should redetermine the signInStatus
]);
// Check signInStatus upon token expiry
useEffect(() => {
if (!tokens?.expireAt) return;
const checkIn = tokens.expireAt.valueOf() - Date.now();
if (checkIn < 0) return;
return setTimeoutWallClock(() => {
const { debug } = configure();
debug?.(
"Checking signInStatus as tokens have expired at:",
tokens.expireAt?.toISOString()
);
setRecheckSignInStatus((s) => s + 1);
}, checkIn);
}, [tokens?.expireAt]);
// Track FIDO2 authenticators for the user
const isSignedIn = signInStatus === "SIGNED_IN";
const revalidateFido2Credentials = () => {
const cancel = new AbortController();
if (isSignedIn) {
fido2ListCredentials()
.then((res) => {
if (!cancel.signal.aborted) {
setFido2Credentials(res.authenticators.map(toFido2Credential));
}
})
.catch((err) => {
const { debug } = configure();
debug?.("Failed to list credentials:", err);
});
return () => cancel.abort();
}
};
useEffect(revalidateFido2Credentials, [isSignedIn, toFido2Credential]);
return {
/** The (raw) tokens: ID token, Access token and Refresh Token */
tokens,
/** The JSON parsed ID and Access token */
tokensParsed,
/** Is the UI currently refreshing tokens? */
isRefreshingTokens,
/** Execute (and reschedule) token refresh */
refreshTokens: (abort?: AbortSignal) =>
refreshTokens({
abort,
tokensCb: (newTokens) =>
newTokens &&
storeTokens(newTokens).then(() =>
setTokens((tokens) => ({ ...tokens, ...newTokens }))
),
isRefreshingCb: setIsRefreshingTokens,
}),
/** Last error that occured */
lastError,
/** The status of the most recent sign-in attempt */
signingInStatus,
/** Are we currently busy signing in or out? */
busy,
/**
* The overall auth status, e.g. is the user signed in or not?
* Use this field to show the relevant UI, e.g. render a sign-in page,
* if the status equals "NOT_SIGNED_IN"
*/
signInStatus,
/** Is a user verifying platform authenticator available? E.g. Face ID or Touch */
userVerifyingPlatformAuthenticatorAvailable,
/** The user's registered FIDO2 credentials. Each credential provides `update` and `delete` methods */
fido2Credentials,
/** Are we currently creating a FIDO2 credential? */
creatingCredential,
/** Register a FIDO2 credential with the Relying Party */
fido2CreateCredential: (
...args: Parameters<typeof fido2CreateCredential>
) => {
setCreatingCredential(true);
return fido2CreateCredential(...args)
.then((storedCredential) => {
setFido2Credentials((state) => {
const credential = toFido2Credential(storedCredential);
return state ? state.concat([credential]) : [credential];
});
return storedCredential;
})
.finally(() => setCreatingCredential(false));
},
/** Sign out */
signOut: () => {
setLastError(undefined);
const signingOut = signOut({
statusCb: setSigninInStatus,
tokensRemovedLocallyCb: () => {
setTokens(undefined);
setTokensParsed(undefined);
setFido2Credentials(undefined);
},
currentStatus: signingInStatus,
});
signingOut.signedOut.catch(setLastError);
return signingOut;
},
/** Request a sign-in link ("magic link") to be sent to the user's e-mail address */
requestSignInLink: ({
username,
redirectUri,
}: {
username: string;
redirectUri?: string;
}) => {
setLastError(undefined);
const requesting = requestSignInLink({
username,
redirectUri,
statusCb: setSigninInStatus,
currentStatus: signingInStatus,
});
requesting.signInLinkRequested.catch(setLastError);
return requesting;
},
/** Sign in with FIDO2 (e.g. Face ID or Touch) */
authenticateWithFido2: ({
username,
credentials,
clientMetadata,
}: {
/**
* Username, or alias (e-mail, phone number)
*/
username?: string;
credentials?: { id: string; transports?: AuthenticatorTransport[] }[];
clientMetadata?: Record<string, string>;
} = {}) => {
setLastError(undefined);
const signinIn = authenticateWithFido2({
username,
credentials,
clientMetadata,
statusCb: setSigninInStatus,
tokensCb: (tokens) => storeTokens(tokens).then(() => setTokens(tokens)),
});
signinIn.signedIn.catch(setLastError);
return signinIn;
},
/** Sign in with username and password (using SRP: Secure Remote Password, where the password isn't sent over the wire) */
authenticateWithSRP: ({
username,
password,
smsMfaCode,
clientMetadata,
}: {
/**
* Username, or alias (e-mail, phone number)
*/
username: string;
password: string;
smsMfaCode?: () => Promise<string>;
clientMetadata?: Record<string, string>;
}) => {
setLastError(undefined);
const signinIn = authenticateWithSRP({
username,
password,
smsMfaCode,
clientMetadata,
statusCb: setSigninInStatus,
tokensCb: (tokens) => storeTokens(tokens).then(() => setTokens(tokens)),
});
signinIn.signedIn.catch(setLastError);
return signinIn;
},
/** Sign in with username and password (the password is sent in plaintext over the wire) */
authenticateWithPlaintextPassword: ({
username,
password,
smsMfaCode,
clientMetadata,
}: {
/**
* Username, or alias (e-mail, phone number)
*/
username: string;
password: string;
smsMfaCode?: () => Promise<string>;
clientMetadata?: Record<string, string>;
}) => {
setLastError(undefined);
const signinIn = authenticateWithPlaintextPassword({
username,
password,
smsMfaCode,
clientMetadata,
statusCb: setSigninInStatus,
tokensCb: (tokens) => storeTokens(tokens).then(() => setTokens(tokens)),
});
signinIn.signedIn.catch(setLastError);
return signinIn;
},
/** Sign-in again, using the user's current tokens (JWTs) and an OTP (One Time Password) that is sent to the user via SMS */
stepUpAuthenticationWithSmsOtp: ({
username,
smsMfaCode,
clientMetadata,
}: {
/**
* Username, or alias (e-mail, phone number)
*/
username: string;
smsMfaCode: (phoneNumber: string, attempt: number) => Promise<string>;
clientMetadata?: Record<string, string>;
}) => {
setLastError(undefined);
const signinIn = stepUpAuthenticationWithSmsOtp({
username,
smsMfaCode,
clientMetadata,
statusCb: setSigninInStatus,
tokensCb: (tokens) => storeTokens(tokens).then(() => setTokens(tokens)),
});
signinIn.signedIn.catch(setLastError);
return signinIn;
},
/** Should the FIDO2 credential manager UI component be shown? */
showAuthenticatorManager,
/** Toggle showing the FIDO2 credential manager UI component */
toggleShowAuthenticatorManager: useCallback(
() => setShowAuthenticatorManager((state) => !state),
[]
),
};
}
/** User Details stored in your configured storage (e.g. localStorage) */
type StoredUser = {
username: string;
email?: string;
useFido?: "YES" | "NO" | "ASK";
credentials?: { id: string; transports?: AuthenticatorTransport[] }[];
};
/** Retrieve the last signed in users from your configured storage (e.g. localStorage) */
async function getLastSignedInUsers() {
const { clientId, storage } = configure();
const lastUsers = await storage.getItem(`Passwordless.${clientId}.lastUsers`);
if (!lastUsers) return [];
const users = JSON.parse(lastUsers) as StoredUser[];
return users;
}
/** Clear the last signed in users from your configured storage (e.g. localStorage) */
async function clearLastSignedInUsers() {
const { clientId, storage } = configure();
await storage.removeItem(`Passwordless.${clientId}.lastUsers`);
}
/** Register a signed in user in your configured storage (e.g. localStorage) */
async function registerSignedInUser(user: StoredUser) {
const { clientId, debug, storage } = configure();
debug?.(`Registering user in storage: ${JSON.stringify(user)}`);
const lastUsers = await getLastSignedInUsers();
const index = lastUsers.findIndex(
(lastUser) => lastUser.username === user.username
);
if (index !== -1) {
lastUsers.splice(index, 1);
}
lastUsers.unshift(user);
await storage.setItem(
`Passwordless.${clientId}.lastUsers`,
JSON.stringify(lastUsers.slice(0, 10))
);
}
type UseLocalUserCache = ReturnType<typeof _useLocalUserCache>;
function _useLocalUserCache() {
const {
tokensParsed,
creatingCredential,
fido2Credentials,
signingInStatus,
} = usePasswordless();
const idToken = tokensParsed?.idToken;
const hasFido2Credentials = fido2Credentials && !!fido2Credentials.length;
const justSignedInWithMagicLink = signingInStatus === "SIGNED_IN_WITH_LINK";
const [lastSignedInUsers, setLastSignedInUsers] = useState<StoredUser[]>();
const [currentUser, setCurrentUser] = useState<StoredUser>();
const [fidoPreferenceOverride, setFidoPreferenceOverride] = useState<
"YES" | "NO"
>();
// 1 populate lastSignedInUsers from local storage
useEffect(() => {
getLastSignedInUsers()
.then(setLastSignedInUsers)
.catch((err) => {
const { debug } = configure();
debug?.("Failed to determine last signed-in users:", err);
});
}, []);
// 2 populate currentUser from lastSignedInUsers OR init currentUser
useEffect(() => {
if (!idToken) {
setCurrentUser(undefined);
return;
}
const user: StoredUser = {
username: idToken["cognito:username"],
email:
idToken.email && idToken.email_verified ? idToken.email : undefined,
};
if (lastSignedInUsers) {
const found = lastSignedInUsers.find(
(lastUser) =>
lastUser.username && lastUser.username === idToken["cognito:username"]
);
if (found) {
user.useFido = found.useFido;
user.credentials = found.credentials;
if (!idToken.email_verified) {
user.email = found.email;
}
}
}
setCurrentUser((state) =>
JSON.stringify(state) === JSON.stringify(user) ? state : user
);
}, [lastSignedInUsers, idToken]);
// 3 If user is updated, store in lastSignedInUsers
useEffect(() => {
if (currentUser) {
registerSignedInUser(currentUser).catch((err) => {
const { debug } = configure();
debug?.("Failed to register last signed-in user:", err);
});
setLastSignedInUsers((state) => {
const update = [currentUser];
for (const user of state ?? []) {
if (user.username !== currentUser.username) {
update.push(user);
}
}
return JSON.stringify(state) === JSON.stringify(update)
? state
: update;
});
}
}, [currentUser]);
const determineFido = useCallback(
(user: StoredUser): "YES" | "NO" | "ASK" | "INDETERMINATE" => {
const { fido2 } = configure();
if (!fido2) {
return "NO";
}
if (hasFido2Credentials === undefined) {
return "INDETERMINATE";
}
if (fidoPreferenceOverride) {
return fidoPreferenceOverride;
}
if (user.useFido === "NO") {
if (justSignedInWithMagicLink) {
return "ASK";
}
return "NO";
}
if (hasFido2Credentials) {
return "YES";
}
if (creatingCredential) {
return user.useFido ?? "INDETERMINATE";
}
return "ASK";
},
[
creatingCredential,
hasFido2Credentials,
fidoPreferenceOverride,
justSignedInWithMagicLink,
]
);
// 4 Update user FIDO preference
useEffect(() => {
if (currentUser) {
const useFido = determineFido(currentUser);
if (useFido === "INDETERMINATE") return;
setCurrentUser((state) => {
const update: StoredUser = {
...currentUser,
useFido,
credentials: fido2Credentials?.map((c) => ({
id: c.credentialId,
transports: c.transports,
})),
};
return JSON.stringify(state) === JSON.stringify(update)
? state
: update;
});
}
}, [currentUser, determineFido, fido2Credentials]);
// 5 reset state on signOut
useEffect(() => {
if (!currentUser) setFidoPreferenceOverride(undefined);
}, [currentUser]);
return {
/** The current signed-in user */
currentUser,
/** Update the current user's FIDO2 preference */
updateFidoPreference: ({ useFido }: { useFido: "YES" | "NO" }) => {
setFidoPreferenceOverride(useFido);
},
/** The list of the 10 last signed-in users in your configured storage (e.g. localStorage) */
lastSignedInUsers,
/** Clear the last signed in users from your configured storage (e.g. localStorage) */
clearLastSignedInUsers: () => {
clearLastSignedInUsers().catch((err) => {
const { debug } = configure();
debug?.("Failed to clear last signed-in users:", err);
});
setLastSignedInUsers(undefined);
},
};
}
/** React hook to turn state (or any variable) into a promise that can be awaited */
export function useAwaitableState<T>(state: T) {
const resolve = useRef<(value: T) => void>();
const reject = useRef<(reason: Error) => void>();
const awaitable = useRef<Promise<T>>();
const [awaited, setAwaited] = useState<{ value: T }>();
const renewPromise = useCallback(() => {
awaitable.current = new Promise<T>((_resolve, _reject) => {
resolve.current = _resolve;
reject.current = _reject;
})
.then((value) => {
setAwaited({ value });
return value;
})
.finally(renewPromise);
}, []);
useEffect(renewPromise, [renewPromise]);
useEffect(() => setAwaited(undefined), [state]);
return {
/** Call to get the current awaitable (promise) */
awaitable: () => awaitable.current!,
/** Resolve the current awaitable (promise) with the current value of state */
resolve: () => resolve.current!(state),
/** Reject the current awaitable (promise) */
reject: (reason: Error) => reject.current!(reason),
/** That value of awaitable (promise) once it resolves. This is undefined if (1) awaitable is not yet resolved or (2) the state has changed since awaitable was resolved */
awaited,
};
}