-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathindex.tsx
More file actions
347 lines (304 loc) · 9.57 KB
/
index.tsx
File metadata and controls
347 lines (304 loc) · 9.57 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
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
import { Linking, Platform, Pressable, ScrollView, StyleSheet, Text, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Application from "expo-application";
import * as passkey from "react-native-passkeys";
import alert from "../utils/alert";
import React from "react";
import { base64 } from "@hexagon/base64";
import type {
Base64URLString,
PublicKeyCredentialUserEntityJSON,
} from "@simplewebauthn/typescript-types";
// ! taken from https://github.com/MasterKale/SimpleWebAuthn/blob/e02dce6f2f83d8923f3a549f84e0b7b3d44fa3da/packages/browser/src/helpers/bufferToBase64URLString.ts
/**
* Convert the given array buffer into a Base64URL-encoded string. Ideal for converting various
* credential response ArrayBuffers to string for sending back to the server as JSON.
*
* Helper method to compliment `base64URLStringToBuffer`
*/
export function bufferToBase64URLString(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let str = "";
for (const charCode of bytes) {
str += String.fromCharCode(charCode);
}
const base64String = btoa(str);
return base64String.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
// ! taken from https://github.com/MasterKale/SimpleWebAuthn/blob/e02dce6f2f83d8923f3a549f84e0b7b3d44fa3da/packages/browser/src/helpers/utf8StringToBuffer.ts
/**
* A helper method to convert an arbitrary string sent from the server to an ArrayBuffer the
* authenticator will expect.
*/
export function utf8StringToBuffer(value: string): ArrayBuffer {
return new TextEncoder().encode(value).buffer;
}
/**
* Decode a base64url string into its original string
*/
export function base64UrlToString(base64urlString: Base64URLString): string {
return base64.toString(base64urlString, true);
}
const bundleId = Application.applicationId?.split(".").reverse().join(".");
// the example app is running on the web.app domain but the bundleId is com.web.react-native-passkeys
// so we need to replace the last part of the bundleId with the domain
const hostname = bundleId?.replaceAll("web.com", "web.app")?.replaceAll("_", "-");
const rp = {
id: Platform.select({
web: undefined,
ios: hostname,
android: hostname,
}),
name: "ReactNativePasskeys",
} satisfies PublicKeyCredentialRpEntity;
// Don't do this in production!
const challenge = bufferToBase64URLString(utf8StringToBuffer("fizz"));
const user = {
id: bufferToBase64URLString(utf8StringToBuffer("290283490")),
displayName: "username",
name: "username",
} satisfies PublicKeyCredentialUserEntityJSON;
const authenticatorSelection = {
userVerification: "required",
residentKey: "required",
} satisfies AuthenticatorSelectionCriteria;
type CreationResponse = NonNullable<Awaited<ReturnType<typeof passkey.create>>>;
type GetResponse = NonNullable<Awaited<ReturnType<typeof passkey.get>>>;
type Result = CreationResponse | GetResponse | null;
export default function App() {
const insets = useSafeAreaInsets();
const [result, setResult] = React.useState<Result>(null);
const [creationResponse, setCreationResponse] = React.useState<
CreationResponse["response"] | null
>(null);
const [credentialId, setCredentialId] = React.useState("");
const createPasskey = async () => {
try {
const json = await passkey.create({
challenge,
pubKeyCredParams: [{ alg: -7, type: "public-key" }],
rp,
user,
authenticatorSelection,
extensions: {
...(Platform.OS !== "android" && { largeBlob: { support: "required" } }),
prf: {},
},
});
console.log("creation json -", json);
if (json?.rawId) setCredentialId(json.rawId);
if (json?.response) setCreationResponse(json.response);
setResult(json);
} catch (e) {
console.error("create error", e);
}
};
const authenticatePasskey = async () => {
const json = await passkey.get({
rpId: rp.id,
challenge,
...(credentialId && {
allowCredentials: [{ id: credentialId, type: "public-key" }],
}),
});
console.log("authentication json -", json);
setResult(json);
};
const writeBlob = async () => {
console.log("user credential id -", credentialId);
if (!credentialId) {
alert("No user credential id found - large blob requires a selected credential");
return;
}
const json = await passkey.get({
rpId: rp.id,
challenge,
extensions: {
largeBlob: { write: bufferToBase64URLString(utf8StringToBuffer("Hey its a private key!")) },
},
...(credentialId && {
allowCredentials: [{ id: credentialId, type: "public-key" }],
}),
});
console.log("add blob json -", json);
const written = json?.clientExtensionResults?.largeBlob?.written;
if (written) alert("This blob was written to the passkey");
setResult(json);
};
const readBlob = async () => {
const json = await passkey.get({
rpId: rp.id,
challenge,
extensions: { largeBlob: { read: true } },
...(credentialId && {
allowCredentials: [{ id: credentialId, type: "public-key" }],
}),
});
console.log("read blob json -", json);
const blob = json?.clientExtensionResults?.largeBlob?.blob;
if (blob) alert("This passkey has blob", base64UrlToString(blob));
setResult(json);
};
const deriveKey = async () => {
const json = await passkey.get({
rpId: rp.id,
challenge,
extensions: {
prf: { eval: { first: bufferToBase64URLString(utf8StringToBuffer("my derived key")) } },
},
...(credentialId && {
allowCredentials: [{ id: credentialId, type: "public-key" }],
}),
});
console.log("derive key json -", json);
setResult(json);
};
const deriveKeyByCredential = async () => {
if (!credentialId) {
alert("No credential", "Create a passkey first");
return;
}
// Example: derive different keys for different credentials
const json = await passkey.get({
rpId: rp.id,
challenge,
extensions: {
prf: {
evalByCredential: {
[credentialId]: {
first: bufferToBase64URLString(utf8StringToBuffer("credential-specific-key")),
},
},
},
},
allowCredentials: [{ id: credentialId, type: "public-key" }],
});
console.log("derive key by credential json -", json);
setResult(json);
};
const testExcludeCredentials = async () => {
if (!credentialId) {
alert("No credential", "Create a passkey first to test excludeCredentials");
return;
}
try {
// Attempt to create a new passkey with the existing credential in excludeCredentials
// This should fail with InvalidStateError
const json = await passkey.create({
...createOptions,
excludeCredentials: [{ id: credentialId, type: "public-key" }],
});
console.log("excludeCredentials test result -", json);
alert("Unexpected Success", "This should have failed with InvalidStateError");
setResult(json);
} catch (e) {
console.error("excludeCredentials error (expected) -", e);
alert("Expected Error (Issue #45)", JSON.stringify(e, null, 2));
}
};
return (
<View style={{ flex: 1 }}>
<ScrollView
style={{
flex: 1,
backgroundColor: "#fccefe",
}}
contentContainerStyle={[
styles.scrollContainer,
{ paddingTop: insets.top, paddingBottom: insets.bottom + 60 },
]}
>
<Text style={styles.title}>Testing Passkeys</Text>
<Text>Application ID: {Application.applicationId}</Text>
<Text>Passkeys are {passkey.isSupported() ? "supported" : "not supported"}</Text>
{credentialId && <Text>User Credential ID: {credentialId}</Text>}
<View style={styles.buttonContainer}>
<Pressable style={styles.button} onPress={createPasskey}>
<Text>Create</Text>
</Pressable>
<Pressable style={styles.button} onPress={authenticatePasskey}>
<Text>Authenticate</Text>
</Pressable>
<Pressable style={styles.button} onPress={testExcludeCredentials}>
<Text>Test excludeCredentials</Text>
</Pressable>
<Pressable style={styles.button} onPress={writeBlob}>
<Text>Add Blob</Text>
</Pressable>
<Pressable style={styles.button} onPress={readBlob}>
<Text>Read Blob</Text>
</Pressable>
<Pressable style={styles.button} onPress={deriveKey}>
<Text>Derive Key (PRF)</Text>
</Pressable>
<Pressable style={styles.button} onPress={deriveKeyByCredential}>
<Text>PRF evalByCredential</Text>
</Pressable>
{creationResponse && (
<Pressable
style={styles.button}
onPress={() => {
const publicKey = creationResponse.getPublicKey();
if (!publicKey) alert("No public key found");
else alert("Public Key", publicKey);
}}
>
<Text>Get PublicKey</Text>
</Pressable>
)}
</View>
{result && <Text style={styles.resultText}>Result {JSON.stringify(result, null, 2)}</Text>}
</ScrollView>
<Text
style={{
textAlign: "center",
position: "absolute",
bottom: insets.bottom + 16,
left: 0,
right: 0,
}}
>
Source available on{" "}
<Text
onPress={() => Linking.openURL("https://github.com/peterferguson/react-native-passkeys")}
style={{ textDecorationLine: "underline" }}
>
GitHub
</Text>
</Text>
</View>
);
}
const styles = StyleSheet.create({
scrollContainer: {
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
},
title: {
fontSize: 20,
fontWeight: "bold",
marginVertical: "5%",
},
resultText: {
maxWidth: "80%",
},
buttonContainer: {
padding: 24,
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
rowGap: 4,
justifyContent: "space-evenly",
},
button: {
backgroundColor: "#fff",
padding: 10,
borderWidth: 1,
borderRadius: 5,
width: "45%",
alignItems: "center",
justifyContent: "center",
textAlign: "center",
},
});