-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathWebAuthnService.ts
More file actions
348 lines (303 loc) · 10.8 KB
/
WebAuthnService.ts
File metadata and controls
348 lines (303 loc) · 10.8 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
348
/// <reference types="web-bluetooth" />
/// <reference types="user-agent-data-types" /> <- add this line
import type { ClientCapabilities } from '@corbado/types';
import { create, get } from '@corbado/webauthn-json';
import { createResponseToJSON, getResponseToJSON } from '@corbado/webauthn-json/extended';
import FingerprintJS from '@fingerprintjs/fingerprintjs';
import { detectIncognito } from 'detectincognitojs';
import log from 'loglevel';
import type { Result } from 'ts-results';
import { Err, Ok } from 'ts-results';
import type { ClientInformation, ClientStateMeta, JavaScriptHighEntropy } from '../api/v2';
import { ConnectError, ConnectErrorType, CorbadoError } from '../utils';
import type { ClientStateEntry } from './ClientStateService';
import { ClientStateService } from './ClientStateService';
export type ResponseWithMessage = {
response: string;
message?: string;
};
/**
* AuthenticatorService handles all interactions with webAuthn platform authenticators.
* Currently, this includes the creation of passkeys and the login with existing passkeys.
*/
export class WebAuthnService {
#abortController: AbortController | undefined;
#visitorId: string | undefined;
async createPasskey(serializedChallenge: string): Promise<Result<string, CorbadoError>> {
try {
const res = await this.createPasskeyRaw(serializedChallenge, false);
return Ok(res.response);
} catch (e) {
if (e instanceof DOMException) {
return Err(CorbadoError.fromDOMException(e));
} else {
return Err(CorbadoError.fromUnknownFrontendError(e));
}
}
}
async createPasskeyRaw(attestationOptions: string, conditional: boolean): Promise<ResponseWithMessage> {
const abortController = this.abortOngoingOperation();
const attestationOptionsJSON = JSON.parse(attestationOptions);
this.#abortController = abortController;
if (!PublicKeyCredential.parseCreationOptionsFromJSON) {
attestationOptionsJSON.signal = abortController.signal;
const signedChallenge = await create(attestationOptionsJSON);
return {
response: JSON.stringify(signedChallenge),
message: 'parseCreationOptionsFromJSON not available',
};
}
const publicKey = PublicKeyCredential.parseCreationOptionsFromJSON(attestationOptionsJSON.publicKey);
let credential: PublicKeyCredential;
if (conditional) {
const result = await WebAuthnService.raceWithTimeout(
navigator.credentials.create({
publicKey,
signal: abortController.signal,
mediation: 'conditional',
} as never),
5000,
);
credential = result as PublicKeyCredential;
} else {
credential = (await navigator.credentials.create({
publicKey,
signal: abortController.signal,
} as never)) as PublicKeyCredential;
}
try {
return {
response: JSON.stringify(credential.toJSON()),
message: '',
};
} catch (e) {
return {
response: JSON.stringify(createResponseToJSON(credential)),
message: 'toJSON() not available on PublicKeyCredential',
};
}
}
async login(
serializedChallenge: string,
conditional: boolean,
onConditionalLoginStart?: (ac: AbortController) => void,
): Promise<Result<string, CorbadoError>> {
try {
const res = await this.loginRaw(serializedChallenge, conditional, onConditionalLoginStart);
return Ok(res.response);
} catch (e) {
if (e instanceof DOMException) {
return Err(CorbadoError.fromDOMException(e));
} else {
return Err(CorbadoError.fromUnknownFrontendError(e));
}
}
}
async loginRaw(
assertionOptions: string,
conditional: boolean,
onConditionalLoginStart?: (ac: AbortController) => void,
): Promise<ResponseWithMessage> {
const abortController = this.abortOngoingOperation();
const assertionOptionsJSON = JSON.parse(assertionOptions);
this.#abortController = abortController;
onConditionalLoginStart?.(abortController);
if (!PublicKeyCredential.parseRequestOptionsFromJSON) {
const signedChallenge = await get(assertionOptionsJSON);
return {
response: JSON.stringify(signedChallenge),
message: 'parseRequestOptionsFromJSON not available',
};
}
const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON(assertionOptionsJSON.publicKey);
let mediation: CredentialMediationRequirement | undefined;
if (conditional) {
mediation = 'conditional';
}
const credential = (await navigator.credentials.get({
publicKey,
mediation,
signal: abortController.signal,
})) as PublicKeyCredential;
try {
return {
response: JSON.stringify(credential.toJSON()),
message: '',
};
} catch (e) {
return {
response: JSON.stringify(getResponseToJSON(credential)),
message: 'toJSON() not available on PublicKeyCredential',
};
}
}
async getClientInformation(maybeClientHandle: ClientStateEntry<string> | undefined): Promise<ClientInformation> {
const bluetoothAvailable = await WebAuthnService.canUseBluetooth();
const isUserVerifyingPlatformAuthenticatorAvailable = await WebAuthnService.doesBrowserSupportPasskeys();
const javaScriptHighEntropy = await WebAuthnService.getHighEntropyValues();
const canUseConditionalUI = await WebAuthnService.doesBrowserSupportConditionalUI();
// iOS & macOS Only so far
const clientCapabilities = await WebAuthnService.getClientCapabilities();
let currentVisitorId = this.#visitorId;
if (!currentVisitorId) {
const fpJS = await FingerprintJS.load();
const { visitorId } = await fpJS.get();
currentVisitorId = visitorId;
this.#visitorId = visitorId;
}
let clientEnvHandleMeta: ClientStateMeta | undefined = undefined;
if (maybeClientHandle) {
clientEnvHandleMeta = {
source: ClientStateService.parseClientStateSource(maybeClientHandle.source),
ts: maybeClientHandle.ts,
};
}
return {
bluetoothAvailable: bluetoothAvailable,
isUserVerifyingPlatformAuthenticatorAvailable: isUserVerifyingPlatformAuthenticatorAvailable,
isConditionalMediationAvailable: canUseConditionalUI,
clientEnvHandle: maybeClientHandle?.data,
visitorId: currentVisitorId,
javaScriptHighEntropy: javaScriptHighEntropy,
clientCapabilities,
webdriver: WebAuthnService.getWebdriver(),
privateMode: await WebAuthnService.isPrivateMode(),
clientEnvHandleMeta: clientEnvHandleMeta,
};
}
static async doesBrowserSupportPasskeys(): Promise<boolean | undefined> {
if (!PublicKeyCredential) {
return undefined;
}
try {
return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
} catch (e) {
log.debug('Error checking passkey availability', e);
return;
}
}
static async doesBrowserSupportConditionalUI(): Promise<boolean | undefined> {
if (!PublicKeyCredential) {
return undefined;
}
try {
return await PublicKeyCredential.isConditionalMediationAvailable();
} catch (e) {
log.debug('Error checking conditional UI availability', e);
return;
}
}
static async isPrivateMode(): Promise<boolean | undefined> {
try {
const res = await detectIncognito();
return res.isPrivate;
} catch (e) {
return;
}
}
static async canUseBluetooth(): Promise<boolean | undefined> {
try {
return await navigator.bluetooth.getAvailability();
} catch (e) {
// When using Safari and Firefox navigator.bluetooth returns undefined => we will return undefined
log.debug('Error checking bluetooth availability', e);
return;
}
}
static getWebdriver(): boolean {
try {
return navigator.webdriver;
} catch (e) {
return false;
}
}
static async getHighEntropyValues(): Promise<JavaScriptHighEntropy | undefined> {
try {
if (!navigator.userAgentData) {
return;
}
const ua = await navigator.userAgentData.getHighEntropyValues(['platformVersion']);
const platform = ua.platform;
const mobile = ua.mobile;
const platformVersion = ua.platformVersion;
if (!platform || mobile === undefined || !platformVersion) {
return;
}
return {
platform,
mobile,
platformVersion,
};
} catch (e) {
return;
}
}
public abortOngoingOperation(): AbortController {
if (this.#abortController) {
this.#abortController.abort();
}
return new AbortController();
}
static async getClientCapabilities(): Promise<ClientCapabilities | undefined> {
if (!PublicKeyCredential) {
log.debug('PublicKeyCredential is not supported on this browser');
return;
}
try {
// We will ignore the type check as getClientCapabilities does not exist in the stable authn version and types
// @ts-ignore
return await PublicKeyCredential.getClientCapabilities();
} catch (e) {
log.debug('Error using getClientCapabilities: ', e);
return;
}
}
static challengeFromAttestationOptions(attestationOptions: string): string {
const typed = JSON.parse(attestationOptions);
return typed.publicKey.challenge;
}
static challengeFromAssertionOptions(assertionOptions: string): string | undefined {
const typed = JSON.parse(assertionOptions);
return typed.publicKey?.challenge;
}
static async signalAllAcceptedCredentials(rpId: string, userId: string, credentialIds: string[]): Promise<void> {
// @ts-ignore
if (!PublicKeyCredential || !PublicKeyCredential.signalAllAcceptedCredentials) {
return undefined;
}
try {
// @ts-ignore
const p1 = PublicKeyCredential.signalAllAcceptedCredentials({
rpId: rpId,
userId: userId,
allAcceptedCredentialIds: credentialIds,
});
await WebAuthnService.raceWithTimeout(p1, 2000);
} catch (e) {
log.debug('Error calling signalAllAcceptedCredentials', e);
return;
}
}
static async signalUnknownCredential(rpId: string, credentialId: string): Promise<void> {
// @ts-ignore
if (!PublicKeyCredential || !PublicKeyCredential.signalUnknownCredential) {
return undefined;
}
try {
// @ts-ignore
await PublicKeyCredential.signalUnknownCredential({
rpId: rpId,
credentialId: credentialId,
});
} catch (e) {
log.debug('Error calling signalUnknownCredential', e);
return;
}
}
static async raceWithTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new ConnectError(ConnectErrorType.RaceTimeout, `timeout of ${ms}ms reached`)), ms),
);
return Promise.race<T>([p, timeout]);
}
}