-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.tsx
315 lines (293 loc) · 9.04 KB
/
App.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
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* Generated with the TypeScript template
* https://github.com/react-native-community/react-native-template-typescript
*
* @format
*/
import React, { useCallback, useEffect, useMemo, useState, PropsWithChildren } from 'react';
import {
Button,
Platform,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
TextInput,
useColorScheme,
View,
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import * as ec from '@toruslabs/eccrypto';
import { ShareSerializationModule } from '@tkey/share-serialization';
import SecurityQuestionsModule from '@tkey/security-questions';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import BN from 'bn.js';
import CustomAuth from '@toruslabs/customauth-react-native-sdk';
import ThresholdKey from '@tkey/default';
import TorusServiceProvider from '@tkey/service-provider-base';
import TorusStorageLayer from '@tkey/storage-layer-torus';
import { ShareTransferModule } from '@tkey/share-transfer';
import { generatePrivateExcludingIndexes } from '@tkey/common-types';
const Section: React.FC<
PropsWithChildren<{
title: string;
}>
> = ({ children, title }) => {
const isDarkMode = useColorScheme() === 'dark';
return (
<View style={styles.sectionContainer}>
<Text
style={[
styles.sectionTitle,
{
color: isDarkMode ? Colors.white : Colors.black,
},
]}
>
{title}
</Text>
<Text
style={[
styles.sectionDescription,
{
color: isDarkMode ? Colors.light : Colors.dark,
},
]}
>
{children}
</Text>
</View>
);
};
const GOOGLE = 'google';
const verifierMap = {
[GOOGLE]: {
name: 'Google',
typeOfLogin: 'google',
clientId: '759944447575-6rm643ia1i9ngmnme3eq5viiep5rp6s0.apps.googleusercontent.com',
verifier: 'sk-react-native-test',
},
};
const directParams = {
baseUrl: `http://localhost:3000/serviceworker/`,
enableLogging: true,
network: 'celeste',
};
const serviceProvider = new TorusServiceProvider({
customAuthArgs: directParams,
} as any);
const storageLayer = new TorusStorageLayer({
hostUrl: 'https://metadata.tor.us',
});
const shareTransferModule = new ShareTransferModule();
const shareSerializationModule = new ShareSerializationModule();
const securityQuestionsModule = new SecurityQuestionsModule();
const tKey = new ThresholdKey({
serviceProvider: serviceProvider,
storageLayer,
modules: {
shareTransfer: shareTransferModule,
securityQuestions: securityQuestionsModule,
shareSerializationModule: shareSerializationModule,
},
});
// disable on prod
const setMetadataKey = true;
const App = () => {
const isDarkMode = useColorScheme() === 'dark';
const [authVerifier] = useState('google');
const [logs, setLogs] = useState([]);
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
const addLog = useCallback((...log: any) => {
// @ts-ignore
setLogs((logs) => ['>' + JSON.stringify(log), ...logs]);
}, []);
const [thirdShareRequired, setThirdShareRequired] = useState(false);
const [freshPassword, onChangeFreshPassword] = useState('');
const [confirmPassword, onChangeConfirmPassword] = useState('');
useEffect(() => {
try {
CustomAuth.init({
browserRedirectUri: 'https://scripts.toruswallet.io/redirect.html',
redirectUri: 'torusapp://org.torusresearch.customauthexample/redirect',
network: 'celeste', // details for test net
enableLogging: true,
enableOneKey: false,
skipSw: true,
});
} catch (error) {
console.log(error, 'mounted caught');
}
});
const login = async (reLogin = false) => {
try {
const { typeOfLogin, clientId, verifier, jwtParams } = (verifierMap as any)[authVerifier];
const loginDetails = await CustomAuth.triggerLogin({
typeOfLogin,
verifier,
clientId,
jwtParams,
});
addLog({ loginDetails });
let pbKey = new BN(loginDetails.privateKey, 16);
tKey.serviceProvider.postboxKey = pbKey;
// tKey.serviceProvider.postboxKey = new BN(ec.generatePrivate());
// disable in prod
if (setMetadataKey) {
await tKey.storageLayer.setMetadata({
privKey: pbKey,
input: { message: 'KEY_NOT_FOUND' },
});
}
const res = await tKey.initialize();
// let keyDetails = await tKey.initialize(); // metadata is from the above step
addLog({ res });
} catch (error) {
addLog(error, 'login caught');
}
};
const createDeviceShare = async () => {
try {
const polyId = tKey.metadata.getLatestPublicPolynomial().getPolynomialID();
const shares = tKey.shares[polyId];
let deviceShare = null;
for (const shareIndex in shares) {
if (shareIndex !== '1') {
deviceShare = shares[shareIndex].share;
}
}
const serializedShare = (await (
tKey.modules.shareSerializationModule as ShareSerializationModule
).serialize(deviceShare?.share as BN, 'mnemonic')) as string;
addLog('serializedShare', serializedShare);
// save to device
await AsyncStorage.setItem('deviceShare', serializedShare);
} catch (error) {
addLog(error, 'login caught');
}
};
const backupSecurityShare = async () => {
try {
// generate a new share(); - security question share - enter your phone number
const securityShare = await (
tKey.modules.securityQuestions as SecurityQuestionsModule
).generateNewShareWithSecurityQuestions(freshPassword.toString(), 'whats your password?');
addLog({ securityShare });
onChangeFreshPassword("");
setThirdShareRequired(true);
} catch (error) {
addLog(error, 'login caught');
}
};
const reLogin = async () => {
await login(true);
try {
const deviceShareMnemonic = await AsyncStorage.getItem('deviceShare');
addLog({ deviceShareMnemonic });
if (deviceShareMnemonic) {
const deviceShare = await (
tKey.modules.shareSerializationModule as ShareSerializationModule
).deserialize(deviceShareMnemonic, 'mnemonic');
tKey.inputShare(deviceShare);
const reconstructKey = await tKey.reconstructKey();
addLog({ reconstructKey });
} else {
setThirdShareRequired(true);
}
} catch (error) {
addLog(error, 'login caught');
}
};
const enterBackupShare = async (password: string) => {
// generate a new share(); - security question share - enter your phone number
try {
await (
tKey.modules.securityQuestions as SecurityQuestionsModule
).inputShareFromSecurityQuestions(password);
const reconstructKey = await tKey.reconstructKey();
addLog({ reconstructKey });
} catch (error) {
addLog(error, 'wrong password');
}
};
return (
<View style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<ScrollView
contentContainerStyle={{
padding: 40,
paddingTop: 10,
flexGrow: 1,
}}
style={{ flex: 1, paddingTop: 50 }}
>
<Button title="Login" onPress={() => login()} />
<Button title="Store 2nd share on device" onPress={() => createDeviceShare()} />
<TextInput
style={{
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
}}
// onChangeText={thirdShareRequired ? onChangeFreshPassword : onChangeConfirmPassword}
value={thirdShareRequired ? confirmPassword : freshPassword}
onChangeText={thirdShareRequired ? onChangeConfirmPassword : onChangeFreshPassword}
placeholder={thirdShareRequired ? 'confirm your password' : 'enter your password'}
keyboardType="numeric"
/>
{!thirdShareRequired && (
<Button title="Create 3rd Share as Password" onPress={() => backupSecurityShare()} />
)}
{thirdShareRequired && (
<Button title="enter password" onPress={() => enterBackupShare(confirmPassword)} />
)}
<Button title="Re Login" onPress={() => reLogin()} />
{logs.map((log, i) => (
<Text
key={`t-${i}`}
style={{
fontFamily: Platform.OS === 'ios' ? 'Courier New' : 'monospace',
color: '#111',
fontSize: 14,
}}
>
{log}
</Text>
))}
</ScrollView>
</View>
</View>
);
};
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
});
export default App;