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

62 lines
2.2 KiB
JavaScript

const start_webauthn = async () => {
const init_data = {
uuid: '{{ uuid }}',
user_name: '{{ username }}',
};
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) => {
const encoder = new TextEncoder();
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 encodeArray = (array) => Base64.fromUint8Array(new Uint8Array(array), true);
const encodeArray2 = (array) => btoa(String.fromCharCode(...new Uint8Array(array)));
console.log(solvedChallenge);
const encodedSolvedChallenge = {
id: solvedChallenge.id,
rawId: encodeArray(solvedChallenge.rawId),
response: {
clientDataJSON: encodeArray(solvedChallenge.response.clientDataJSON),
attestationObject: encodeArray(solvedChallenge.response.attestationObject)
},
type: solvedChallenge.type
};
const encodedSolvedChallenge2 = {
id: solvedChallenge.id,
rawId: encodeArray2(solvedChallenge.rawId),
response: {
clientDataJSON: encodeArray2(solvedChallenge.response.clientDataJSON),
attestationObject: encodeArray2(solvedChallenge.response.attestationObject)
},
type: solvedChallenge.type
};
console.log(encodedSolvedChallenge);
console.log(encodedSolvedChallenge2);
const resp = await fetch("/account/register-finish", {
method: 'POST',
body: JSON.stringify(encodedSolvedChallenge),
headers: { 'Content-Type': 'application/json' }
});
return resp.json();
}
// Main
(async () => {
const publicKey = await start_webauthn()
let solved = await solve_challenge(publicKey);
let finished = await finish_auth(solved);
console.log(solved);
}) ();