-
Notifications
You must be signed in to change notification settings - Fork 14
/
SecureUnlockProvider.tsx
235 lines (206 loc) · 7.45 KB
/
SecureUnlockProvider.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
import { useQuery } from '@tanstack/react-query'
import { type PropsWithChildren, createContext, useContext, useState } from 'react'
import { KeychainError } from '../error/KeychainError'
import { secureWalletKey } from './secureWalletKey'
const SecureUnlockContext = createContext<SecureUnlockReturn<Record<string, unknown>>>({
state: 'initializing',
})
export function useSecureUnlock<Context extends Record<string, unknown>>(): SecureUnlockReturn<Context> {
const value = useContext(SecureUnlockContext)
if (!value) {
throw new Error('useSecureUnlock must be wrapped in a <SecureUnlockProvider />')
}
return value as SecureUnlockReturn<Context>
}
export function SecureUnlockProvider({ children }: PropsWithChildren) {
const secureUnlockState = _useSecureUnlockState()
return (
<SecureUnlockContext.Provider value={secureUnlockState as SecureUnlockReturn<Record<string, unknown>>}>
{children}
</SecureUnlockContext.Provider>
)
}
export type SecureUnlockState = 'initializing' | 'not-configured' | 'locked' | 'acquired-wallet-key' | 'unlocked'
export type SecureUnlockMethod = 'pin' | 'biometrics'
export type SecureUnlockReturnInitializing = {
state: 'initializing'
}
export type SecureUnlockReturnNotConfigured = {
state: 'not-configured'
setup: (pin: string) => Promise<{ walletKey: string }>
reinitialize: () => void
}
export type SecureUnlockReturnLocked = {
state: 'locked'
tryUnlockingUsingBiometrics: () => Promise<string | null>
canTryUnlockingUsingBiometrics: boolean
unlockUsingPin: (pin: string) => Promise<string>
isUnlocking: boolean
reinitialize: () => void
}
export type SecureUnlockReturnWalletKeyAcquired<Context extends Record<string, unknown>> = {
state: 'acquired-wallet-key'
walletKey: string
unlockMethod: SecureUnlockMethod
setWalletKeyValid: (context: Context, options: { enableBiometrics: boolean }) => Promise<void>
setWalletKeyInvalid: () => void
reinitialize: () => void
}
export type SecureUnlockReturnUnlocked<Context extends Record<string, unknown>> = {
state: 'unlocked'
unlockMethod: SecureUnlockMethod
context: Context
lock: () => void
reinitialize: () => void
}
export type SecureUnlockReturn<Context extends Record<string, unknown>> =
| SecureUnlockReturnInitializing
| SecureUnlockReturnNotConfigured
| SecureUnlockReturnLocked
| SecureUnlockReturnWalletKeyAcquired<Context>
| SecureUnlockReturnUnlocked<Context>
function _useSecureUnlockState<Context extends Record<string, unknown>>(): SecureUnlockReturn<Context> {
const [state, setState] = useState<SecureUnlockState>('initializing')
const [walletKey, setWalletKey] = useState<string>()
const [canTryUnlockingUsingBiometrics, setCanTryUnlockingUsingBiometrics] = useState<boolean>(true)
const [biometricsUnlockAttempts, setBiometricsUnlockAttempts] = useState(0)
const [canUseBiometrics, setCanUseBiometrics] = useState<boolean>()
const [unlockMethod, setUnlockMethod] = useState<SecureUnlockMethod>()
const [context, setContext] = useState<Context>()
const [isUnlocking, setIsUnlocking] = useState(false)
useQuery({
queryFn: async () => {
const salt = await secureWalletKey.getSalt(secureWalletKey.getWalletKeyVersion())
// TODO: is salt the best way to test this?
// We have two params. If e.g. unlocking using biometrics failed, we will
// set setCanTryUnlockingUsingBiometrics to false, but `setCanUseBiometrics`
// will still be true (so we can store it)
const canUseBiometrics = await secureWalletKey.canUseBiometryBackedWalletKey()
setCanUseBiometrics(canUseBiometrics)
setCanTryUnlockingUsingBiometrics(canUseBiometrics)
setState(salt ? 'locked' : 'not-configured')
return salt
},
queryKey: ['wallet_unlock_salt'],
enabled: state === 'initializing',
})
const reinitialize = () => {
setState('initializing')
setWalletKey(undefined)
setCanTryUnlockingUsingBiometrics(true)
setBiometricsUnlockAttempts(0)
setCanUseBiometrics(undefined)
setUnlockMethod(undefined)
setContext(undefined)
setIsUnlocking(false)
}
if (state === 'acquired-wallet-key') {
if (!walletKey || !unlockMethod) {
throw new Error('Missing walletKey or unlockMethod')
}
return {
state,
walletKey,
unlockMethod,
reinitialize,
setWalletKeyInvalid: () => {
if (unlockMethod === 'biometrics') {
setCanTryUnlockingUsingBiometrics(false)
}
setState('locked')
setWalletKey(undefined)
setUnlockMethod(undefined)
},
setWalletKeyValid: async (context, options) => {
setContext(context)
setState('unlocked')
// TODO: need extra option to know whether user wants to use biometrics?
// TODO: do we need to check whether already stored?
if (canUseBiometrics && options.enableBiometrics) {
await secureWalletKey.storeWalletKey(walletKey, secureWalletKey.getWalletKeyVersion())
}
},
}
}
if (state === 'unlocked') {
if (!walletKey || !unlockMethod || !context) {
throw new Error('Missing walletKey, unlockMethod or context')
}
return {
state,
context,
unlockMethod,
reinitialize,
lock: () => {
setState('locked')
setWalletKey(undefined)
setUnlockMethod(undefined)
setContext(undefined)
},
}
}
if (state === 'locked') {
return {
state,
isUnlocking,
canTryUnlockingUsingBiometrics,
reinitialize,
tryUnlockingUsingBiometrics: async () => {
// TODO: need to somehow inform user that the unlocking went wrong
if (!canTryUnlockingUsingBiometrics) return null
setIsUnlocking(true)
setBiometricsUnlockAttempts((attempts) => attempts + 1)
try {
const walletKey = await secureWalletKey.getWalletKeyUsingBiometrics(secureWalletKey.getWalletKeyVersion())
if (walletKey) {
setWalletKey(walletKey)
setUnlockMethod('biometrics')
setState('acquired-wallet-key')
}
return walletKey
} catch (error) {
// If use cancelled we won't allow trying using biometrics again
if (error instanceof KeychainError && error.reason === 'userCancelled') {
setCanTryUnlockingUsingBiometrics(false)
}
// If other error, we will allow up to three attempts
else if (biometricsUnlockAttempts > 3) {
setCanTryUnlockingUsingBiometrics(false)
}
} finally {
setIsUnlocking(false)
}
return null
},
unlockUsingPin: async (pin: string) => {
setIsUnlocking(true)
try {
const walletKey = await secureWalletKey.getWalletKeyUsingPin(pin, secureWalletKey.getWalletKeyVersion())
setWalletKey(walletKey)
setUnlockMethod('pin')
setState('acquired-wallet-key')
return walletKey
} finally {
setIsUnlocking(false)
}
},
}
}
if (state === 'not-configured') {
return {
state,
reinitialize,
setup: async (pin) => {
await secureWalletKey.createAndStoreSalt(true, secureWalletKey.getWalletKeyVersion())
const walletKey = await secureWalletKey.getWalletKeyUsingPin(pin, secureWalletKey.getWalletKeyVersion())
setWalletKey(walletKey)
setUnlockMethod('pin')
setState('acquired-wallet-key')
return { walletKey }
},
}
}
return {
state,
}
}