forked from ForgeRock/forgerock-javascript-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
657 lines (605 loc) · 22.8 KB
/
index.ts
File metadata and controls
657 lines (605 loc) · 22.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/*
* @forgerock/javascript-sdk
*
* index.ts
*
* Copyright (c) 2024 - 2025 Ping Identity Corporation. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import { CallbackType } from '../auth/enums';
import type HiddenValueCallback from '../fr-auth/callbacks/hidden-value-callback';
import type MetadataCallback from '../fr-auth/callbacks/metadata-callback';
import type FRStep from '../fr-auth/fr-step';
import { FRLogger } from '../util/logger';
import { WebAuthnOutcome, WebAuthnOutcomeType, WebAuthnStepType } from './enums';
import {
arrayBufferToString,
parseCredentials,
parsePubKeyArray,
parseRelyingPartyId,
} from './helpers';
import type {
AttestationType,
RelyingParty,
WebAuthnAuthenticationMetadata,
WebAuthnCallbacks,
WebAuthnRegistrationMetadata,
WebAuthnTextOutputRegistration,
} from './interfaces';
import type TextOutputCallback from '../fr-auth/callbacks/text-output-callback';
import { parseWebAuthnAuthenticateText, parseWebAuthnRegisterText } from './script-parser';
import { withTimeout } from '../util/timeout';
// <clientdata>::<attestation>::<publickeyCredential>::<DeviceName>
type OutcomeWithName<
ClientId extends string,
Attestation extends AttestationType,
PubKeyCred extends PublicKeyCredential,
Name = '',
> = Name extends infer P extends string
? `${ClientId}::${Attestation}::${PubKeyCred['id']}${P extends '' ? '' : `::${P}`}`
: never;
// JSON-based WebAuthn
type WebAuthnMetadata = WebAuthnAuthenticationMetadata | WebAuthnRegistrationMetadata;
// Script-based WebAuthn
type WebAuthnTextOutput = WebAuthnTextOutputRegistration;
const TWO_SECOND = 2000;
declare global {
interface Window {
PingWebAuthnAbortController: AbortController;
}
}
/**
* Utility for integrating a web browser's WebAuthn API.
*
* Example:
*
* ```js
* // Determine if a step is a WebAuthn step
* const stepType = FRWebAuthn.getWebAuthnStepType(step);
* if (stepType === WebAuthnStepType.Registration) {
* // Register a new device
* await FRWebAuthn.register(step);
* } else if (stepType === WebAuthnStepType.Authentication) {
* // Authenticate with a registered device
* await FRWebAuthn.authenticate(step);
* }
* ```
*
* Conditional mediation (Autofill) Support:
*
* ```js
* // Check if browser supports conditional mediation
* const supportsConditionalUI = await FRWebAuthn.isConditionalUISupported();
*
* if (supportsConditionalUI) {
* // The authenticate() method automatically handles conditional mediation
* // when the server indicates support via conditionalWebAuthn: true
* // in the metadata. No additional code changes needed.
* await FRWebAuthn.authenticate(step);
*
* // For conditional mediation to work in the browser, add autocomplete="webauthn"
* // to your username input field:
* // <input type="text" name="username" autocomplete="webauthn" />
* }
* ```
*/
abstract class FRWebAuthn {
/**
* Determines if the given step is a WebAuthn step.
*
* @param step The step to evaluate
* @return A WebAuthnStepType value
*/
public static getWebAuthnStepType(step: FRStep): WebAuthnStepType {
const outcomeCallback = this.getOutcomeCallback(step);
const metadataCallback = this.getMetadataCallback(step);
const textOutputCallback = this.getTextOutputCallback(step);
if (outcomeCallback && metadataCallback) {
const metadata = metadataCallback.getOutputValue('data') as {
pubKeyCredParams?: [];
};
if (metadata?.pubKeyCredParams) {
return WebAuthnStepType.Registration;
}
return WebAuthnStepType.Authentication;
} else if (outcomeCallback && textOutputCallback) {
const message = textOutputCallback.getMessage();
if (message.includes('pubKeyCredParams')) {
return WebAuthnStepType.Registration;
}
return WebAuthnStepType.Authentication;
} else {
return WebAuthnStepType.None;
}
}
/**
* Checks if the browser supports WebAuthn.
*
* @return boolean indicating if WebAuthn is available
*/
public static isWebAuthnSupported(): boolean {
return !!window.PublicKeyCredential;
}
/**
* Checks if the browser supports conditional mediation (autofill) for WebAuthn.
*
* @return Promise<boolean> indicating if conditional mediation is available
*/
public static async isConditionalMediationSupported(): Promise<boolean> {
if (!this.isWebAuthnSupported()) {
return false;
}
// Check if the browser supports conditional mediation
try {
return withTimeout(PublicKeyCredential.isConditionalMediationAvailable(), TWO_SECOND);
} catch {
FRLogger.warn('Conditional mediation check timed out');
}
return false;
}
/**
* Populates the step with the necessary authentication outcome.
* Automatically handles conditional mediation if indicated by the server metadata.
*
* @param step The step that contains WebAuthn authentication data
* @param optionsTransformer Augments the derived options with custom behaviour
* @return The populated step
*/
public static async authenticate(
step: FRStep,
optionsTransformer: (options: CredentialRequestOptions) => CredentialRequestOptions = (
options,
) => options,
): Promise<FRStep> {
const { hiddenCallback, metadataCallback, textOutputCallback } = this.getCallbacks(step);
if (hiddenCallback && (metadataCallback || textOutputCallback)) {
const options: CredentialRequestOptions = {};
try {
if (metadataCallback) {
const meta = metadataCallback.getOutputValue('data') as WebAuthnAuthenticationMetadata;
const mediation = meta.mediation as CredentialMediationRequirement;
if (mediation === 'conditional') {
const isConditionalMediationSupported = await this.isConditionalMediationSupported();
if (!isConditionalMediationSupported) {
const e = new Error(
'Conditional mediation was requested, but is not supported by this browser.',
);
e.name = WebAuthnOutcomeType.NotSupportedError;
throw e;
}
}
options.publicKey = this.createAuthenticationPublicKey(meta);
options.mediation = mediation;
} else if (textOutputCallback) {
const metadata = this.extractMetadata(textOutputCallback.getMessage());
if (metadata) {
options.publicKey = this.createAuthenticationPublicKey(
metadata as WebAuthnAuthenticationMetadata,
);
} else {
options.publicKey = parseWebAuthnAuthenticateText(textOutputCallback.getMessage());
}
} else {
throw new Error('No Credential found from Public Key');
}
const credential: PublicKeyCredential | null = await this.getAuthenticationCredential(
optionsTransformer(options),
);
const outcome: ReturnType<typeof this.getAuthenticationOutcome> =
this.getAuthenticationOutcome(credential);
if (metadataCallback) {
const meta = metadataCallback.getOutputValue('data') as WebAuthnAuthenticationMetadata;
if (meta?.supportsJsonResponse && credential && 'authenticatorAttachment' in credential) {
hiddenCallback.setInputValue(
JSON.stringify({
authenticatorAttachment: credential.authenticatorAttachment,
legacyData: outcome,
}),
);
return step;
}
}
hiddenCallback.setInputValue(outcome);
return step;
} catch (error) {
if (!(error instanceof Error)) throw error;
// NotSupportedError is a special case
if (error.name === WebAuthnOutcomeType.NotSupportedError) {
hiddenCallback.setInputValue(WebAuthnOutcome.Unsupported);
throw error;
}
hiddenCallback.setInputValue(`${WebAuthnOutcome.Error}::${error.name}:${error.message}`);
throw error;
}
} else {
const e = new Error('Incorrect callbacks for WebAuthn authentication');
e.name = WebAuthnOutcomeType.DataError;
hiddenCallback?.setInputValue(`${WebAuthnOutcome.Error}::${e.name}:${e.message}`);
throw e;
}
}
/**
* Populates the step with the necessary registration outcome.
*
* @param step The step that contains WebAuthn registration data
* @return The populated step
*/
// Can make this generic const in Typescript 5.0 > and the name itself will
// be inferred from the type so `typeof deviceName` will not just return string
// but the actual name of the deviceName passed in as a generic.
public static async register<T extends string = ''>(
step: FRStep,
deviceName?: T,
): Promise<FRStep> {
const { hiddenCallback, metadataCallback, textOutputCallback } = this.getCallbacks(step);
if (hiddenCallback && (metadataCallback || textOutputCallback)) {
let outcome: OutcomeWithName<string, AttestationType, PublicKeyCredential>;
let credential: PublicKeyCredential | null = null;
try {
let publicKey: PublicKeyCredentialRequestOptions;
if (metadataCallback) {
const meta = metadataCallback.getOutputValue('data') as WebAuthnRegistrationMetadata;
publicKey = this.createRegistrationPublicKey(meta);
credential = await this.getRegistrationCredential(
publicKey as PublicKeyCredentialCreationOptions,
);
outcome = this.getRegistrationOutcome(credential);
} else if (textOutputCallback) {
const metadata = this.extractMetadata(textOutputCallback.getMessage());
if (metadata) {
publicKey = this.createRegistrationPublicKey(metadata as WebAuthnRegistrationMetadata);
} else {
publicKey = parseWebAuthnRegisterText(textOutputCallback.getMessage());
}
credential = await this.getRegistrationCredential(
publicKey as PublicKeyCredentialCreationOptions,
);
outcome = this.getRegistrationOutcome(credential);
} else {
throw new Error('No Credential found from Public Key');
}
} catch (error) {
if (!(error instanceof Error)) throw error;
// NotSupportedError is a special case
if (error.name === WebAuthnOutcomeType.NotSupportedError) {
hiddenCallback.setInputValue(WebAuthnOutcome.Unsupported);
throw error;
}
hiddenCallback.setInputValue(`${WebAuthnOutcome.Error}::${error.name}:${error.message}`);
throw error;
}
if (metadataCallback) {
const meta = metadataCallback.getOutputValue('data') as WebAuthnAuthenticationMetadata;
if (meta?.supportsJsonResponse && credential && 'authenticatorAttachment' in credential) {
hiddenCallback.setInputValue(
JSON.stringify({
authenticatorAttachment: credential.authenticatorAttachment,
legacyData:
deviceName && deviceName.length > 0 ? `${outcome}::${deviceName}` : outcome,
}),
);
return step;
}
}
hiddenCallback.setInputValue(
deviceName && deviceName.length > 0 ? `${outcome}::${deviceName}` : outcome,
);
return step;
} else {
const e = new Error('Incorrect callbacks for WebAuthn registration');
e.name = WebAuthnOutcomeType.DataError;
hiddenCallback?.setInputValue(`${WebAuthnOutcome.Error}::${e.name}:${e.message}`);
throw e;
}
}
/**
* Returns an object containing the two WebAuthn callbacks.
*
* @param step The step that contains WebAuthn callbacks
* @return The WebAuthn callbacks
*/
public static getCallbacks(step: FRStep): WebAuthnCallbacks {
const hiddenCallback = this.getOutcomeCallback(step);
const metadataCallback = this.getMetadataCallback(step);
const textOutputCallback = this.getTextOutputCallback(step);
const returnObj: WebAuthnCallbacks = {
hiddenCallback,
};
if (metadataCallback) {
returnObj.metadataCallback = metadataCallback;
} else if (textOutputCallback) {
returnObj.textOutputCallback = textOutputCallback;
}
return returnObj;
}
/**
* Returns the WebAuthn metadata callback containing data to pass to the browser
* Web Authentication API.
*
* @param step The step that contains WebAuthn callbacks
* @return The metadata callback
*/
public static getMetadataCallback(step: FRStep): MetadataCallback | undefined {
return step.getCallbacksOfType<MetadataCallback>(CallbackType.MetadataCallback).find((x) => {
const cb = x.getOutputByName<WebAuthnMetadata | undefined>('data', undefined);
// eslint-disable-next-line no-prototype-builtins
return cb && cb.hasOwnProperty('relyingPartyId');
});
}
/**
* Returns the WebAuthn hidden value callback where the outcome should be populated.
*
* @param step The step that contains WebAuthn callbacks
* @return The hidden value callback
*/
public static getOutcomeCallback(step: FRStep): HiddenValueCallback | undefined {
return step
.getCallbacksOfType<HiddenValueCallback>(CallbackType.HiddenValueCallback)
.find((x) => x.getOutputByName<string>('id', '') === 'webAuthnOutcome');
}
/**
* Returns the WebAuthn metadata callback containing data to pass to the browser
* Web Authentication API.
*
* @param step The step that contains WebAuthn callbacks
* @return The metadata callback
*/
public static getTextOutputCallback(step: FRStep): TextOutputCallback | undefined {
return step
.getCallbacksOfType<TextOutputCallback>(CallbackType.TextOutputCallback)
.find((x) => {
const cb = x.getOutputByName<WebAuthnTextOutput | undefined>('message', undefined);
return cb && cb.includes('webAuthnOutcome');
});
}
/**
* Retrieves the credential from the browser Web Authentication API.
*
* @param options The options associated with the request
* @return The credential
*/
public static async getAuthenticationCredential(
options: CredentialRequestOptions,
): Promise<PublicKeyCredential | null> {
// Feature check before we attempt authenticating
if (!this.isWebAuthnSupported()) {
const e = new Error('PublicKeyCredential not supported by this browser');
e.name = WebAuthnOutcomeType.NotSupportedError;
throw e;
}
const credential = await navigator.credentials.get({
...options,
signal: this.createAbortController().signal,
});
return credential as PublicKeyCredential;
}
/**
* Converts an authentication credential into the outcome expected by OpenAM.
*
* @param credential The credential to convert
* @return The outcome string
*/
public static getAuthenticationOutcome(
credential: PublicKeyCredential | null,
):
| OutcomeWithName<string, AttestationType, PublicKeyCredential>
| OutcomeWithName<string, AttestationType, PublicKeyCredential, string> {
if (credential === null) {
const e = new Error('No credential generated from authentication');
e.name = WebAuthnOutcomeType.UnknownError;
throw e;
}
try {
const clientDataJSON = arrayBufferToString(credential.response.clientDataJSON);
const assertionResponse = credential.response as AuthenticatorAssertionResponse;
const authenticatorData = new Int8Array(
assertionResponse.authenticatorData,
).toString() as AttestationType;
const signature = new Int8Array(assertionResponse.signature).toString();
// Current native typing for PublicKeyCredential does not include `userHandle`
// eslint-disable-next-line
// @ts-ignore
const userHandle = arrayBufferToString(credential.response.userHandle);
let stringOutput =
`${clientDataJSON}::${authenticatorData}::${signature}::${credential.id}` as OutcomeWithName<
string,
AttestationType,
PublicKeyCredential
>;
// Check if Username is stored on device
if (userHandle) {
stringOutput = `${stringOutput}::${userHandle}`;
return stringOutput as OutcomeWithName<
string,
AttestationType,
PublicKeyCredential,
string
>;
}
return stringOutput;
} catch (error) {
const e = new Error('Transforming credential object to string failed');
e.name = WebAuthnOutcomeType.EncodingError;
throw e;
}
}
/**
* Retrieves the credential from the browser Web Authentication API.
*
* @param options The public key options associated with the request
* @return The credential
*/
public static async getRegistrationCredential(
options: PublicKeyCredentialCreationOptions,
): Promise<PublicKeyCredential | null> {
// Feature check before we attempt registering a device
if (!this.isWebAuthnSupported()) {
const e = new Error('PublicKeyCredential not supported by this browser');
e.name = WebAuthnOutcomeType.NotSupportedError;
throw e;
}
const credential = await navigator.credentials.create({
publicKey: options,
});
return credential as PublicKeyCredential;
}
/**
* Converts a registration credential into the outcome expected by OpenAM.
*
* @param credential The credential to convert
* @return The outcome string
*/
public static getRegistrationOutcome(
credential: PublicKeyCredential | null,
): OutcomeWithName<string, AttestationType, PublicKeyCredential> {
if (credential === null) {
const e = new Error('No credential generated from registration');
e.name = WebAuthnOutcomeType.UnknownError;
throw e;
}
try {
const clientDataJSON = arrayBufferToString(credential.response.clientDataJSON);
const attestationResponse = credential.response as AuthenticatorAttestationResponse;
const attestationObject = new Int8Array(
attestationResponse.attestationObject,
).toString() as AttestationType.Direct;
return `${clientDataJSON}::${attestationObject}::${credential.id}`;
} catch (error) {
const e = new Error('Transforming credential object to string failed');
e.name = WebAuthnOutcomeType.EncodingError;
throw e;
}
}
/**
* Converts authentication tree metadata into options required by the browser
* Web Authentication API.
*
* @param metadata The metadata provided in the authentication tree MetadataCallback
* @return The Web Authentication API request options
*/
public static createAuthenticationPublicKey(
metadata: WebAuthnAuthenticationMetadata,
): PublicKeyCredentialRequestOptions {
const {
acceptableCredentials,
allowCredentials,
_allowCredentials,
challenge,
relyingPartyId,
_relyingPartyId,
timeout,
userVerification,
extensions,
} = metadata;
// Use the structured _allowCredentials if available, otherwise parse the string format
let allowCredentialsValue: PublicKeyCredentialDescriptor[] | undefined;
if (_allowCredentials && Array.isArray(_allowCredentials)) {
// The incoming _allowCredentials entries have an `id` property of type `Array`, which is rejected by `navigator.credentials.get()`.
// Converting it to a TypedArray here to meet the spec (https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions#id).
allowCredentialsValue = _allowCredentials.map((cred) => {
return {
...cred,
id: new Int8Array(cred.id as unknown as number[]),
};
});
} else {
allowCredentialsValue = parseCredentials(allowCredentials || acceptableCredentials || '');
}
// Use _relyingPartyId if available, otherwise parse the old format
const rpId = _relyingPartyId || parseRelyingPartyId(relyingPartyId);
const options: PublicKeyCredentialRequestOptions = {
challenge: Uint8Array.from(atob(challenge), (c) => c.charCodeAt(0)).buffer,
timeout,
};
// For conditional mediation, allowCredentials can be omitted.
// For standard WebAuthn, it may or may not be present.
// Only add the property if the array is not empty.
if (allowCredentialsValue && allowCredentialsValue.length > 0) {
options.allowCredentials = allowCredentialsValue;
}
// Add optional properties only if they have values
if (userVerification) {
options.userVerification = userVerification;
}
if (rpId) {
options.rpId = rpId;
}
if (extensions && Object.keys(extensions).length > 0) {
options.extensions = extensions;
}
return options;
}
/**
* Converts authentication tree metadata into options required by the browser
* Web Authentication API.
*
* @param metadata The metadata provided in the authentication tree MetadataCallback
* @return The Web Authentication API request options
*/
public static createRegistrationPublicKey(
metadata: WebAuthnRegistrationMetadata,
): PublicKeyCredentialCreationOptions {
const { pubKeyCredParams: pubKeyCredParamsString } = metadata;
const pubKeyCredParams = parsePubKeyArray(pubKeyCredParamsString);
if (!pubKeyCredParams) {
const e = new Error('Missing pubKeyCredParams property from registration options');
e.name = WebAuthnOutcomeType.DataError;
throw e;
}
const excludeCredentials = parseCredentials(metadata.excludeCredentials);
const {
attestationPreference,
authenticatorSelection,
challenge,
relyingPartyId,
relyingPartyName,
timeout,
userId,
userName,
displayName,
} = metadata;
const rpId = parseRelyingPartyId(relyingPartyId);
const rp: RelyingParty = {
name: relyingPartyName,
...(rpId && { id: rpId }),
};
return {
attestation: attestationPreference,
authenticatorSelection: JSON.parse(authenticatorSelection),
challenge: Uint8Array.from(atob(challenge), (c) => c.charCodeAt(0)).buffer,
...(excludeCredentials.length && { excludeCredentials }),
pubKeyCredParams,
rp,
timeout,
user: {
displayName: displayName || userName,
id: Int8Array.from(userId.split('').map((c: string) => c.charCodeAt(0))),
name: displayName || userName,
},
};
}
private static createAbortController() {
window.PingWebAuthnAbortController?.abort();
const abortController = new AbortController();
window.PingWebAuthnAbortController = abortController;
return abortController;
}
private static extractMetadata(message: string): object | null {
const contextMatch = message.match(/^var scriptContext = (.*);*$/m);
const jsonString = contextMatch?.[1];
if (jsonString) {
return JSON.parse(jsonString);
}
return null;
}
}
export default FRWebAuthn;
export type {
RelyingParty,
WebAuthnAuthenticationMetadata,
WebAuthnCallbacks,
WebAuthnRegistrationMetadata,
};
export { WebAuthnOutcome, WebAuthnOutcomeType, WebAuthnStepType };