diff options
24 files changed, 512 insertions, 426 deletions
diff --git a/packages/browser/src/helpers/__jest__/generateCustomError.ts b/packages/browser/src/helpers/__jest__/generateCustomError.ts index 55f6acf..3c0a817 100644 --- a/packages/browser/src/helpers/__jest__/generateCustomError.ts +++ b/packages/browser/src/helpers/__jest__/generateCustomError.ts @@ -2,15 +2,18 @@ * Create "custom errors" to help emulate WebAuthn API errors */ type WebAuthnErrorName = - | 'AbortError' - | 'ConstraintError' - | 'InvalidStateError' - | 'NotAllowedError' - | 'NotSupportedError' - | 'SecurityError' - | 'UnknownError'; + | "AbortError" + | "ConstraintError" + | "InvalidStateError" + | "NotAllowedError" + | "NotSupportedError" + | "SecurityError" + | "UnknownError"; -export function generateCustomError(name: WebAuthnErrorName, message = ''): Error { +export function generateCustomError( + name: WebAuthnErrorName, + message = "", +): Error { const customError = new Error(); customError.name = name; customError.message = message; diff --git a/packages/browser/src/helpers/base64URLStringToBuffer.ts b/packages/browser/src/helpers/base64URLStringToBuffer.ts index f30b3d5..db78b35 100644 --- a/packages/browser/src/helpers/base64URLStringToBuffer.ts +++ b/packages/browser/src/helpers/base64URLStringToBuffer.ts @@ -7,7 +7,7 @@ */ export function base64URLStringToBuffer(base64URLString: string): ArrayBuffer { // Convert from Base64URL to Base64 - const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/'); + const base64 = base64URLString.replace(/-/g, "+").replace(/_/g, "/"); /** * Pad with '=' until it's a multiple of four * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding @@ -16,7 +16,7 @@ export function base64URLStringToBuffer(base64URLString: string): ArrayBuffer { * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding */ const padLength = (4 - (base64.length % 4)) % 4; - const padded = base64.padEnd(base64.length + padLength, '='); + const padded = base64.padEnd(base64.length + padLength, "="); // Convert to a binary string const binary = atob(padded); diff --git a/packages/browser/src/helpers/browserSupportsWebAuthn.test.ts b/packages/browser/src/helpers/browserSupportsWebAuthn.test.ts index 20d96c2..195f089 100644 --- a/packages/browser/src/helpers/browserSupportsWebAuthn.test.ts +++ b/packages/browser/src/helpers/browserSupportsWebAuthn.test.ts @@ -1,22 +1,22 @@ -import { browserSupportsWebAuthn } from './browserSupportsWebAuthn'; +import { browserSupportsWebAuthn } from "./browserSupportsWebAuthn"; beforeEach(() => { // @ts-ignore 2741 window.PublicKeyCredential = jest.fn().mockReturnValue(() => {}); }); -test('should return true when browser supports WebAuthn', () => { +test("should return true when browser supports WebAuthn", () => { expect(browserSupportsWebAuthn()).toBe(true); }); -test('should return false when browser does not support WebAuthn', () => { +test("should return false when browser does not support WebAuthn", () => { delete (window as any).PublicKeyCredential; expect(browserSupportsWebAuthn()).toBe(false); }); -test('should return false when window is undefined', () => { +test("should return false when window is undefined", () => { // Make window undefined as it is in node environments. - const windowSpy = jest.spyOn<any, 'window'>(global, 'window', 'get'); + const windowSpy = jest.spyOn<any, "window">(global, "window", "get"); windowSpy.mockImplementation(() => undefined); expect(window).toBe(undefined); diff --git a/packages/browser/src/helpers/browserSupportsWebAuthn.ts b/packages/browser/src/helpers/browserSupportsWebAuthn.ts index 79fe673..02b3c43 100644 --- a/packages/browser/src/helpers/browserSupportsWebAuthn.ts +++ b/packages/browser/src/helpers/browserSupportsWebAuthn.ts @@ -3,6 +3,7 @@ */ export function browserSupportsWebAuthn(): boolean { return ( - window?.PublicKeyCredential !== undefined && typeof window.PublicKeyCredential === 'function' + window?.PublicKeyCredential !== undefined && + typeof window.PublicKeyCredential === "function" ); } diff --git a/packages/browser/src/helpers/browserSupportsWebAuthnAutofill.ts b/packages/browser/src/helpers/browserSupportsWebAuthnAutofill.ts index afc1176..b3b1e86 100644 --- a/packages/browser/src/helpers/browserSupportsWebAuthnAutofill.ts +++ b/packages/browser/src/helpers/browserSupportsWebAuthnAutofill.ts @@ -1,4 +1,4 @@ -import { PublicKeyCredentialFuture } from '@simplewebauthn/typescript-types'; +import { PublicKeyCredentialFuture } from "@simplewebauthn/typescript-types"; /** * Determine if the browser supports conditional UI, so that WebAuthn credentials can @@ -11,8 +11,8 @@ export async function browserSupportsWebAuthnAutofill(): Promise<boolean> { * want. I think I'm fine with this for now since it's _supposed_ to be temporary, until TS types * have a chance to catch up. */ - const globalPublicKeyCredential = - window.PublicKeyCredential as unknown as PublicKeyCredentialFuture; + const globalPublicKeyCredential = window + .PublicKeyCredential as unknown as PublicKeyCredentialFuture; return ( globalPublicKeyCredential.isConditionalMediationAvailable !== undefined && diff --git a/packages/browser/src/helpers/bufferToBase64URLString.ts b/packages/browser/src/helpers/bufferToBase64URLString.ts index 6a40cbb..0bd29b5 100644 --- a/packages/browser/src/helpers/bufferToBase64URLString.ts +++ b/packages/browser/src/helpers/bufferToBase64URLString.ts @@ -6,7 +6,7 @@ */ export function bufferToBase64URLString(buffer: ArrayBuffer): string { const bytes = new Uint8Array(buffer); - let str = ''; + let str = ""; for (const charCode of bytes) { str += String.fromCharCode(charCode); @@ -14,5 +14,5 @@ export function bufferToBase64URLString(buffer: ArrayBuffer): string { const base64String = btoa(str); - return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); + return base64String.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } diff --git a/packages/browser/src/helpers/bufferToUTF8String.ts b/packages/browser/src/helpers/bufferToUTF8String.ts index 0da3246..8a6c3b9 100644 --- a/packages/browser/src/helpers/bufferToUTF8String.ts +++ b/packages/browser/src/helpers/bufferToUTF8String.ts @@ -3,5 +3,5 @@ * string. */ export function bufferToUTF8String(value: ArrayBuffer): string { - return new TextDecoder('utf-8').decode(value); + return new TextDecoder("utf-8").decode(value); } diff --git a/packages/browser/src/helpers/identifyAuthenticationError.ts b/packages/browser/src/helpers/identifyAuthenticationError.ts index d8d6960..3d84ce2 100644 --- a/packages/browser/src/helpers/identifyAuthenticationError.ts +++ b/packages/browser/src/helpers/identifyAuthenticationError.ts @@ -1,5 +1,5 @@ -import { isValidDomain } from './isValidDomain'; -import { WebAuthnError } from './webAuthnError'; +import { isValidDomain } from "./isValidDomain"; +import { WebAuthnError } from "./webAuthnError"; /** * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()` @@ -14,51 +14,52 @@ export function identifyAuthenticationError({ const { publicKey } = options; if (!publicKey) { - throw Error('options was missing required publicKey property'); + throw Error("options was missing required publicKey property"); } - if (error.name === 'AbortError') { + if (error.name === "AbortError") { if (options.signal instanceof AbortSignal) { // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) return new WebAuthnError({ - message: 'Authentication ceremony was sent an abort signal', - code: 'ERROR_CEREMONY_ABORTED', + message: "Authentication ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", cause: error, }); } - } else if (error.name === 'NotAllowedError') { + } else if (error.name === "NotAllowedError") { /** * Pass the error directly through. Platforms are overloading this error beyond what the spec * defines and we don't want to overwrite potentially useful error messages. */ return new WebAuthnError({ message: error.message, - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", cause: error, }); - } else if (error.name === 'SecurityError') { + } else if (error.name === "SecurityError") { const effectiveDomain = window.location.hostname; if (!isValidDomain(effectiveDomain)) { // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) return new WebAuthnError({ message: `${window.location.hostname} is an invalid domain`, - code: 'ERROR_INVALID_DOMAIN', + code: "ERROR_INVALID_DOMAIN", cause: error, }); } else if (publicKey.rpId !== effectiveDomain) { // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) return new WebAuthnError({ message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, - code: 'ERROR_INVALID_RP_ID', + code: "ERROR_INVALID_RP_ID", cause: error, }); } - } else if (error.name === 'UnknownError') { + } else if (error.name === "UnknownError") { // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) return new WebAuthnError({ - message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature', - code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + message: + "The authenticator was unable to process the specified options, or could not create a new assertion signature", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", cause: error, }); } diff --git a/packages/browser/src/helpers/identifyRegistrationError.ts b/packages/browser/src/helpers/identifyRegistrationError.ts index 02c9dac..d0def65 100644 --- a/packages/browser/src/helpers/identifyRegistrationError.ts +++ b/packages/browser/src/helpers/identifyRegistrationError.ts @@ -1,5 +1,5 @@ -import { isValidDomain } from './isValidDomain'; -import { WebAuthnError } from './webAuthnError'; +import { isValidDomain } from "./isValidDomain"; +import { WebAuthnError } from "./webAuthnError"; /** * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()` @@ -14,104 +14,110 @@ export function identifyRegistrationError({ const { publicKey } = options; if (!publicKey) { - throw Error('options was missing required publicKey property'); + throw Error("options was missing required publicKey property"); } - if (error.name === 'AbortError') { + if (error.name === "AbortError") { if (options.signal instanceof AbortSignal) { // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) return new WebAuthnError({ - message: 'Registration ceremony was sent an abort signal', - code: 'ERROR_CEREMONY_ABORTED', + message: "Registration ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", cause: error, }); } - } else if (error.name === 'ConstraintError') { + } else if (error.name === "ConstraintError") { if (publicKey.authenticatorSelection?.requireResidentKey === true) { // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) return new WebAuthnError({ - message: 'Discoverable credentials were required but no available authenticator supported it', - code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', + message: + "Discoverable credentials were required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT", cause: error, }); - } else if (publicKey.authenticatorSelection?.userVerification === 'required') { + } else if ( + publicKey.authenticatorSelection?.userVerification === "required" + ) { // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) return new WebAuthnError({ - message: 'User verification was required but no available authenticator supported it', - code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', + message: + "User verification was required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT", cause: error, }); } - } else if (error.name === 'InvalidStateError') { + } else if (error.name === "InvalidStateError") { // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) return new WebAuthnError({ - message: 'The authenticator was previously registered', - code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', - cause: error + message: "The authenticator was previously registered", + code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", + cause: error, }); - } else if (error.name === 'NotAllowedError') { + } else if (error.name === "NotAllowedError") { /** * Pass the error directly through. Platforms are overloading this error beyond what the spec * defines and we don't want to overwrite potentially useful error messages. */ return new WebAuthnError({ message: error.message, - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", cause: error, }); - } else if (error.name === 'NotSupportedError') { + } else if (error.name === "NotSupportedError") { const validPubKeyCredParams = publicKey.pubKeyCredParams.filter( - param => param.type === 'public-key', + (param) => param.type === "public-key", ); if (validPubKeyCredParams.length === 0) { // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) return new WebAuthnError({ message: 'No entry in pubKeyCredParams was of type "public-key"', - code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', + code: "ERROR_MALFORMED_PUBKEYCREDPARAMS", cause: error, }); } // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) return new WebAuthnError({ - message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms', - code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', + message: + "No available authenticator supported any of the specified pubKeyCredParams algorithms", + code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG", cause: error, }); - } else if (error.name === 'SecurityError') { + } else if (error.name === "SecurityError") { const effectiveDomain = window.location.hostname; if (!isValidDomain(effectiveDomain)) { // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) return new WebAuthnError({ message: `${window.location.hostname} is an invalid domain`, - code: 'ERROR_INVALID_DOMAIN', - cause: error + code: "ERROR_INVALID_DOMAIN", + cause: error, }); } else if (publicKey.rp.id !== effectiveDomain) { // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) return new WebAuthnError({ message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, - code: 'ERROR_INVALID_RP_ID', + code: "ERROR_INVALID_RP_ID", cause: error, }); } - } else if (error.name === 'TypeError') { + } else if (error.name === "TypeError") { if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) return new WebAuthnError({ - message: 'User ID was not between 1 and 64 characters', - code: 'ERROR_INVALID_USER_ID_LENGTH', + message: "User ID was not between 1 and 64 characters", + code: "ERROR_INVALID_USER_ID_LENGTH", cause: error, }); } - } else if (error.name === 'UnknownError') { + } else if (error.name === "UnknownError") { // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) return new WebAuthnError({ - message: 'The authenticator was unable to process the specified options, or could not create a new credential', - code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + message: + "The authenticator was unable to process the specified options, or could not create a new credential", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", cause: error, }); } diff --git a/packages/browser/src/helpers/isValidDomain.ts b/packages/browser/src/helpers/isValidDomain.ts index 4d2eedd..3e1ad10 100644 --- a/packages/browser/src/helpers/isValidDomain.ts +++ b/packages/browser/src/helpers/isValidDomain.ts @@ -9,6 +9,7 @@ export function isValidDomain(hostname: string): boolean { return ( // Consider localhost valid as well since it's okay wrt Secure Contexts - hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname) + hostname === "localhost" || + /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname) ); } diff --git a/packages/browser/src/helpers/platformAuthenticatorIsAvailable.test.ts b/packages/browser/src/helpers/platformAuthenticatorIsAvailable.test.ts index 3e0b65b..3024420 100644 --- a/packages/browser/src/helpers/platformAuthenticatorIsAvailable.test.ts +++ b/packages/browser/src/helpers/platformAuthenticatorIsAvailable.test.ts @@ -1,4 +1,4 @@ -import { platformAuthenticatorIsAvailable } from './platformAuthenticatorIsAvailable'; +import { platformAuthenticatorIsAvailable } from "./platformAuthenticatorIsAvailable"; const mockIsUVPAA = jest.fn(); @@ -11,13 +11,13 @@ beforeEach(() => { mockIsUVPAA.mockResolvedValue(true); }); -test('should return true when platform authenticator is available', async () => { +test("should return true when platform authenticator is available", async () => { const isAvailable = await platformAuthenticatorIsAvailable(); expect(isAvailable).toEqual(true); }); -test('should return false when platform authenticator is unavailable', async () => { +test("should return false when platform authenticator is unavailable", async () => { mockIsUVPAA.mockResolvedValue(false); const isAvailable = await platformAuthenticatorIsAvailable(); @@ -25,7 +25,7 @@ test('should return false when platform authenticator is unavailable', async () expect(isAvailable).toEqual(false); }); -test('should return false when browser does not support WebAuthn', async () => { +test("should return false when browser does not support WebAuthn", async () => { delete (window as any).PublicKeyCredential; const isAvailable = await platformAuthenticatorIsAvailable(); diff --git a/packages/browser/src/helpers/platformAuthenticatorIsAvailable.ts b/packages/browser/src/helpers/platformAuthenticatorIsAvailable.ts index 7dc1505..319825b 100644 --- a/packages/browser/src/helpers/platformAuthenticatorIsAvailable.ts +++ b/packages/browser/src/helpers/platformAuthenticatorIsAvailable.ts @@ -1,4 +1,4 @@ -import { browserSupportsWebAuthn } from './browserSupportsWebAuthn'; +import { browserSupportsWebAuthn } from "./browserSupportsWebAuthn"; /** * Determine whether the browser can communicate with a built-in authenticator, like diff --git a/packages/browser/src/helpers/toAuthenticatorAttachment.ts b/packages/browser/src/helpers/toAuthenticatorAttachment.ts index 366cf8f..99319fb 100644 --- a/packages/browser/src/helpers/toAuthenticatorAttachment.ts +++ b/packages/browser/src/helpers/toAuthenticatorAttachment.ts @@ -1,6 +1,6 @@ -import { AuthenticatorAttachment } from '@simplewebauthn/typescript-types'; +import { AuthenticatorAttachment } from "@simplewebauthn/typescript-types"; -const attachments: AuthenticatorAttachment[] = ['cross-platform', 'platform']; +const attachments: AuthenticatorAttachment[] = ["cross-platform", "platform"]; /** * If possible coerce a `string` value into a known `AuthenticatorAttachment` diff --git a/packages/browser/src/helpers/toPublicKeyCredentialDescriptor.ts b/packages/browser/src/helpers/toPublicKeyCredentialDescriptor.ts index e4c34a2..258efe2 100644 --- a/packages/browser/src/helpers/toPublicKeyCredentialDescriptor.ts +++ b/packages/browser/src/helpers/toPublicKeyCredentialDescriptor.ts @@ -1,6 +1,6 @@ -import type { PublicKeyCredentialDescriptorJSON } from '@simplewebauthn/typescript-types'; +import type { PublicKeyCredentialDescriptorJSON } from "@simplewebauthn/typescript-types"; -import { base64URLStringToBuffer } from './base64URLStringToBuffer'; +import { base64URLStringToBuffer } from "./base64URLStringToBuffer"; export function toPublicKeyCredentialDescriptor( descriptor: PublicKeyCredentialDescriptorJSON, diff --git a/packages/browser/src/helpers/webAuthnAbortService.test.ts b/packages/browser/src/helpers/webAuthnAbortService.test.ts index 98c1ccd..c1607e6 100644 --- a/packages/browser/src/helpers/webAuthnAbortService.test.ts +++ b/packages/browser/src/helpers/webAuthnAbortService.test.ts @@ -1,13 +1,13 @@ -import { webauthnAbortService } from './webAuthnAbortService'; +import { webauthnAbortService } from "./webAuthnAbortService"; -test('should create a new abort signal every time', () => { +test("should create a new abort signal every time", () => { const signal1 = webauthnAbortService.createNewAbortSignal(); const signal2 = webauthnAbortService.createNewAbortSignal(); expect(signal2).not.toBe(signal1); }); -test('should call abort() with AbortError on existing controller when creating a new signal', () => { +test("should call abort() with AbortError on existing controller when creating a new signal", () => { // Populate `.controller` webauthnAbortService.createNewAbortSignal(); @@ -23,5 +23,5 @@ test('should call abort() with AbortError on existing controller when creating a // Make sure we raise an AbortError so it can be detected correctly const abortReason = abortSpy.mock.calls[0][0]; expect(abortReason).toBeInstanceOf(Error); - expect(abortReason.name).toEqual('AbortError'); + expect(abortReason.name).toEqual("AbortError"); }); diff --git a/packages/browser/src/helpers/webAuthnAbortService.ts b/packages/browser/src/helpers/webAuthnAbortService.ts index f90b263..eb0e9be 100644 --- a/packages/browser/src/helpers/webAuthnAbortService.ts +++ b/packages/browser/src/helpers/webAuthnAbortService.ts @@ -12,8 +12,10 @@ class WebAuthnAbortService { createNewAbortSignal() { // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() if (this.controller) { - const abortError = new Error('Cancelling existing WebAuthn API call for new one'); - abortError.name = 'AbortError'; + const abortError = new Error( + "Cancelling existing WebAuthn API call for new one", + ); + abortError.name = "AbortError"; this.controller.abort(abortError); } diff --git a/packages/browser/src/helpers/webAuthnError.ts b/packages/browser/src/helpers/webAuthnError.ts index 1debec0..968c05b 100644 --- a/packages/browser/src/helpers/webAuthnError.ts +++ b/packages/browser/src/helpers/webAuthnError.ts @@ -25,32 +25,31 @@ export class WebAuthnError extends Error { cause, name, }: { - message: string, - code: WebAuthnErrorCode, - cause: Error, - name?: string, + message: string; + code: WebAuthnErrorCode; + cause: Error; + name?: string; }) { /** * `cause` is supported in evergreen browsers, but not IE10, so this ts-ignore is to * help Rollup complete the ES5 build. */ // @ts-ignore - super(message, { cause }) + super(message, { cause }); this.name = name ?? cause.name; this.code = code; } } export type WebAuthnErrorCode = - 'ERROR_CEREMONY_ABORTED' - | 'ERROR_INVALID_DOMAIN' - | 'ERROR_INVALID_RP_ID' - | 'ERROR_INVALID_USER_ID_LENGTH' - | 'ERROR_MALFORMED_PUBKEYCREDPARAMS' - | 'ERROR_AUTHENTICATOR_GENERAL_ERROR' - | 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT' - | 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT' - | 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED' - | 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG' - | 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY' - ; + | "ERROR_CEREMONY_ABORTED" + | "ERROR_INVALID_DOMAIN" + | "ERROR_INVALID_RP_ID" + | "ERROR_INVALID_USER_ID_LENGTH" + | "ERROR_MALFORMED_PUBKEYCREDPARAMS" + | "ERROR_AUTHENTICATOR_GENERAL_ERROR" + | "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT" + | "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT" + | "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED" + | "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG" + | "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY"; diff --git a/packages/browser/src/index.test.ts b/packages/browser/src/index.test.ts index 945ea1a..ee659d2 100644 --- a/packages/browser/src/index.test.ts +++ b/packages/browser/src/index.test.ts @@ -1,17 +1,17 @@ -import * as index from './index'; +import * as index from "./index"; -test('should export method `startRegistration`', () => { +test("should export method `startRegistration`", () => { expect(index.startRegistration).toBeDefined(); }); -test('should export method `startAuthentication`', () => { +test("should export method `startAuthentication`", () => { expect(index.startAuthentication).toBeDefined(); }); -test('should export method `browserSupportsWebAuthn`', () => { +test("should export method `browserSupportsWebAuthn`", () => { expect(index.browserSupportsWebAuthn).toBeDefined(); }); -test('should export method `platformAuthenticatorIsAvailable`', () => { +test("should export method `platformAuthenticatorIsAvailable`", () => { expect(index.browserSupportsWebAuthn).toBeDefined(); }); diff --git a/packages/browser/src/index.ts b/packages/browser/src/index.ts index 67c7c74..7fe2c4b 100644 --- a/packages/browser/src/index.ts +++ b/packages/browser/src/index.ts @@ -2,18 +2,18 @@ * @packageDocumentation * @module @simplewebauthn/browser */ -import { startRegistration } from './methods/startRegistration'; -import { startAuthentication } from './methods/startAuthentication'; -import { browserSupportsWebAuthn } from './helpers/browserSupportsWebAuthn'; -import { platformAuthenticatorIsAvailable } from './helpers/platformAuthenticatorIsAvailable'; -import { browserSupportsWebAuthnAutofill } from './helpers/browserSupportsWebAuthnAutofill'; +import { startRegistration } from "./methods/startRegistration"; +import { startAuthentication } from "./methods/startAuthentication"; +import { browserSupportsWebAuthn } from "./helpers/browserSupportsWebAuthn"; +import { platformAuthenticatorIsAvailable } from "./helpers/platformAuthenticatorIsAvailable"; +import { browserSupportsWebAuthnAutofill } from "./helpers/browserSupportsWebAuthnAutofill"; export { - startRegistration, - startAuthentication, browserSupportsWebAuthn, browserSupportsWebAuthnAutofill, platformAuthenticatorIsAvailable, + startAuthentication, + startRegistration, }; -export type { WebAuthnErrorCode } from './helpers/webAuthnError'; +export type { WebAuthnErrorCode } from "./helpers/webAuthnError"; diff --git a/packages/browser/src/methods/startAuthentication.test.ts b/packages/browser/src/methods/startAuthentication.test.ts index f8830ae..62f3061 100644 --- a/packages/browser/src/methods/startAuthentication.test.ts +++ b/packages/browser/src/methods/startAuthentication.test.ts @@ -1,40 +1,41 @@ import { AuthenticationCredential, - PublicKeyCredentialRequestOptionsJSON, AuthenticationExtensionsClientInputs, AuthenticationExtensionsClientOutputs, -} from '@simplewebauthn/typescript-types'; + PublicKeyCredentialRequestOptionsJSON, +} from "@simplewebauthn/typescript-types"; -import { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn'; -import { browserSupportsWebAuthnAutofill } from '../helpers/browserSupportsWebAuthnAutofill'; -import { utf8StringToBuffer } from '../helpers/utf8StringToBuffer'; -import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString'; -import { WebAuthnError } from '../helpers/webAuthnError'; -import { generateCustomError } from '../helpers/__jest__/generateCustomError'; -import { webauthnAbortService } from '../helpers/webAuthnAbortService'; +import { browserSupportsWebAuthn } from "../helpers/browserSupportsWebAuthn"; +import { browserSupportsWebAuthnAutofill } from "../helpers/browserSupportsWebAuthnAutofill"; +import { utf8StringToBuffer } from "../helpers/utf8StringToBuffer"; +import { bufferToBase64URLString } from "../helpers/bufferToBase64URLString"; +import { WebAuthnError } from "../helpers/webAuthnError"; +import { generateCustomError } from "../helpers/__jest__/generateCustomError"; +import { webauthnAbortService } from "../helpers/webAuthnAbortService"; -import { startAuthentication } from './startAuthentication'; +import { startAuthentication } from "./startAuthentication"; -jest.mock('../helpers/browserSupportsWebAuthn'); -jest.mock('../helpers/browserSupportsWebAuthnAutofill'); +jest.mock("../helpers/browserSupportsWebAuthn"); +jest.mock("../helpers/browserSupportsWebAuthnAutofill"); const mockNavigatorGet = window.navigator.credentials.get as jest.Mock; const mockSupportsWebAuthn = browserSupportsWebAuthn as jest.Mock; const mockSupportsAutofill = browserSupportsWebAuthnAutofill as jest.Mock; -const mockAuthenticatorData = 'mockAuthenticatorData'; -const mockClientDataJSON = 'mockClientDataJSON'; -const mockSignature = 'mockSignature'; -const mockUserHandle = 'mockUserHandle'; +const mockAuthenticatorData = "mockAuthenticatorData"; +const mockClientDataJSON = "mockClientDataJSON"; +const mockSignature = "mockSignature"; +const mockUserHandle = "mockUserHandle"; // With ASCII challenge const goodOpts1: PublicKeyCredentialRequestOptionsJSON = { - challenge: bufferToBase64URLString(utf8StringToBuffer('fizz')), + challenge: bufferToBase64URLString(utf8StringToBuffer("fizz")), allowCredentials: [ { - id: 'C0VGlvYFratUdAV1iCw-ULpUW8E-exHPXQChBfyVeJZCMfjMFcwDmOFgoMUz39LoMtCJUBW8WPlLkGT6q8qTCg', - type: 'public-key', - transports: ['nfc'], + id: + "C0VGlvYFratUdAV1iCw-ULpUW8E-exHPXQChBfyVeJZCMfjMFcwDmOFgoMUz39LoMtCJUBW8WPlLkGT6q8qTCg", + type: "public-key", + transports: ["nfc"], }, ], timeout: 1, @@ -42,7 +43,7 @@ const goodOpts1: PublicKeyCredentialRequestOptionsJSON = { // With UTF-8 challenge const goodOpts2UTF8: PublicKeyCredentialRequestOptionsJSON = { - challenge: bufferToBase64URLString(utf8StringToBuffer('やれやれだぜ')), + challenge: bufferToBase64URLString(utf8StringToBuffer("やれやれだぜ")), allowCredentials: [], timeout: 1, }; @@ -50,7 +51,7 @@ const goodOpts2UTF8: PublicKeyCredentialRequestOptionsJSON = { beforeEach(() => { // Stub out a response so the method won't throw mockNavigatorGet.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: {}, getClientExtensionResults: () => ({}), @@ -72,102 +73,125 @@ afterEach(() => { mockSupportsAutofill.mockReset(); }); -test('should convert options before passing to navigator.credentials.get(...)', async () => { +test("should convert options before passing to navigator.credentials.get(...)", async () => { await startAuthentication(goodOpts1); const argsPublicKey = mockNavigatorGet.mock.calls[0][0].publicKey; const credId = argsPublicKey.allowCredentials[0].id; - expect(new Uint8Array(argsPublicKey.challenge)).toEqual(new Uint8Array([102, 105, 122, 122])); + expect(new Uint8Array(argsPublicKey.challenge)).toEqual( + new Uint8Array([102, 105, 122, 122]), + ); // Make sure the credential ID is an ArrayBuffer with a length of 64 expect(credId instanceof ArrayBuffer).toEqual(true); expect(credId.byteLength).toEqual(64); }); -test('should support optional allowCredential', async () => { +test("should support optional allowCredential", async () => { await startAuthentication({ - challenge: bufferToBase64URLString(utf8StringToBuffer('fizz')), + challenge: bufferToBase64URLString(utf8StringToBuffer("fizz")), timeout: 1, }); expect(mockNavigatorGet.mock.calls[0][0].allowCredentials).toEqual(undefined); }); -test('should convert allow allowCredential to undefined when empty', async () => { +test("should convert allow allowCredential to undefined when empty", async () => { await startAuthentication({ - challenge: bufferToBase64URLString(utf8StringToBuffer('fizz')), + challenge: bufferToBase64URLString(utf8StringToBuffer("fizz")), timeout: 1, allowCredentials: [], }); expect(mockNavigatorGet.mock.calls[0][0].allowCredentials).toEqual(undefined); }); -test('should return base64url-encoded response values', async () => { +test("should return base64url-encoded response values", async () => { mockNavigatorGet.mockImplementation((): Promise<AuthenticationCredential> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ - id: 'foobar', - rawId: Buffer.from('foobar', 'ascii'), + id: "foobar", + rawId: Buffer.from("foobar", "ascii"), response: { - authenticatorData: Buffer.from(mockAuthenticatorData, 'ascii'), - clientDataJSON: Buffer.from(mockClientDataJSON, 'ascii'), - signature: Buffer.from(mockSignature, 'ascii'), - userHandle: Buffer.from(mockUserHandle, 'ascii'), + authenticatorData: Buffer.from(mockAuthenticatorData, "ascii"), + clientDataJSON: Buffer.from(mockClientDataJSON, "ascii"), + signature: Buffer.from(mockSignature, "ascii"), + userHandle: Buffer.from(mockUserHandle, "ascii"), }, getClientExtensionResults: () => ({}), - type: 'public-key', - authenticatorAttachment: '', + type: "public-key", + authenticatorAttachment: "", }); }); }); const response = await startAuthentication(goodOpts1); - expect(response.rawId).toEqual('Zm9vYmFy'); - expect(response.response.authenticatorData).toEqual('bW9ja0F1dGhlbnRpY2F0b3JEYXRh'); - expect(response.response.clientDataJSON).toEqual('bW9ja0NsaWVudERhdGFKU09O'); - expect(response.response.signature).toEqual('bW9ja1NpZ25hdHVyZQ'); - expect(response.response.userHandle).toEqual('mockUserHandle'); + expect(response.rawId).toEqual("Zm9vYmFy"); + expect(response.response.authenticatorData).toEqual( + "bW9ja0F1dGhlbnRpY2F0b3JEYXRh", + ); + expect(response.response.clientDataJSON).toEqual("bW9ja0NsaWVudERhdGFKU09O"); + expect(response.response.signature).toEqual("bW9ja1NpZ25hdHVyZQ"); + expect(response.response.userHandle).toEqual("mockUserHandle"); }); test("should throw error if WebAuthn isn't supported", async () => { mockSupportsWebAuthn.mockReturnValue(false); await expect(startAuthentication(goodOpts1)).rejects.toThrow( - 'WebAuthn is not supported in this browser', + "WebAuthn is not supported in this browser", ); }); -test('should throw error if assertion is cancelled for some reason', async () => { +test("should throw error if assertion is cancelled for some reason", async () => { mockNavigatorGet.mockImplementation((): Promise<null> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve(null); }); }); - await expect(startAuthentication(goodOpts1)).rejects.toThrow('Authentication was not completed'); + await expect(startAuthentication(goodOpts1)).rejects.toThrow( + "Authentication was not completed", + ); }); -test('should handle UTF-8 challenges', async () => { +test("should handle UTF-8 challenges", async () => { await startAuthentication(goodOpts2UTF8); const argsPublicKey = mockNavigatorGet.mock.calls[0][0].publicKey; expect(new Uint8Array(argsPublicKey.challenge)).toEqual( new Uint8Array([ - 227, 130, 132, 227, 130, 140, 227, 130, 132, 227, 130, 140, 227, 129, 160, 227, 129, 156, + 227, + 130, + 132, + 227, + 130, + 140, + 227, + 130, + 132, + 227, + 130, + 140, + 227, + 129, + 160, + 227, + 129, + 156, ]), ); }); -test('should send extensions to authenticator if present in options', async () => { +test("should send extensions to authenticator if present in options", async () => { const extensions: AuthenticationExtensionsClientInputs = { credProps: true, - appid: 'appidHere', + appid: "appidHere", // @ts-ignore uvm: true, // @ts-ignore - appidExclude: 'appidExcludeHere', + appidExclude: "appidExcludeHere", }; const optsWithExts: PublicKeyCredentialRequestOptionsJSON = { ...goodOpts1, @@ -180,7 +204,7 @@ test('should send extensions to authenticator if present in options', async () = expect(argsExtensions).toEqual(extensions); }); -test('should not set any extensions if not present in options', async () => { +test("should not set any extensions if not present in options", async () => { await startAuthentication(goodOpts1); const argsExtensions = mockNavigatorGet.mock.calls[0][0].publicKey.extensions; @@ -188,7 +212,7 @@ test('should not set any extensions if not present in options', async () => { expect(argsExtensions).toEqual(undefined); }); -test('should include extension results', async () => { +test("should include extension results", async () => { const extResults: AuthenticationExtensionsClientOutputs = { appid: true, credProps: { @@ -198,7 +222,7 @@ test('should include extension results', async () => { // Mock extension return values from authenticator mockNavigatorGet.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: {}, getClientExtensionResults: () => extResults }); }); }); @@ -209,7 +233,7 @@ test('should include extension results', async () => { expect(response.clientExtensionResults).toEqual(extResults); }); -test('should include extension results when no extensions specified', async () => { +test("should include extension results when no extensions specified", async () => { const response = await startAuthentication(goodOpts1); expect(response.clientExtensionResults).toEqual({}); @@ -221,20 +245,23 @@ test('should support "cable" transport', async () => { allowCredentials: [ { ...goodOpts1.allowCredentials![0], - transports: ['cable'], + transports: ["cable"], }, ], }; await startAuthentication(opts); - expect(mockNavigatorGet.mock.calls[0][0].publicKey.allowCredentials[0].transports[0]).toEqual( - 'cable', + expect( + mockNavigatorGet.mock.calls[0][0].publicKey.allowCredentials[0] + .transports[0], + ).toEqual( + "cable", ); }); -test('should cancel an existing call when executed again', async () => { - const abortSpy = jest.spyOn(AbortController.prototype, 'abort'); +test("should cancel an existing call when executed again", async () => { + const abortSpy = jest.spyOn(AbortController.prototype, "abort"); // Fire off a request and immediately attempt a second one startAuthentication(goodOpts1); @@ -242,13 +269,13 @@ test('should cancel an existing call when executed again', async () => { expect(abortSpy).toHaveBeenCalledTimes(1); }); -test('should set up autofill a.k.a. Conditional UI', async () => { +test("should set up autofill a.k.a. Conditional UI", async () => { const opts: PublicKeyCredentialRequestOptionsJSON = { ...goodOpts1, allowCredentials: [ { ...goodOpts1.allowCredentials![0], - transports: ['cable'], + transports: ["cable"], }, ], }; @@ -263,14 +290,16 @@ test('should set up autofill a.k.a. Conditional UI', async () => { await startAuthentication(opts, true); // The most important bit - expect(mockNavigatorGet.mock.calls[0][0].mediation).toEqual('conditional'); + expect(mockNavigatorGet.mock.calls[0][0].mediation).toEqual("conditional"); // The latest version of https://github.com/w3c/webauthn/pull/1576 says allowCredentials should // be an "empty list", as opposed to being undefined - expect(mockNavigatorGet.mock.calls[0][0].publicKey.allowCredentials).toBeDefined(); - expect(mockNavigatorGet.mock.calls[0][0].publicKey.allowCredentials.length).toEqual(0); + expect(mockNavigatorGet.mock.calls[0][0].publicKey.allowCredentials) + .toBeDefined(); + expect(mockNavigatorGet.mock.calls[0][0].publicKey.allowCredentials.length) + .toEqual(0); }); -test('should throw error if autofill not supported', async () => { +test("should throw error if autofill not supported", async () => { mockSupportsAutofill.mockResolvedValue(false); const rejected = await expect(startAuthentication(goodOpts1, true)).rejects; @@ -278,7 +307,7 @@ test('should throw error if autofill not supported', async () => { rejected.toThrow(/does not support webauthn autofill/i); }); -test('should throw error if no acceptable <input> is found', async () => { +test("should throw error if no acceptable <input> is found", async () => { // <input> is missing "webauthn" from the autocomplete attribute document.body.innerHTML = ` <form> @@ -293,26 +322,26 @@ test('should throw error if no acceptable <input> is found', async () => { rejected.toThrow(/no <input>/i); }); -test('should return authenticatorAttachment if present', async () => { +test("should return authenticatorAttachment if present", async () => { // Mock extension return values from authenticator mockNavigatorGet.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: {}, - getClientExtensionResults: () => { }, - authenticatorAttachment: 'cross-platform', + getClientExtensionResults: () => {}, + authenticatorAttachment: "cross-platform", }); }); }); const response = await startAuthentication(goodOpts1); - expect(response.authenticatorAttachment).toEqual('cross-platform'); + expect(response.authenticatorAttachment).toEqual("cross-platform"); }); -describe('WebAuthnError', () => { - describe('AbortError', () => { - const AbortError = generateCustomError('AbortError'); +describe("WebAuthnError", () => { + describe("AbortError", () => { + const AbortError = generateCustomError("AbortError"); /** * We can't actually test this because nothing in startAuthentication() propagates the abort @@ -321,38 +350,41 @@ describe('WebAuthnError', () => { * * As a matter of fact I couldn't actually get any browser to respect the abort signal... */ - test.skip('should identify abort signal', async () => { + test.skip("should identify abort signal", async () => { mockNavigatorGet.mockRejectedValueOnce(AbortError); const rejected = await expect(startAuthentication(goodOpts1)).rejects; rejected.toThrow(WebAuthnError); rejected.toThrow(/abort signal/i); - rejected.toHaveProperty('name', 'AbortError'); - rejected.toHaveProperty('code', 'ERROR_CEREMONY_ABORTED'); - rejected.toHaveProperty('cause', AbortError); + rejected.toHaveProperty("name", "AbortError"); + rejected.toHaveProperty("code", "ERROR_CEREMONY_ABORTED"); + rejected.toHaveProperty("cause", AbortError); }); }); - describe('NotAllowedError', () => { - test('should pass through error message (iOS Safari - Operation failed)', async () => { + describe("NotAllowedError", () => { + test("should pass through error message (iOS Safari - Operation failed)", async () => { /** * Thrown when biometric is not enrolled, or a Safari bug prevents conditional UI from being * aborted properly between page reloads. * * See https://github.com/MasterKale/SimpleWebAuthn/discussions/350#discussioncomment-4896572 */ - const NotAllowedError = generateCustomError('NotAllowedError', 'Operation failed.'); + const NotAllowedError = generateCustomError( + "NotAllowedError", + "Operation failed.", + ); mockNavigatorGet.mockRejectedValueOnce(NotAllowedError); const rejected = await expect(startAuthentication(goodOpts1)).rejects; rejected.toThrow(Error); rejected.toThrow(/operation failed/i); - rejected.toHaveProperty('name', 'NotAllowedError'); - rejected.toHaveProperty('code', 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY'); - rejected.toHaveProperty('cause', NotAllowedError); + rejected.toHaveProperty("name", "NotAllowedError"); + rejected.toHaveProperty("code", "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY"); + rejected.toHaveProperty("cause", NotAllowedError); }); - test('should pass through error message (Chrome M110 - Bad TLS Cert)', async () => { + test("should pass through error message (Chrome M110 - Bad TLS Cert)", async () => { /** * Starting from Chrome M110, WebAuthn is blocked if the site is being displayed on a URL with * TLS certificate issues. This includes during development. @@ -360,22 +392,22 @@ describe('WebAuthnError', () => { * See https://github.com/MasterKale/SimpleWebAuthn/discussions/351#discussioncomment-4910458 */ const NotAllowedError = generateCustomError( - 'NotAllowedError', - 'WebAuthn is not supported on sites with TLS certificate errors.' + "NotAllowedError", + "WebAuthn is not supported on sites with TLS certificate errors.", ); mockNavigatorGet.mockRejectedValueOnce(NotAllowedError); const rejected = await expect(startAuthentication(goodOpts1)).rejects; rejected.toThrow(Error); rejected.toThrow(/sites with TLS certificate errors/i); - rejected.toHaveProperty('name', 'NotAllowedError'); - rejected.toHaveProperty('code', 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY'); - rejected.toHaveProperty('cause', NotAllowedError); + rejected.toHaveProperty("name", "NotAllowedError"); + rejected.toHaveProperty("code", "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY"); + rejected.toHaveProperty("cause", NotAllowedError); }); }); - describe('SecurityError', () => { - const SecurityError = generateCustomError('SecurityError'); + describe("SecurityError", () => { + const SecurityError = generateCustomError("SecurityError"); let _originalHostName: string; @@ -387,8 +419,8 @@ describe('WebAuthnError', () => { window.location.hostname = _originalHostName; }); - test('should identify invalid domain', async () => { - window.location.hostname = '1.2.3.4'; + test("should identify invalid domain", async () => { + window.location.hostname = "1.2.3.4"; mockNavigatorGet.mockRejectedValueOnce(SecurityError); @@ -396,13 +428,13 @@ describe('WebAuthnError', () => { rejected.toThrowError(WebAuthnError); rejected.toThrow(/1\.2\.3\.4/); rejected.toThrow(/invalid domain/i); - rejected.toHaveProperty('name', 'SecurityError'); - rejected.toHaveProperty('code', 'ERROR_INVALID_DOMAIN'); - rejected.toHaveProperty('cause', SecurityError); + rejected.toHaveProperty("name", "SecurityError"); + rejected.toHaveProperty("code", "ERROR_INVALID_DOMAIN"); + rejected.toHaveProperty("cause", SecurityError); }); - test('should identify invalid RP ID', async () => { - window.location.hostname = 'simplewebauthn.com'; + test("should identify invalid RP ID", async () => { + window.location.hostname = "simplewebauthn.com"; mockNavigatorGet.mockRejectedValueOnce(SecurityError); @@ -410,16 +442,16 @@ describe('WebAuthnError', () => { rejected.toThrowError(WebAuthnError); rejected.toThrow(goodOpts1.rpId); rejected.toThrow(/invalid for this domain/i); - rejected.toHaveProperty('name', 'SecurityError'); - rejected.toHaveProperty('code', 'ERROR_INVALID_RP_ID'); - rejected.toHaveProperty('cause', SecurityError); + rejected.toHaveProperty("name", "SecurityError"); + rejected.toHaveProperty("code", "ERROR_INVALID_RP_ID"); + rejected.toHaveProperty("cause", SecurityError); }); }); - describe('UnknownError', () => { - const UnknownError = generateCustomError('UnknownError'); + describe("UnknownError", () => { + const UnknownError = generateCustomError("UnknownError"); - test('should identify potential authenticator issues', async () => { + test("should identify potential authenticator issues", async () => { mockNavigatorGet.mockRejectedValueOnce(UnknownError); const rejected = await expect(startAuthentication(goodOpts1)).rejects; @@ -427,9 +459,9 @@ describe('WebAuthnError', () => { rejected.toThrow(/authenticator/i); rejected.toThrow(/unable to process the specified options/i); rejected.toThrow(/could not create a new assertion signature/i); - rejected.toHaveProperty('name', 'UnknownError'); - rejected.toHaveProperty('code', 'ERROR_AUTHENTICATOR_GENERAL_ERROR'); - rejected.toHaveProperty('cause', UnknownError); + rejected.toHaveProperty("name", "UnknownError"); + rejected.toHaveProperty("code", "ERROR_AUTHENTICATOR_GENERAL_ERROR"); + rejected.toHaveProperty("cause", UnknownError); }); }); }); diff --git a/packages/browser/src/methods/startAuthentication.ts b/packages/browser/src/methods/startAuthentication.ts index cce28e7..5147232 100644 --- a/packages/browser/src/methods/startAuthentication.ts +++ b/packages/browser/src/methods/startAuthentication.ts @@ -1,18 +1,18 @@ import { - PublicKeyCredentialRequestOptionsJSON, AuthenticationCredential, AuthenticationResponseJSON, -} from '@simplewebauthn/typescript-types'; + PublicKeyCredentialRequestOptionsJSON, +} from "@simplewebauthn/typescript-types"; -import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString'; -import { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer'; -import { bufferToUTF8String } from '../helpers/bufferToUTF8String'; -import { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn'; -import { browserSupportsWebAuthnAutofill } from '../helpers/browserSupportsWebAuthnAutofill'; -import { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor'; -import { identifyAuthenticationError } from '../helpers/identifyAuthenticationError'; -import { webauthnAbortService } from '../helpers/webAuthnAbortService'; -import { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment'; +import { bufferToBase64URLString } from "../helpers/bufferToBase64URLString"; +import { base64URLStringToBuffer } from "../helpers/base64URLStringToBuffer"; +import { bufferToUTF8String } from "../helpers/bufferToUTF8String"; +import { browserSupportsWebAuthn } from "../helpers/browserSupportsWebAuthn"; +import { browserSupportsWebAuthnAutofill } from "../helpers/browserSupportsWebAuthnAutofill"; +import { toPublicKeyCredentialDescriptor } from "../helpers/toPublicKeyCredentialDescriptor"; +import { identifyAuthenticationError } from "../helpers/identifyAuthenticationError"; +import { webauthnAbortService } from "../helpers/webAuthnAbortService"; +import { toAuthenticatorAttachment } from "../helpers/toAuthenticatorAttachment"; /** * Begin authenticator "login" via WebAuthn assertion @@ -26,14 +26,16 @@ export async function startAuthentication( useBrowserAutofill = false, ): Promise<AuthenticationResponseJSON> { if (!browserSupportsWebAuthn()) { - throw new Error('WebAuthn is not supported in this browser'); + throw new Error("WebAuthn is not supported in this browser"); } // We need to avoid passing empty array to avoid blocking retrieval // of public key let allowCredentials; if (requestOptionsJSON.allowCredentials?.length !== 0) { - allowCredentials = requestOptionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor); + allowCredentials = requestOptionsJSON.allowCredentials?.map( + toPublicKeyCredentialDescriptor, + ); } // We need to convert some values to Uint8Arrays before passing the credentials to the navigator @@ -52,20 +54,24 @@ export async function startAuthentication( */ if (useBrowserAutofill) { if (!(await browserSupportsWebAuthnAutofill())) { - throw Error('Browser does not support WebAuthn autofill'); + throw Error("Browser does not support WebAuthn autofill"); } // Check for an <input> with "webauthn" in its `autocomplete` attribute - const eligibleInputs = document.querySelectorAll("input[autocomplete*='webauthn']"); + const eligibleInputs = document.querySelectorAll( + "input[autocomplete*='webauthn']", + ); // WebAuthn autofill requires at least one valid input if (eligibleInputs.length < 1) { - throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected'); + throw Error( + 'No <input> with `"webauthn"` in its `autocomplete` attribute was detected', + ); } // `CredentialMediationRequirement` doesn't know about "conditional" yet as of // typescript@4.6.3 - options.mediation = 'conditional' as CredentialMediationRequirement; + options.mediation = "conditional" as CredentialMediationRequirement; // Conditional UI requires an empty allow list publicKey.allowCredentials = []; } @@ -78,13 +84,14 @@ export async function startAuthentication( // Wait for the user to complete assertion let credential; try { - credential = (await navigator.credentials.get(options)) as AuthenticationCredential; + credential = + (await navigator.credentials.get(options)) as AuthenticationCredential; } catch (err) { throw identifyAuthenticationError({ error: err as Error, options }); } if (!credential) { - throw new Error('Authentication was not completed'); + throw new Error("Authentication was not completed"); } const { id, rawId, response, type } = credential; @@ -106,6 +113,8 @@ export async function startAuthentication( }, type, clientExtensionResults: credential.getClientExtensionResults(), - authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment), + authenticatorAttachment: toAuthenticatorAttachment( + credential.authenticatorAttachment, + ), }; } diff --git a/packages/browser/src/methods/startRegistration.test.ts b/packages/browser/src/methods/startRegistration.test.ts index e27099d..d9ea0f7 100644 --- a/packages/browser/src/methods/startRegistration.test.ts +++ b/packages/browser/src/methods/startRegistration.test.ts @@ -3,49 +3,50 @@ import { AuthenticationExtensionsClientOutputs, PublicKeyCredentialCreationOptionsJSON, RegistrationCredential, -} from '@simplewebauthn/typescript-types'; -import { generateCustomError } from '../helpers/__jest__/generateCustomError'; -import { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn'; -import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString'; -import { WebAuthnError } from '../helpers/webAuthnError'; -import { webauthnAbortService } from '../helpers/webAuthnAbortService'; +} from "@simplewebauthn/typescript-types"; +import { generateCustomError } from "../helpers/__jest__/generateCustomError"; +import { browserSupportsWebAuthn } from "../helpers/browserSupportsWebAuthn"; +import { bufferToBase64URLString } from "../helpers/bufferToBase64URLString"; +import { WebAuthnError } from "../helpers/webAuthnError"; +import { webauthnAbortService } from "../helpers/webAuthnAbortService"; -import { utf8StringToBuffer } from '../helpers/utf8StringToBuffer'; +import { utf8StringToBuffer } from "../helpers/utf8StringToBuffer"; -import { startRegistration } from './startRegistration'; +import { startRegistration } from "./startRegistration"; -jest.mock('../helpers/browserSupportsWebAuthn'); +jest.mock("../helpers/browserSupportsWebAuthn"); const mockNavigatorCreate = window.navigator.credentials.create as jest.Mock; const mockSupportsWebauthn = browserSupportsWebAuthn as jest.Mock; -const mockAttestationObject = 'mockAtte'; -const mockClientDataJSON = 'mockClie'; +const mockAttestationObject = "mockAtte"; +const mockClientDataJSON = "mockClie"; const goodOpts1: PublicKeyCredentialCreationOptionsJSON = { - challenge: bufferToBase64URLString(utf8StringToBuffer('fizz')), - attestation: 'direct', + challenge: bufferToBase64URLString(utf8StringToBuffer("fizz")), + attestation: "direct", pubKeyCredParams: [ { alg: -7, - type: 'public-key', + type: "public-key", }, ], rp: { - id: 'simplewebauthn.dev', - name: 'SimpleWebAuthn', + id: "simplewebauthn.dev", + name: "SimpleWebAuthn", }, user: { - id: '5678', - displayName: 'username', - name: 'username', + id: "5678", + displayName: "username", + name: "username", }, timeout: 1, excludeCredentials: [ { - id: 'C0VGlvYFratUdAV1iCw-ULpUW8E-exHPXQChBfyVeJZCMfjMFcwDmOFgoMUz39LoMtCJUBW8WPlLkGT6q8qTCg', - type: 'public-key', - transports: ['internal'], + id: + "C0VGlvYFratUdAV1iCw-ULpUW8E-exHPXQChBfyVeJZCMfjMFcwDmOFgoMUz39LoMtCJUBW8WPlLkGT6q8qTCg", + type: "public-key", + transports: ["internal"], }, ], }; @@ -53,7 +54,7 @@ const goodOpts1: PublicKeyCredentialCreationOptionsJSON = { beforeEach(() => { // Stub out a response so the method won't throw mockNavigatorCreate.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: {}, getClientExtensionResults: () => ({}) }); }); }); @@ -70,77 +71,85 @@ afterEach(() => { mockSupportsWebauthn.mockReset(); }); -test('should convert options before passing to navigator.credentials.create(...)', async () => { +test("should convert options before passing to navigator.credentials.create(...)", async () => { await startRegistration(goodOpts1); const argsPublicKey = mockNavigatorCreate.mock.calls[0][0].publicKey; const credId = argsPublicKey.excludeCredentials[0].id; // Make sure challenge and user.id are converted to Buffers - expect(new Uint8Array(argsPublicKey.challenge)).toEqual(new Uint8Array([102, 105, 122, 122])); - expect(new Uint8Array(argsPublicKey.user.id)).toEqual(new Uint8Array([53, 54, 55, 56])); + expect(new Uint8Array(argsPublicKey.challenge)).toEqual( + new Uint8Array([102, 105, 122, 122]), + ); + expect(new Uint8Array(argsPublicKey.user.id)).toEqual( + new Uint8Array([53, 54, 55, 56]), + ); // Confirm construction of excludeCredentials array expect(credId instanceof ArrayBuffer).toEqual(true); expect(credId.byteLength).toEqual(64); - expect(argsPublicKey.excludeCredentials[0].type).toEqual('public-key'); - expect(argsPublicKey.excludeCredentials[0].transports).toEqual(['internal']); + expect(argsPublicKey.excludeCredentials[0].type).toEqual("public-key"); + expect(argsPublicKey.excludeCredentials[0].transports).toEqual(["internal"]); }); -test('should return base64url-encoded response values', async () => { - mockNavigatorCreate.mockImplementation((): Promise<RegistrationCredential> => { - return new Promise(resolve => { - resolve({ - id: 'foobar', - rawId: utf8StringToBuffer('foobar'), - response: { - attestationObject: Buffer.from(mockAttestationObject, 'ascii'), - clientDataJSON: Buffer.from(mockClientDataJSON, 'ascii'), - getTransports: () => [], - getAuthenticatorData: () => new Uint8Array(), - getPublicKey: () => null, - getPublicKeyAlgorithm: () => -999, - }, - getClientExtensionResults: () => ({}), - type: 'public-key', - authenticatorAttachment: '', +test("should return base64url-encoded response values", async () => { + mockNavigatorCreate.mockImplementation( + (): Promise<RegistrationCredential> => { + return new Promise((resolve) => { + resolve({ + id: "foobar", + rawId: utf8StringToBuffer("foobar"), + response: { + attestationObject: Buffer.from(mockAttestationObject, "ascii"), + clientDataJSON: Buffer.from(mockClientDataJSON, "ascii"), + getTransports: () => [], + getAuthenticatorData: () => new Uint8Array(), + getPublicKey: () => null, + getPublicKeyAlgorithm: () => -999, + }, + getClientExtensionResults: () => ({}), + type: "public-key", + authenticatorAttachment: "", + }); }); - }); - }); + }, + ); const response = await startRegistration(goodOpts1); - expect(response.rawId).toEqual('Zm9vYmFy'); - expect(response.response.attestationObject).toEqual('bW9ja0F0dGU'); - expect(response.response.clientDataJSON).toEqual('bW9ja0NsaWU'); + expect(response.rawId).toEqual("Zm9vYmFy"); + expect(response.response.attestationObject).toEqual("bW9ja0F0dGU"); + expect(response.response.clientDataJSON).toEqual("bW9ja0NsaWU"); }); test("should throw error if WebAuthn isn't supported", async () => { mockSupportsWebauthn.mockReturnValue(false); await expect(startRegistration(goodOpts1)).rejects.toThrow( - 'WebAuthn is not supported in this browser', + "WebAuthn is not supported in this browser", ); }); -test('should throw error if attestation is cancelled for some reason', async () => { +test("should throw error if attestation is cancelled for some reason", async () => { mockNavigatorCreate.mockImplementation((): Promise<null> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve(null); }); }); - await expect(startRegistration(goodOpts1)).rejects.toThrow('Registration was not completed'); + await expect(startRegistration(goodOpts1)).rejects.toThrow( + "Registration was not completed", + ); }); -test('should send extensions to authenticator if present in options', async () => { +test("should send extensions to authenticator if present in options", async () => { const extensions: AuthenticationExtensionsClientInputs = { credProps: true, - appid: 'appidHere', + appid: "appidHere", // @ts-ignore uvm: true, // @ts-ignore - appidExclude: 'appidExcludeHere', + appidExclude: "appidExcludeHere", }; const optsWithExts: PublicKeyCredentialCreationOptionsJSON = { ...goodOpts1, @@ -148,20 +157,22 @@ test('should send extensions to authenticator if present in options', async () = }; await startRegistration(optsWithExts); - const argsExtensions = mockNavigatorCreate.mock.calls[0][0].publicKey.extensions; + const argsExtensions = + mockNavigatorCreate.mock.calls[0][0].publicKey.extensions; expect(argsExtensions).toEqual(extensions); }); -test('should not set any extensions if not present in options', async () => { +test("should not set any extensions if not present in options", async () => { await startRegistration(goodOpts1); - const argsExtensions = mockNavigatorCreate.mock.calls[0][0].publicKey.extensions; + const argsExtensions = + mockNavigatorCreate.mock.calls[0][0].publicKey.extensions; expect(argsExtensions).toEqual(undefined); }); -test('should include extension results', async () => { +test("should include extension results", async () => { const extResults: AuthenticationExtensionsClientOutputs = { appid: true, credProps: { @@ -171,7 +182,7 @@ test('should include extension results', async () => { // Mock extension return values from authenticator mockNavigatorCreate.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: {}, getClientExtensionResults: () => extResults }); }); }); @@ -182,7 +193,7 @@ test('should include extension results', async () => { expect(response.clientExtensionResults).toEqual(extResults); }); -test('should include extension results when no extensions specified', async () => { +test("should include extension results when no extensions specified", async () => { const response = await startRegistration(goodOpts1); expect(response.clientExtensionResults).toEqual({}); @@ -194,7 +205,7 @@ test('should support "cable" transport in excludeCredentials', async () => { excludeCredentials: [ { ...goodOpts1.excludeCredentials![0], - transports: ['cable'], + transports: ["cable"], }, ], }; @@ -202,30 +213,31 @@ test('should support "cable" transport in excludeCredentials', async () => { await startRegistration(opts); expect( - mockNavigatorCreate.mock.calls[0][0].publicKey.excludeCredentials[0].transports[0], - ).toEqual('cable'); + mockNavigatorCreate.mock.calls[0][0].publicKey.excludeCredentials[0] + .transports[0], + ).toEqual("cable"); }); test('should return "cable" transport from response', async () => { mockNavigatorCreate.mockResolvedValue({ - id: 'foobar', - rawId: utf8StringToBuffer('foobar'), + id: "foobar", + rawId: utf8StringToBuffer("foobar"), response: { - attestationObject: Buffer.from(mockAttestationObject, 'ascii'), - clientDataJSON: Buffer.from(mockClientDataJSON, 'ascii'), - getTransports: () => ['cable'], + attestationObject: Buffer.from(mockAttestationObject, "ascii"), + clientDataJSON: Buffer.from(mockClientDataJSON, "ascii"), + getTransports: () => ["cable"], }, getClientExtensionResults: () => ({}), - type: 'webauthn.create', + type: "webauthn.create", }); const regResponse = await startRegistration(goodOpts1); - expect(regResponse.response.transports).toEqual(['cable']); + expect(regResponse.response.transports).toEqual(["cable"]); }); -test('should cancel an existing call when executed again', async () => { - const abortSpy = jest.spyOn(AbortController.prototype, 'abort'); +test("should cancel an existing call when executed again", async () => { + const abortSpy = jest.spyOn(AbortController.prototype, "abort"); // Fire off a request and immediately attempt a second one startRegistration(goodOpts1); @@ -233,24 +245,24 @@ test('should cancel an existing call when executed again', async () => { expect(abortSpy).toHaveBeenCalledTimes(1); }); -test('should return authenticatorAttachment if present', async () => { +test("should return authenticatorAttachment if present", async () => { // Mock extension return values from authenticator mockNavigatorCreate.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: {}, - getClientExtensionResults: () => { }, - authenticatorAttachment: 'cross-platform', + getClientExtensionResults: () => {}, + authenticatorAttachment: "cross-platform", }); }); }); const response = await startRegistration(goodOpts1); - expect(response.authenticatorAttachment).toEqual('cross-platform'); + expect(response.authenticatorAttachment).toEqual("cross-platform"); }); -test('should return convenience values if getters present', async () => { +test("should return convenience values if getters present", async () => { /** * I call them "convenience values" because the getters for public key algorithm, * public key bytes, and authenticator data are alternative ways to access information @@ -258,14 +270,14 @@ test('should return convenience values if getters present', async () => { */ // Mock extension return values from authenticator mockNavigatorCreate.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: { getPublicKeyAlgorithm: () => 777, getPublicKey: () => new Uint8Array([0, 0, 0, 0]).buffer, getAuthenticatorData: () => new Uint8Array([0, 0, 0, 0]).buffer, }, - getClientExtensionResults: () => { }, + getClientExtensionResults: () => {}, }); }); }); @@ -273,11 +285,11 @@ test('should return convenience values if getters present', async () => { const response = await startRegistration(goodOpts1); expect(response.response.publicKeyAlgorithm).toEqual(777); - expect(response.response.publicKey).toEqual('AAAAAA'); - expect(response.response.authenticatorData).toEqual('AAAAAA'); + expect(response.response.publicKey).toEqual("AAAAAA"); + expect(response.response.authenticatorData).toEqual("AAAAAA"); }); -test('should not return convenience values if getters missing', async () => { +test("should not return convenience values if getters missing", async () => { /** * I call them "convenience values" because the getters for public key algorithm, * public key bytes, and authenticator data are alternative ways to access information @@ -285,10 +297,10 @@ test('should not return convenience values if getters missing', async () => { */ // Mock extension return values from authenticator mockNavigatorCreate.mockImplementation((): Promise<any> => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({ response: {}, - getClientExtensionResults: () => { }, + getClientExtensionResults: () => {}, }); }); }); @@ -300,9 +312,9 @@ test('should not return convenience values if getters missing', async () => { expect(response.response.authenticatorData).toBeUndefined(); }); -describe('WebAuthnError', () => { - describe('AbortError', () => { - const AbortError = generateCustomError('AbortError'); +describe("WebAuthnError", () => { + describe("AbortError", () => { + const AbortError = generateCustomError("AbortError"); /** * We can't actually test this because nothing in startRegistration() propagates the abort * signal. But if you invoked WebAuthn via this and then manually sent an abort signal I guess @@ -310,28 +322,28 @@ describe('WebAuthnError', () => { * * As a matter of fact I couldn't actually get any browser to respect the abort signal... */ - test.skip('should identify abort signal', async () => { + test.skip("should identify abort signal", async () => { mockNavigatorCreate.mockRejectedValueOnce(AbortError); const rejected = await expect(startRegistration(goodOpts1)).rejects; rejected.toThrow(WebAuthnError); rejected.toThrow(/abort signal/i); rejected.toThrow(/AbortError/); - rejected.toHaveProperty('code', 'ERROR_CEREMONY_ABORTED'); - rejected.toHaveProperty('cause', AbortError); + rejected.toHaveProperty("code", "ERROR_CEREMONY_ABORTED"); + rejected.toHaveProperty("cause", AbortError); }); }); - describe('ConstraintError', () => { - const ConstraintError = generateCustomError('ConstraintError'); + describe("ConstraintError", () => { + const ConstraintError = generateCustomError("ConstraintError"); - test('should identify unsupported discoverable credentials', async () => { + test("should identify unsupported discoverable credentials", async () => { mockNavigatorCreate.mockRejectedValueOnce(ConstraintError); const opts: PublicKeyCredentialCreationOptionsJSON = { ...goodOpts1, authenticatorSelection: { - residentKey: 'required', + residentKey: "required", requireResidentKey: true, }, }; @@ -340,18 +352,21 @@ describe('WebAuthnError', () => { rejected.toThrow(WebAuthnError); rejected.toThrow(/discoverable credentials were required/i); rejected.toThrow(/no available authenticator supported/i); - rejected.toHaveProperty('name', 'ConstraintError'); - rejected.toHaveProperty('code', 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT'); - rejected.toHaveProperty('cause', ConstraintError); + rejected.toHaveProperty("name", "ConstraintError"); + rejected.toHaveProperty( + "code", + "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT", + ); + rejected.toHaveProperty("cause", ConstraintError); }); - test('should identify unsupported user verification', async () => { + test("should identify unsupported user verification", async () => { mockNavigatorCreate.mockRejectedValueOnce(ConstraintError); const opts: PublicKeyCredentialCreationOptionsJSON = { ...goodOpts1, authenticatorSelection: { - userVerification: 'required', + userVerification: "required", }, }; @@ -359,48 +374,57 @@ describe('WebAuthnError', () => { rejected.toThrow(WebAuthnError); rejected.toThrow(/user verification was required/i); rejected.toThrow(/no available authenticator supported/i); - rejected.toHaveProperty('name', 'ConstraintError'); - rejected.toHaveProperty('code', 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT'); - rejected.toHaveProperty('cause', ConstraintError); + rejected.toHaveProperty("name", "ConstraintError"); + rejected.toHaveProperty( + "code", + "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT", + ); + rejected.toHaveProperty("cause", ConstraintError); }); }); - describe('InvalidStateError', () => { - const InvalidStateError = generateCustomError('InvalidStateError'); + describe("InvalidStateError", () => { + const InvalidStateError = generateCustomError("InvalidStateError"); - test('should identify re-registration attempt', async () => { + test("should identify re-registration attempt", async () => { mockNavigatorCreate.mockRejectedValueOnce(InvalidStateError); const rejected = await expect(startRegistration(goodOpts1)).rejects; rejected.toThrow(WebAuthnError); rejected.toThrow(/authenticator/i); rejected.toThrow(/previously registered/i); - rejected.toHaveProperty('name', 'InvalidStateError'); - rejected.toHaveProperty('code', 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED'); - rejected.toHaveProperty('cause', InvalidStateError); + rejected.toHaveProperty("name", "InvalidStateError"); + rejected.toHaveProperty( + "code", + "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", + ); + rejected.toHaveProperty("cause", InvalidStateError); }); }); - describe('NotAllowedError', () => { - test('should pass through error message (iOS Safari - Operation failed)', async () => { + describe("NotAllowedError", () => { + test("should pass through error message (iOS Safari - Operation failed)", async () => { /** * Thrown when biometric is not enrolled, or a Safari bug prevents conditional UI from being * aborted properly between page reloads. * * See https://github.com/MasterKale/SimpleWebAuthn/discussions/350#discussioncomment-4896572 */ - const NotAllowedError = generateCustomError('NotAllowedError', 'Operation failed.'); + const NotAllowedError = generateCustomError( + "NotAllowedError", + "Operation failed.", + ); mockNavigatorCreate.mockRejectedValueOnce(NotAllowedError); const rejected = await expect(startRegistration(goodOpts1)).rejects; rejected.toThrow(Error); rejected.toThrow(/operation failed/i); - rejected.toHaveProperty('name', 'NotAllowedError'); - rejected.toHaveProperty('code', 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY'); - rejected.toHaveProperty('cause', NotAllowedError); + rejected.toHaveProperty("name", "NotAllowedError"); + rejected.toHaveProperty("code", "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY"); + rejected.toHaveProperty("cause", NotAllowedError); }); - test('should pass through error message (Chrome M110 - Bad TLS Cert)', async () => { + test("should pass through error message (Chrome M110 - Bad TLS Cert)", async () => { /** * Starting from Chrome M110, WebAuthn is blocked if the site is being displayed on a URL with * TLS certificate issues. This includes during development. @@ -408,22 +432,22 @@ describe('WebAuthnError', () => { * See https://github.com/MasterKale/SimpleWebAuthn/discussions/351#discussioncomment-4910458 */ const NotAllowedError = generateCustomError( - 'NotAllowedError', - 'WebAuthn is not supported on sites with TLS certificate errors.' + "NotAllowedError", + "WebAuthn is not supported on sites with TLS certificate errors.", ); mockNavigatorCreate.mockRejectedValueOnce(NotAllowedError); const rejected = await expect(startRegistration(goodOpts1)).rejects; rejected.toThrow(Error); rejected.toThrow(/sites with TLS certificate errors/i); - rejected.toHaveProperty('name', 'NotAllowedError'); - rejected.toHaveProperty('code', 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY'); - rejected.toHaveProperty('cause', NotAllowedError); + rejected.toHaveProperty("name", "NotAllowedError"); + rejected.toHaveProperty("code", "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY"); + rejected.toHaveProperty("cause", NotAllowedError); }); }); - describe('NotSupportedError', () => { - const NotSupportedError = generateCustomError('NotSupportedError'); + describe("NotSupportedError", () => { + const NotSupportedError = generateCustomError("NotSupportedError"); test('should identify missing "public-key" entries in pubKeyCredParams', async () => { mockNavigatorCreate.mockRejectedValueOnce(NotSupportedError); @@ -437,31 +461,34 @@ describe('WebAuthnError', () => { rejected.toThrow(WebAuthnError); rejected.toThrow(/pubKeyCredParams/i); rejected.toThrow(/public-key/i); - rejected.toHaveProperty('name', 'NotSupportedError'); - rejected.toHaveProperty('code', 'ERROR_MALFORMED_PUBKEYCREDPARAMS'); - rejected.toHaveProperty('cause', NotSupportedError); + rejected.toHaveProperty("name", "NotSupportedError"); + rejected.toHaveProperty("code", "ERROR_MALFORMED_PUBKEYCREDPARAMS"); + rejected.toHaveProperty("cause", NotSupportedError); }); - test('should identify no authenticator supports algs in pubKeyCredParams', async () => { + test("should identify no authenticator supports algs in pubKeyCredParams", async () => { mockNavigatorCreate.mockRejectedValueOnce(NotSupportedError); const opts: PublicKeyCredentialCreationOptionsJSON = { ...goodOpts1, - pubKeyCredParams: [{ alg: -7, type: 'public-key' }], + pubKeyCredParams: [{ alg: -7, type: "public-key" }], }; const rejected = await expect(startRegistration(opts)).rejects; rejected.toThrow(WebAuthnError); rejected.toThrow(/No available authenticator/i); rejected.toThrow(/pubKeyCredParams/i); - rejected.toHaveProperty('name', 'NotSupportedError'); - rejected.toHaveProperty('code', 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG'); - rejected.toHaveProperty('cause', NotSupportedError); + rejected.toHaveProperty("name", "NotSupportedError"); + rejected.toHaveProperty( + "code", + "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG", + ); + rejected.toHaveProperty("cause", NotSupportedError); }); }); - describe('SecurityError', () => { - const SecurityError = generateCustomError('SecurityError'); + describe("SecurityError", () => { + const SecurityError = generateCustomError("SecurityError"); let _originalHostName: string; @@ -473,8 +500,8 @@ describe('WebAuthnError', () => { window.location.hostname = _originalHostName; }); - test('should identify invalid domain', async () => { - window.location.hostname = '1.2.3.4'; + test("should identify invalid domain", async () => { + window.location.hostname = "1.2.3.4"; mockNavigatorCreate.mockRejectedValueOnce(SecurityError); @@ -482,13 +509,13 @@ describe('WebAuthnError', () => { rejected.toThrowError(WebAuthnError); rejected.toThrow(/1\.2\.3\.4/); rejected.toThrow(/invalid domain/i); - rejected.toHaveProperty('name', 'SecurityError'); - rejected.toHaveProperty('code', 'ERROR_INVALID_DOMAIN'); - rejected.toHaveProperty('cause', SecurityError); + rejected.toHaveProperty("name", "SecurityError"); + rejected.toHaveProperty("code", "ERROR_INVALID_DOMAIN"); + rejected.toHaveProperty("cause", SecurityError); }); - test('should identify invalid RP ID', async () => { - window.location.hostname = 'simplewebauthn.com'; + test("should identify invalid RP ID", async () => { + window.location.hostname = "simplewebauthn.com"; mockNavigatorCreate.mockRejectedValueOnce(SecurityError); @@ -496,22 +523,22 @@ describe('WebAuthnError', () => { rejected.toThrowError(WebAuthnError); rejected.toThrow(goodOpts1.rp.id); rejected.toThrow(/invalid for this domain/i); - rejected.toHaveProperty('name', 'SecurityError'); - rejected.toHaveProperty('code', 'ERROR_INVALID_RP_ID'); - rejected.toHaveProperty('cause', SecurityError); + rejected.toHaveProperty("name", "SecurityError"); + rejected.toHaveProperty("code", "ERROR_INVALID_RP_ID"); + rejected.toHaveProperty("cause", SecurityError); }); }); - describe('TypeError', () => { - test('should identify malformed user ID', async () => { - const typeError = new TypeError('user id is bad'); + describe("TypeError", () => { + test("should identify malformed user ID", async () => { + const typeError = new TypeError("user id is bad"); mockNavigatorCreate.mockRejectedValueOnce(typeError); const opts = { ...goodOpts1, user: { ...goodOpts1.user, - id: Array(65).fill('a').join(''), + id: Array(65).fill("a").join(""), }, }; @@ -519,16 +546,16 @@ describe('WebAuthnError', () => { rejected.toThrowError(WebAuthnError); rejected.toThrow(/user id/i); rejected.toThrow(/not between 1 and 64 characters/i); - rejected.toHaveProperty('name', 'TypeError'); - rejected.toHaveProperty('code', 'ERROR_INVALID_USER_ID_LENGTH'); - rejected.toHaveProperty('cause', typeError); + rejected.toHaveProperty("name", "TypeError"); + rejected.toHaveProperty("code", "ERROR_INVALID_USER_ID_LENGTH"); + rejected.toHaveProperty("cause", typeError); }); }); - describe('UnknownError', () => { - const UnknownError = generateCustomError('UnknownError'); + describe("UnknownError", () => { + const UnknownError = generateCustomError("UnknownError"); - test('should identify potential authenticator issues', async () => { + test("should identify potential authenticator issues", async () => { mockNavigatorCreate.mockRejectedValueOnce(UnknownError); const rejected = await expect(startRegistration(goodOpts1)).rejects; @@ -536,9 +563,9 @@ describe('WebAuthnError', () => { rejected.toThrow(/authenticator/i); rejected.toThrow(/unable to process the specified options/i); rejected.toThrow(/could not create a new credential/i); - rejected.toHaveProperty('name', 'UnknownError'); - rejected.toHaveProperty('code', 'ERROR_AUTHENTICATOR_GENERAL_ERROR'); - rejected.toHaveProperty('cause', UnknownError); + rejected.toHaveProperty("name", "UnknownError"); + rejected.toHaveProperty("code", "ERROR_AUTHENTICATOR_GENERAL_ERROR"); + rejected.toHaveProperty("cause", UnknownError); }); }); }); diff --git a/packages/browser/src/methods/startRegistration.ts b/packages/browser/src/methods/startRegistration.ts index 5b97a5e..c56f0ed 100644 --- a/packages/browser/src/methods/startRegistration.ts +++ b/packages/browser/src/methods/startRegistration.ts @@ -1,18 +1,18 @@ import { + AuthenticatorTransportFuture, PublicKeyCredentialCreationOptionsJSON, RegistrationCredential, RegistrationResponseJSON, - AuthenticatorTransportFuture, -} from '@simplewebauthn/typescript-types'; +} from "@simplewebauthn/typescript-types"; -import { utf8StringToBuffer } from '../helpers/utf8StringToBuffer'; -import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString'; -import { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer'; -import { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn'; -import { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor'; -import { identifyRegistrationError } from '../helpers/identifyRegistrationError'; -import { webauthnAbortService } from '../helpers/webAuthnAbortService'; -import { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment'; +import { utf8StringToBuffer } from "../helpers/utf8StringToBuffer"; +import { bufferToBase64URLString } from "../helpers/bufferToBase64URLString"; +import { base64URLStringToBuffer } from "../helpers/base64URLStringToBuffer"; +import { browserSupportsWebAuthn } from "../helpers/browserSupportsWebAuthn"; +import { toPublicKeyCredentialDescriptor } from "../helpers/toPublicKeyCredentialDescriptor"; +import { identifyRegistrationError } from "../helpers/identifyRegistrationError"; +import { webauthnAbortService } from "../helpers/webAuthnAbortService"; +import { toAuthenticatorAttachment } from "../helpers/toAuthenticatorAttachment"; /** * Begin authenticator "registration" via WebAuthn attestation @@ -23,7 +23,7 @@ export async function startRegistration( creationOptionsJSON: PublicKeyCredentialCreationOptionsJSON, ): Promise<RegistrationResponseJSON> { if (!browserSupportsWebAuthn()) { - throw new Error('WebAuthn is not supported in this browser'); + throw new Error("WebAuthn is not supported in this browser"); } // We need to convert some values to Uint8Arrays before passing the credentials to the navigator @@ -47,31 +47,32 @@ export async function startRegistration( // Wait for the user to complete attestation let credential; try { - credential = (await navigator.credentials.create(options)) as RegistrationCredential; + credential = + (await navigator.credentials.create(options)) as RegistrationCredential; } catch (err) { throw identifyRegistrationError({ error: err as Error, options }); } if (!credential) { - throw new Error('Registration was not completed'); + throw new Error("Registration was not completed"); } const { id, rawId, response, type } = credential; // Continue to play it safe with `getTransports()` for now, even when L3 types say it's required let transports: AuthenticatorTransportFuture[] | undefined = undefined; - if (typeof response.getTransports === 'function') { + if (typeof response.getTransports === "function") { transports = response.getTransports(); } // L3 says this is required, but browser and webview support are still not guaranteed. let responsePublicKeyAlgorithm: number | undefined = undefined; - if (typeof response.getPublicKeyAlgorithm === 'function') { + if (typeof response.getPublicKeyAlgorithm === "function") { responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm(); } let responsePublicKey: string | undefined = undefined; - if (typeof response.getPublicKey === 'function') { + if (typeof response.getPublicKey === "function") { const _publicKey = response.getPublicKey(); if (_publicKey !== null) { responsePublicKey = bufferToBase64URLString(_publicKey); @@ -80,8 +81,10 @@ export async function startRegistration( // L3 says this is required, but browser and webview support are still not guaranteed. let responseAuthenticatorData: string | undefined; - if (typeof response.getAuthenticatorData === 'function') { - responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData()); + if (typeof response.getAuthenticatorData === "function") { + responseAuthenticatorData = bufferToBase64URLString( + response.getAuthenticatorData(), + ); } return { @@ -97,6 +100,8 @@ export async function startRegistration( }, type, clientExtensionResults: credential.getClientExtensionResults(), - authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment), + authenticatorAttachment: toAuthenticatorAttachment( + credential.authenticatorAttachment, + ), }; } diff --git a/packages/browser/src/setupTests.ts b/packages/browser/src/setupTests.ts index 5b6efcf..e5d5807 100644 --- a/packages/browser/src/setupTests.ts +++ b/packages/browser/src/setupTests.ts @@ -7,7 +7,7 @@ * JSDom doesn't seem to support `credentials`, so let's define them here so we can mock their * implementations in specific tests. */ -Object.defineProperty(window.navigator, 'credentials', { +Object.defineProperty(window.navigator, "credentials", { writable: true, value: { create: jest.fn(), @@ -18,9 +18,9 @@ Object.defineProperty(window.navigator, 'credentials', { /** * Allow for setting values to `window.location.hostname` */ -Object.defineProperty(window, 'location', { +Object.defineProperty(window, "location", { writable: true, value: { - hostname: '', + hostname: "", }, }); |