aboutsummaryrefslogtreecommitdiff
/* SPDX-License-Identifier: CC0-1.0
 *
 * Use Hacktcha on Stack Exchange registration page.
 *
 * Copyright (C) 2022 Wojtek Kosior
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the CC0 1.0 Universal License as published by
 * the Creative Commons Corporation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * CC0 1.0 Universal License for more details.
 */

/* Use with https://meta.stackexchange.com/users/signup */

/* Load captcha-parent.js first. */

(async () => {
    const captcha_div = document.createElement("div");
    const submit_but  = document.getElementById("submit-button");
    const token_field = document.createElement("textarea");

    /*
     * Let's remove <noscript> tag with the original reCAPTCHA iframe and an
     * unnecessary button.
     */
    document.querySelector("#no-captcha-here + *").remove();
    for (const elem of [...captcha_div.childNodes])
        elem.remove();

    token_field.name = "g-recaptcha-response";
    token_field.style.display = "none";

    document.getElementById("no-captcha-here").after(token_field);
    token_field.after(captcha_div);

    /*
     * The reCAPTCHA site key is present in 2 places: in a script and in fallback iframe's
     * URL. Let's use the former as the source for now.
     */
    let site_key;
    const site_key_regex = /['"]sitekey['"]\s*:\s*['"]([a-zA-Z0-9-]+)['"]/;

    for (const script of document.scripts) {
        match = site_key_regex.exec(script.textContent);
        if (match !== null)
            site_key = match[1];
    }

    if (site_key === null) {
        console.error("Could not extract site key :(");
        return;
    }

    submit_but.setAttribute("disabled", "");

    for await (const token of HCHA.run(captcha_div, site_key)) {
	if (token === null) {
	    submit_but.setAttribute("disabled", "");
	} else {
	    token_field.value = token;
	    submit_but.removeAttribute("disabled");
	}
    }
})();