aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/passkey.ts
blob: 7c9e98cc45218ec8a064207885dc698438a93f90 (plain) (blame)
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
import { startRegistration, startAuthentication } from "@simplewebauthn/browser";
import { post } from "$lib/utils";

async function deriveKey(credentialId: string): Promise<ArrayBuffer> {
  const data = new TextEncoder().encode("coinos-wallet-key:" + credentialId);
  return crypto.subtle.digest("SHA-256", data);
}

function authHeader(token: string) {
  return { authorization: `Bearer ${token}` };
}

export async function registerPasskey(
  token?: string,
): Promise<{ prfKey: ArrayBuffer; credentialId: string }> {
  const headers = token ? authHeader(token) : undefined;
  const options = await post("/passkey/register/options", {}, headers);
  const registration = await startRegistration({ optionsJSON: options });
  await post("/passkey/register/verify", registration, headers);
  const prfKey = await deriveKey(registration.id);
  return { prfKey, credentialId: registration.id };
}

export async function loginWithPasskey(): Promise<{
  credential: any;
  challengeId: string;
  prfKey: ArrayBuffer;
}> {
  const { challengeId, ...options } = await post("/passkey/login/options", {});
  const authentication = await startAuthentication({ optionsJSON: options });
  const prfKey = await deriveKey(authentication.id);
  return { credential: authentication, challengeId, prfKey };
}