nom-nom-nix-gc/src/templates/webauthn-register.js

61 lines
2 KiB
JavaScript

const start_webauthn = async () => {
const init_data = {
uuid: '{{ registration-uuid }}',
};
const challenge_resp = await fetch("/account/register-init", {
method: 'POST',
body: JSON.stringify(init_data),
headers: {
'Content-Type': 'application/json'
}
});
return await challenge_resp.json();
}
const solve_challenge = async (publicKey) => {
// Decode challenge and userid base64 strings into JS arrays.
publicKey.publicKey.challenge = Base64.toUint8Array(publicKey.publicKey.challenge);
publicKey.publicKey.user.id = Base64.toUint8Array(publicKey.publicKey.user.id);
return navigator.credentials.create(publicKey);
}
const finish_auth = async (solvedChallenge) => {
const uinttobase64 = (array) => Base64.fromUint8Array(new Uint8Array(array), true);
const encodedSolvedChallenge = {
id: solvedChallenge.id,
rawId: uinttobase64(solvedChallenge.rawId),
response: {
clientDataJSON: uinttobase64(solvedChallenge.response.clientDataJSON),
attestationObject: uinttobase64(solvedChallenge.response.attestationObject)
},
type: solvedChallenge.type
};
const name = document.getElementById("key-name").value;
const resp = await fetch("/account/register-finish", {
method: 'POST',
body: JSON.stringify({
'uuid': '{{ registration-uuid }}',
'keyname': name,
'credentials': encodedSolvedChallenge
}),
headers: { 'Content-Type': 'application/json' }
});
return resp;
}
const perform_webauthn_dance = async () => {
const publicKey = await start_webauthn()
let solved = await solve_challenge(publicKey);
let finished = await finish_auth(solved);
}
// Main
(async () => {
const form = document.getElementById("key-form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
await perform_webauthn_dance();
location.reload();
});
}) ();