import { ab2str, exportedKeyToPem, pemToKey, genKey } from "./ecc.js"; import { add_div_register_text } from "./registertext.js"; export async function registerConfirm() { const apiUrl = `/account/register`; const inputFieldSharedSecret = document.getElementById("sharedsecret"); const inputFieldPublicKey = document.getElementById("publickey"); let pubkey = null; if (!inputFieldPublicKey.value) { const { privateKey, publicKey } = await genKey(); pubkey = exportedKeyToPem(publicKey, "public"); let privkey = exportedKeyToPem(privateKey, "private"); add_div_register_text(privkey); } else { pubkey = inputFieldPublicKey.value; } const postData = { sharedSecret: inputFieldSharedSecret.value, publicKey: pubkey }; // clear input fields inputFieldSharedSecret.value=''; inputFieldPublicKey.value=''; const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData) }; const response = await fetch(apiUrl, requestOptions) .catch(error => { console.error('Error during POST request:', error); }); if (response.ok) { console.log(response); } else { registerPopupText = document.getElementById("registerPopupText") registerPopupText.innerHTML = ''; registerPopupText.innerText = "Registration failed. Please try again."; console.error('Error in server response.', response); } } export async function loginConfirm() { const apiUrl = `/account/login`; const inputFieldPrivateKey = document.getElementById("privatekey"); const response = await fetch(apiUrl, { method: 'GET' }); if (!response.ok) { throw new Error('Failed to fetch challenge'); } const { challenge } = await response.json(); console.log("Received challenge:", challenge); let privKey = await pemToKey(inputFieldPrivateKey.value, "private"); const encoder = new TextEncoder(); let encodedData = encoder.encode(challenge); // Sign the data using the private key. const signature = await crypto.subtle.sign( { name: "Ed25519", }, privKey, encodedData, ); let signatureString = ab2str(signature); let signatureBase64 = window.btoa(signatureString); const verifyApiUrl = `/account/verify-challenge`; const verifyResponse = await fetch(verifyApiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ signature: signatureBase64 }) }); if (!verifyResponse.ok) { throw new Error('Failed to verify the challenge'); } else { const verifyResult = await verifyResponse.json(); console.log("Verification result:", verifyResult); inputFieldPrivateKey.value = ''; location.reload(); } }