summaryrefslogtreecommitdiffhomepage
path: root/packages/browser/src/methods/startAssertion.ts
blob: 603c6fbf45455f69422bfdfa2fbd8c8b93372094 (plain)
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
import {
  PublicKeyCredentialRequestOptionsJSON,
  AuthenticatorAssertionResponseJSON,
  AssertionCredential,
} from '@webauthntine/typescript-types';

import toUint8Array from '../helpers/toUint8Array';
import toBase64String from '../helpers/toBase64String';
import supportsWebauthn from '../helpers/supportsWebauthn';

/**
 * Begin authenticator "login" via WebAuthn assertion
 *
 * @param requestOptionsJSON Output from @webauthntine/server's generateAssertionOptions(...)
 */
export default async function startAssertion(
  requestOptionsJSON: PublicKeyCredentialRequestOptionsJSON
): Promise<AuthenticatorAssertionResponseJSON> {
  if (!supportsWebauthn()) {
    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
  const publicKey: PublicKeyCredentialRequestOptions = {
    ...requestOptionsJSON.publicKey,
    challenge: toUint8Array(requestOptionsJSON.publicKey.challenge),
    allowCredentials: requestOptionsJSON.publicKey.allowCredentials.map((cred) => ({
      ...cred,
      id: toUint8Array(cred.id),
    }))
  };

  // Wait for the user to complete assertion
  const credential = await navigator.credentials.get({ publicKey });

  if (!credential) {
    throw new Error('Assertion was not completed');
  }

  const { response } = (credential as AssertionCredential);

  let base64UserHandle = undefined;
  if (response.userHandle) {
    base64UserHandle = toBase64String(response.userHandle);
  }

  // Convert values to base64 to make it easier to send back to the server
  return {
    base64AuthenticatorData: toBase64String(response.authenticatorData),
    base64ClientDataJSON: toBase64String(response.clientDataJSON),
    base64Signature: toBase64String(response.signature),
    base64UserHandle,
  };
}