forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseNativeBiometricsHSM.ts
More file actions
205 lines (176 loc) · 8.37 KB
/
Copy pathuseNativeBiometricsHSM.ts
File metadata and controls
205 lines (176 loc) · 8.37 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
import addMFABreadcrumb from '@components/MultifactorAuthentication/observability/breadcrumbs';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useLocalize from '@hooks/useLocalize';
import {buildSigningData, decodeLibraryError, getKeyAlias, mapAuthTypeNumber, mapSignErrorCodeToReason} from '@libs/MultifactorAuthentication/NativeBiometricsHSM/helpers';
import type NativeBiometricsHSMKeyInfo from '@libs/MultifactorAuthentication/NativeBiometricsHSM/types';
import {createLocalMFAError} from '@libs/MultifactorAuthentication/shared/MFAResult';
import VALUES from '@libs/MultifactorAuthentication/VALUES';
import CONST from '@src/CONST';
import Base64URL from '@src/utils/Base64URL';
import type {SignatureResult} from '@sbaiahmed1/react-native-biometrics';
import {createKeys, deleteKeys, getAllKeys, InputEncoding, signWithOptions} from '@sbaiahmed1/react-native-biometrics';
import type {AuthorizeParams, AuthorizeResult, RegisterResult, UseBiometricsReturn} from './shared/types';
import useServerCredentials from './shared/useServerCredentials';
/**
* UTILS START
* These utils were added to comply with react compiler requirements:
* "Error: Support value blocks (conditional, logical, optional chaining, etc) within a try/catch statement"
*/
function isCredentialAllowed(credentialID: string | undefined, allowedIDs: string[]): credentialID is string {
return !!credentialID && allowedIDs.includes(credentialID);
}
function hasValidSignature(signResult: SignatureResult): signResult is SignatureResult & {signature: string} {
return signResult.success && !!signResult.signature;
}
/**
* UTILS END
*/
/**
* Native biometrics hook using HSM-backed EC P-256 keys via react-native-biometrics.
* All cryptographic operations happen in native code (Secure Enclave / Android Keystore).
* Private keys never enter JS memory.
*/
function useNativeBiometricsHSM(): UseBiometricsReturn {
const {accountID} = useCurrentUserPersonalDetails();
const {translate} = useLocalize();
const {serverKnownCredentialIDs, haveCredentialsEverBeenConfigured} = useServerCredentials();
const getLocalCredentialID = async () => {
try {
const keyAlias = getKeyAlias(accountID);
const {keys} = await getAllKeys(keyAlias);
const entry = keys.at(0);
if (!entry) {
return undefined;
}
return Base64URL.base64ToBase64url(entry.publicKey);
} catch (error) {
addMFABreadcrumb('Failed to get local credential ID', decodeLibraryError(error), 'error');
return undefined;
}
};
/**
* 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.native.ts` until the hook is removed.
*/
const areLocalCredentialsKnownToServer = async () => {
const key = await getLocalCredentialID();
return !!key && serverKnownCredentialIDs.includes(key);
};
const deleteLocalKeysForAccount = async () => {
try {
const keyAlias = getKeyAlias(accountID);
await deleteKeys(keyAlias);
} catch (error) {
addMFABreadcrumb('Failed to delete local keys', decodeLibraryError(error), 'error');
}
};
const register = async (onResult: (result: RegisterResult) => Promise<void> | void, registrationChallenge: Parameters<UseBiometricsReturn['register']>[1]) => {
try {
const keyAlias = getKeyAlias(accountID);
/**
* createKeys called with:
* keyAlias - alias associated with the key stored on the device
* keyType: 'ec256' - Elliptic Curve P-256 key
* biometricStrength: undefined - currently ignored when allowDeviceCredentials is set to true
* allowDeviceCredentials: true - allow device credentials fallback when biometrics are unavailable
* failIfExists: false - overwrite any existing key for this alias to support re-registration
*/
const {publicKey} = await createKeys(keyAlias, 'ec256', undefined, true, false);
const credentialID = Base64URL.base64ToBase64url(publicKey);
const clientDataJSON = JSON.stringify({challenge: registrationChallenge.challenge});
const keyInfo: NativeBiometricsHSMKeyInfo = {
rawId: credentialID,
type: CONST.MULTIFACTOR_AUTHENTICATION.BIOMETRICS_HSM_TYPE,
response: {
clientDataJSON: Base64URL.encode(clientDataJSON),
biometric: {
publicKey: credentialID,
algorithm: CONST.COSE_ALGORITHM.ES256,
},
},
};
await onResult({
success: true,
keyInfo,
});
} catch (error) {
onResult({
success: false,
error: decodeLibraryError(error),
});
}
};
const authorize = async (params: AuthorizeParams, onResult: (result: AuthorizeResult) => Promise<void> | void) => {
const {challenge} = params;
try {
const keyAlias = getKeyAlias(accountID);
const credentialID = await getLocalCredentialID();
const allowedIDs = challenge.allowCredentials.map((credential: {id: string; type: string}) => credential.id);
if (!isCredentialAllowed(credentialID, allowedIDs)) {
await deleteLocalKeysForAccount();
onResult({
success: false,
error: createLocalMFAError(VALUES.REASON.LOCAL_ERRORS.HSM.NO_MATCHING_LOCAL_CREDENTIAL, 'Local HSM credential not in challenge allowCredentials, keys deleted'),
});
return;
}
const {authenticatorData, clientDataJSON, dataToSignB64} = await buildSigningData(challenge.rpId, challenge.challenge);
// Sign with biometric prompt — signWithOptions
const signResult = await signWithOptions({
keyAlias,
data: dataToSignB64,
inputEncoding: InputEncoding.Base64,
promptTitle: translate('multifactorAuthentication.letsVerifyItsYou'),
promptSubtitle: '',
returnAuthType: true,
});
if (!hasValidSignature(signResult)) {
const failReason = mapSignErrorCodeToReason(signResult.errorCode) ?? VALUES.REASON.LOCAL_ERRORS.HSM.UNRECOGNIZED;
onResult({
success: false,
error: createLocalMFAError(failReason, `Error Code: ${signResult.errorCode}`),
});
return;
}
const authType = mapAuthTypeNumber(signResult.authType);
if (!authType) {
onResult({
success: false,
error: createLocalMFAError(VALUES.REASON.LOCAL_ERRORS.HSM.UNRECOGNIZED_AUTH_TYPE, `Unrecognized auth type from HSM sign result: ${signResult.authType}`),
});
return;
}
await onResult({
success: true,
signedChallenge: {
rawId: credentialID,
type: CONST.MULTIFACTOR_AUTHENTICATION.BIOMETRICS_HSM_TYPE,
response: {
authenticatorData: Base64URL.base64ToBase64url(authenticatorData.toString('base64')),
clientDataJSON: Base64URL.encode(clientDataJSON),
signature: Base64URL.base64ToBase64url(signResult.signature),
},
},
authenticationMethod: authType,
});
} catch (error) {
onResult({
success: false,
error: decodeLibraryError(error),
});
}
};
const hasLocalCredentials = async () => !!(await getLocalCredentialID());
return {
serverKnownCredentialIDs,
haveCredentialsEverBeenConfigured,
getLocalCredentialID,
hasLocalCredentials,
areLocalCredentialsKnownToServer,
register,
authorize,
deleteLocalKeysForAccount,
};
}
export default useNativeBiometricsHSM;