forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathusePasskeys.ts
More file actions
197 lines (171 loc) · 7.75 KB
/
Copy pathusePasskeys.ts
File metadata and controls
197 lines (171 loc) · 7.75 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
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useOnyx from '@hooks/useOnyx';
import {
arrayBufferToBase64URL,
authenticateWithPasskey,
buildAllowedCredentialDescriptors,
buildPublicKeyCredentialCreationOptions,
buildPublicKeyCredentialRequestOptions,
createPasskeyCredential,
decodeWebAuthnError,
extractAAGUID,
isSupportedTransport,
PASSKEY_AUTH_TYPE,
} from '@libs/MultifactorAuthentication/Passkeys/WebAuthn';
import type {RegistrationChallenge} from '@libs/MultifactorAuthentication/shared/challengeTypes';
import {createLocalMFAError} from '@libs/MultifactorAuthentication/shared/MFAResult';
import VALUES from '@libs/MultifactorAuthentication/VALUES';
import {addLocalPasskeyCredential, deleteLocalPasskeyCredentials, getPasskeyOnyxKey, reconcileLocalPasskeysWithBackend} from '@userActions/Passkey';
import CONST from '@src/CONST';
import type {AuthorizeParams, AuthorizeResult, RegisterResult, UseBiometricsReturn} from './shared/types';
import useServerCredentials from './shared/useServerCredentials';
function usePasskeys(): UseBiometricsReturn {
const {accountID} = useCurrentUserPersonalDetails();
const userId = String(accountID);
const {serverKnownCredentialIDs, haveCredentialsEverBeenConfigured} = useServerCredentials();
const [localPasskeyCredentials] = useOnyx(getPasskeyOnyxKey(userId));
const getLocalCredentialID = async (): Promise<string | undefined> => {
return (localPasskeyCredentials ?? []).at(0)?.id;
};
const hasLocalCredentials = async () => (localPasskeyCredentials?.length ?? 0) > 0;
/**
* Legacy compatibility path. The MFA machine uses the platform-resolved biometrics operation,
* while this hook keeps using reactive Onyx values for existing React consumers. Keep this
* comparison aligned with `operations/index.ts` until the hook is removed.
*/
const areLocalCredentialsKnownToServer = async () => {
const serverSet = new Set(serverKnownCredentialIDs);
return (localPasskeyCredentials ?? []).some((c) => serverSet.has(c.id));
};
const deleteLocalKeysForAccount = async () => {
deleteLocalPasskeyCredentials(userId);
};
const register = async (onResult: (result: RegisterResult) => Promise<void> | void, registrationChallenge: RegistrationChallenge) => {
const backendCredentials = serverKnownCredentialIDs.map((id) => ({id, type: CONST.PASSKEY_CREDENTIAL_TYPE}));
const reconciledExisting = reconcileLocalPasskeysWithBackend({
userId,
backendCredentials,
localCredentials: localPasskeyCredentials ?? null,
});
const publicKeyOptions = buildPublicKeyCredentialCreationOptions(registrationChallenge, reconciledExisting);
let credential: PublicKeyCredential;
try {
credential = await createPasskeyCredential(publicKeyOptions);
} catch (error) {
await onResult({
success: false,
error: decodeWebAuthnError(error),
});
return;
}
if (!(credential.response instanceof AuthenticatorAttestationResponse)) {
await onResult({
success: false,
error: createLocalMFAError(VALUES.REASON.LOCAL_ERRORS.WEBAUTHN.UNEXPECTED_RESPONSE, 'Registration credential response is not AuthenticatorAttestationResponse'),
});
return;
}
const attestationResponse = credential.response;
const credentialId = arrayBufferToBase64URL(credential.rawId);
const clientDataJSON = arrayBufferToBase64URL(attestationResponse.clientDataJSON);
const attestationObject = arrayBufferToBase64URL(attestationResponse.attestationObject);
const transports = attestationResponse.getTransports?.().filter(isSupportedTransport);
// getAuthenticatorData() is a WebAuthn Level 2 method — not available in older browsers.
// NOTE: A value of "00000000-0000-0000-0000-000000000000" is expected for Apple iCloud Keychain
const aaguid = attestationResponse.getAuthenticatorData ? extractAAGUID(attestationResponse.getAuthenticatorData()) : undefined;
addLocalPasskeyCredential({
userId,
credential: {
id: credentialId,
type: CONST.PASSKEY_CREDENTIAL_TYPE,
transports,
aaguid,
},
existingCredentials: localPasskeyCredentials ?? null,
});
await onResult({
success: true,
keyInfo: {
rawId: credentialId,
type: CONST.PASSKEY_CREDENTIAL_TYPE,
transports,
aaguid,
response: {
clientDataJSON,
attestationObject,
},
},
});
};
const authorize = async (params: AuthorizeParams, onResult: (result: AuthorizeResult) => Promise<void> | void) => {
const {challenge} = params;
const backendCredentials = challenge.allowCredentials?.map((c) => ({id: c.id, type: CONST.PASSKEY_CREDENTIAL_TYPE})) ?? [];
const reconciled = reconcileLocalPasskeysWithBackend({
userId,
backendCredentials,
localCredentials: localPasskeyCredentials ?? null,
});
if (reconciled.length === 0) {
await deleteLocalKeysForAccount();
await onResult({
success: false,
error: createLocalMFAError(
VALUES.REASON.LOCAL_ERRORS.WEBAUTHN.NO_MATCHING_LOCAL_CREDENTIAL,
'No local passkey credentials match challenge allowCredentials, credentials cleared',
),
});
return;
}
const allowCredentials = buildAllowedCredentialDescriptors(reconciled);
const publicKeyOptions = buildPublicKeyCredentialRequestOptions(challenge, allowCredentials);
let assertion: PublicKeyCredential;
try {
assertion = await authenticateWithPasskey(publicKeyOptions);
} catch (error) {
await onResult({
success: false,
error: decodeWebAuthnError(error),
});
return;
}
if (!(assertion.response instanceof AuthenticatorAssertionResponse)) {
await onResult({
success: false,
error: createLocalMFAError(VALUES.REASON.LOCAL_ERRORS.WEBAUTHN.UNEXPECTED_RESPONSE, 'Authentication assertion response is not AuthenticatorAssertionResponse'),
});
return;
}
const assertionResponse = assertion.response;
const rawId = arrayBufferToBase64URL(assertion.rawId);
const authenticatorData = arrayBufferToBase64URL(assertionResponse.authenticatorData);
const clientDataJSON = arrayBufferToBase64URL(assertionResponse.clientDataJSON);
const signature = arrayBufferToBase64URL(assertionResponse.signature);
await onResult({
success: true,
signedChallenge: {
rawId,
type: CONST.PASSKEY_CREDENTIAL_TYPE,
response: {
authenticatorData,
clientDataJSON,
signature,
},
},
authenticationMethod: {
name: PASSKEY_AUTH_TYPE.NAME,
marqetaValue: PASSKEY_AUTH_TYPE.MARQETA_VALUE,
},
});
};
return {
serverKnownCredentialIDs,
haveCredentialsEverBeenConfigured,
getLocalCredentialID,
hasLocalCredentials,
areLocalCredentialsKnownToServer,
register,
authorize,
deleteLocalKeysForAccount,
};
}
export default usePasskeys;