|
| 1 | +import { isValidBrowser } from '@clerk/shared/browser'; |
| 2 | +import { ClerkRuntimeError } from '@clerk/shared/error'; |
| 3 | +import type { |
| 4 | + PublicKeyCredentialCreationOptionsJSON, |
| 5 | + PublicKeyCredentialCreationOptionsWithoutExtensions, |
| 6 | +} from '@clerk/types'; |
| 7 | + |
| 8 | +type PublicKeyCredentialWithAuthenticatorAttestationResponse = Omit< |
| 9 | + PublicKeyCredential, |
| 10 | + 'response' | 'getClientExtensionResults' |
| 11 | +> & { |
| 12 | + response: Omit<AuthenticatorAttestationResponse, 'getAuthenticatorData' | 'getPublicKey' | 'getPublicKeyAlgorithm'>; |
| 13 | +}; |
| 14 | + |
| 15 | +type WebAuthnCreateCredentialReturn = |
| 16 | + | { |
| 17 | + publicKeyCredential: PublicKeyCredentialWithAuthenticatorAttestationResponse; |
| 18 | + error: null; |
| 19 | + } |
| 20 | + | { |
| 21 | + publicKeyCredential: null; |
| 22 | + error: ClerkWebAuthnError | Error; |
| 23 | + }; |
| 24 | + |
| 25 | +type ClerkWebAuthnErrorCode = 'passkey_exists' | 'passkey_registration_cancelled' | 'passkey_credential_failed'; |
| 26 | + |
| 27 | +function isWebAuthnSupported() { |
| 28 | + return ( |
| 29 | + isValidBrowser() && |
| 30 | + // Check if `PublicKeyCredential` is a constructor |
| 31 | + typeof window.PublicKeyCredential === 'function' |
| 32 | + ); |
| 33 | +} |
| 34 | + |
| 35 | +async function isWebAuthnAutofillSupported(): Promise<boolean> { |
| 36 | + try { |
| 37 | + return isWebAuthnSupported() && (await window.PublicKeyCredential.isConditionalMediationAvailable()); |
| 38 | + } catch (e) { |
| 39 | + return false; |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +async function isWebAuthnPlatformAuthenticatorSupported(): Promise<boolean> { |
| 44 | + try { |
| 45 | + return ( |
| 46 | + typeof window !== 'undefined' && |
| 47 | + (await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()) |
| 48 | + ); |
| 49 | + } catch (e) { |
| 50 | + return false; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +class Base64Converter { |
| 55 | + static encode(buffer: ArrayBuffer): string { |
| 56 | + return btoa(String.fromCharCode(...new Uint8Array(buffer))) |
| 57 | + .replace(/\+/g, '-') |
| 58 | + .replace(/\//g, '_') |
| 59 | + .replace(/=+$/, ''); |
| 60 | + } |
| 61 | + |
| 62 | + static decode(base64url: string): ArrayBuffer { |
| 63 | + // TODO-PASSKEYS: check if this can be replaced with Buffer.from(base64url, 'base64'); |
| 64 | + const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/'); |
| 65 | + |
| 66 | + const binaryString = atob(base64); |
| 67 | + const length = binaryString.length; |
| 68 | + const bytes = new Uint8Array(length); |
| 69 | + for (let i = 0; i < length; i++) { |
| 70 | + bytes[i] = binaryString.charCodeAt(i); |
| 71 | + } |
| 72 | + return bytes.buffer; |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +async function webAuthnCreateCredential( |
| 77 | + publicKeyOptions: PublicKeyCredentialCreationOptionsWithoutExtensions, |
| 78 | +): Promise<WebAuthnCreateCredentialReturn> { |
| 79 | + try { |
| 80 | + // Typescript types are not aligned with the spec. These type assertions are required to comply with the spec. |
| 81 | + const credential = (await navigator.credentials.create({ |
| 82 | + publicKey: publicKeyOptions, |
| 83 | + })) as PublicKeyCredential | null; |
| 84 | + |
| 85 | + if (!credential) { |
| 86 | + return { |
| 87 | + error: new ClerkWebAuthnError('Browser failed to create credential', { code: 'passkey_credential_failed' }), |
| 88 | + publicKeyCredential: null, |
| 89 | + }; |
| 90 | + } |
| 91 | + |
| 92 | + // Typescript types are not aligned with the spec. These type assertions are required to comply with the spec. |
| 93 | + const res = credential.response as AuthenticatorAttestationResponse; |
| 94 | + |
| 95 | + return { publicKeyCredential: { ...credential, response: res }, error: null }; |
| 96 | + } catch (e) { |
| 97 | + return { error: handlePublicKeyCreateError(e), publicKeyCredential: null }; |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +/** |
| 102 | + * Map webauthn errors from `navigator.credentials.create()` to Clerk-js errors |
| 103 | + * @param error |
| 104 | + */ |
| 105 | +function handlePublicKeyCreateError(error: Error): ClerkWebAuthnError | ClerkRuntimeError | Error { |
| 106 | + if (error.name === 'InvalidStateError') { |
| 107 | + return new ClerkWebAuthnError(error.message, { code: 'passkey_exists' }); |
| 108 | + } else if (error.name === 'NotAllowedError') { |
| 109 | + return new ClerkWebAuthnError(error.message, { code: 'passkey_registration_cancelled' }); |
| 110 | + } |
| 111 | + return error; |
| 112 | +} |
| 113 | + |
| 114 | +function convertJSONToPublicKeyCreateOptions(jsonPublicKey: PublicKeyCredentialCreationOptionsJSON) { |
| 115 | + const userIdBuffer = base64UrlToBuffer(jsonPublicKey.user.id); |
| 116 | + const challengeBuffer = base64UrlToBuffer(jsonPublicKey.challenge); |
| 117 | + |
| 118 | + const excludeCredentialsWithBuffer = (jsonPublicKey.excludeCredentials || []).map(cred => ({ |
| 119 | + ...cred, |
| 120 | + id: base64UrlToBuffer(cred.id), |
| 121 | + })); |
| 122 | + |
| 123 | + return { |
| 124 | + ...jsonPublicKey, |
| 125 | + excludeCredentials: excludeCredentialsWithBuffer, |
| 126 | + challenge: challengeBuffer, |
| 127 | + user: { |
| 128 | + ...jsonPublicKey.user, |
| 129 | + id: userIdBuffer, |
| 130 | + }, |
| 131 | + } as PublicKeyCredentialCreationOptionsWithoutExtensions; |
| 132 | +} |
| 133 | + |
| 134 | +function serializePublicKeyCredential(publicKeyCredential: PublicKeyCredentialWithAuthenticatorAttestationResponse) { |
| 135 | + const response = publicKeyCredential.response; |
| 136 | + return { |
| 137 | + type: publicKeyCredential.type, |
| 138 | + id: publicKeyCredential.id, |
| 139 | + rawId: bufferToBase64Url(publicKeyCredential.rawId), |
| 140 | + authenticatorAttachment: publicKeyCredential.authenticatorAttachment, |
| 141 | + response: { |
| 142 | + clientDataJSON: bufferToBase64Url(response.clientDataJSON), |
| 143 | + attestationObject: bufferToBase64Url(response.attestationObject), |
| 144 | + transports: response.getTransports(), |
| 145 | + }, |
| 146 | + }; |
| 147 | +} |
| 148 | + |
| 149 | +const bufferToBase64Url = Base64Converter.encode.bind(Base64Converter); |
| 150 | +const base64UrlToBuffer = Base64Converter.decode.bind(Base64Converter); |
| 151 | + |
| 152 | +export class ClerkWebAuthnError extends ClerkRuntimeError { |
| 153 | + /** |
| 154 | + * A unique code identifying the error, can be used for localization. |
| 155 | + */ |
| 156 | + code: ClerkWebAuthnErrorCode; |
| 157 | + |
| 158 | + constructor(message: string, { code }: { code: ClerkWebAuthnErrorCode }) { |
| 159 | + super(message, { code }); |
| 160 | + this.code = code; |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +export { |
| 165 | + isWebAuthnPlatformAuthenticatorSupported, |
| 166 | + isWebAuthnAutofillSupported, |
| 167 | + isWebAuthnSupported, |
| 168 | + base64UrlToBuffer, |
| 169 | + bufferToBase64Url, |
| 170 | + handlePublicKeyCreateError, |
| 171 | + webAuthnCreateCredential, |
| 172 | + convertJSONToPublicKeyCreateOptions, |
| 173 | + serializePublicKeyCredential, |
| 174 | +}; |
| 175 | + |
| 176 | +export type { PublicKeyCredentialWithAuthenticatorAttestationResponse }; |
0 commit comments