All files / app/web-ui/scripts submit-mfa-scripts.ts

100% Statements 61/61
100% Branches 1/1
100% Functions 1/1
100% Lines 61/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 55 56 57 58 59 60 611x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x
/**
 * This script exposes the submitMfa() function and adds event listeners to the input to progress the cursor
 */
export const submitMfaScript = (basePath: string) => ` 
async function submitMfa() {
    document.querySelector("#submitButton").disabled = true
    document.querySelector("#submitButton").style['background-color'] = "rgb(147 157 179)"
    
    const mfaCode = Array.from(document
        .querySelectorAll("#mfaInput input"))
        .reduce((acc, input) => acc + input.value, "");
    try {
        const response = await fetch("${basePath}/api/mfa?code=" + mfaCode, {method: "POST"});
        if (!response.ok) {
            const body = response.json()
            throw new Error(body?.message ?? response.statusText);
        }
    } catch (err) {
        alert("MFA submission failed: " + err.msg)
    }
    setTimeout(() => navigate("${basePath}/state"), 2000);
}
 
const mfaInputs = document.querySelectorAll("#mfaInput input");
mfaInputs.forEach((input, index) => {
    input.addEventListener("input", (e) => {
        if (e.target.value.length == 1) {
            if(index < mfaInputs.length - 1) {
                mfaInputs[index + 1].focus();
            } else {
                document.querySelector("#submitButton").focus();
            }
        }
    });
 
    input.addEventListener("keydown", (e) => {
        if (e.key === "Backspace" && index > 0) {
            mfaInputs[index - 1].focus();
        }
    });
 
    input.addEventListener("focus", (e) => {
        input.value = "";
    });
});
 
document.querySelector("#mfaInput").addEventListener("paste", (e) => {
    e.preventDefault();
    const pasteData = e.clipboardData.getData("text/plain").slice(0, 6);
    if (pasteData.length === 6 && /^[0-9]+$/.test(pasteData)) {
        pasteData.split("").forEach((digit, index) => {
            if (index < mfaInputs.length) {
                mfaInputs[index].value = digit;
            }
        });
        submitMfa();
    } else {
        alert("Please paste a 6-digit numeric code.");
    }
});
`