laracaptcha 0.1.0

Driver-based captcha for Laravel Rust: Cloudflare Turnstile and Google reCAPTCHA v2 and v3 behind one API.
Documentation
use crate::contracts::CaptchaDriver;
use crate::manager::CaptchaManager;
use crate::support::escape;

/// The script that draws every widget on the page, once each, whenever one appears: on load, after
/// `wire:navigate` and after every Livewire update. The same script as the PHP package's loader.
pub const LOADER: &str = include_str!("../resources/loader.js");

/// Run when a bound widget enters the page. Kept for parity with PHP's `Widget::BOOT`; Laravel Rust
/// has no Livewire, so the Rust widget never binds a property.
pub const BOOT: &str = "window.Laracaptcha ? window.Laracaptcha.scan() : document.querySelectorAll('script[data-laracaptcha-loader]').forEach(function (s) { var c = document.createElement('script'); c.textContent = s.textContent; document.head.appendChild(c); })";

/// `laracaptcha_widget(...)`: the provider's challenge, drawn in place.
///
/// Every widget is rendered explicitly by the package's own script rather than by the provider
/// scanning the page once on load. A scan on load misses every widget that arrives later, such as a
/// form step a page update reveals. `defer` holds a widget back from that drawing pass until the
/// page asks for it with `Laracaptcha.draw(...)`: it is for a widget that sits in markup present
/// from the start but hidden, a modal for instance.
#[derive(Debug, Clone, Default)]
pub struct Widget {
    /// A configured driver name, the default when `None`.
    pub driver: Option<String>,
    /// Signed into the token (Turnstile, reCAPTCHA v3), for the rule to compare.
    pub action: Option<String>,
    /// `auto`, `light` or `dark`. Defaults to `auto` when `None`.
    pub theme: Option<String>,
    /// The provider's size (`normal`, `compact`, `flexible`...).
    pub size: Option<String>,
    /// Turnstile's language, `auto` (the browser's) when `None`.
    pub language: Option<String>,
    /// Leave it undrawn until `Laracaptcha.draw(...)` asks for it.
    pub defer: bool,
    /// Extra attributes for the element, such as `class`. A `class` is merged after the provider's
    /// own class, as Blade's `merge` does.
    pub attributes: Vec<(String, String)>,
}

impl Widget {
    /// The markup of the widget, without the loader.
    ///
    /// Empty when the driver needs no script, which is how the fake renders nothing.
    ///
    /// # Errors
    ///
    /// Fails when the driver does not exist.
    pub fn render(&self, manager: &CaptchaManager) -> laravel::Result<String> {
        let captcha = manager.driver(self.driver.as_deref())?;

        Ok(self.markup(captcha.as_ref()))
    }

    pub(crate) fn markup(&self, captcha: &dyn CaptchaDriver) -> String {
        let script = CaptchaManager::script(captcha);

        if script.is_empty() {
            return String::new();
        }

        let provider = captcha.name();
        let theme = self.theme.as_deref().unwrap_or("auto");
        let action = CaptchaManager::action(captcha, self.action.as_deref());
        let defer = if self.defer { " data-laracaptcha-defer" } else { "" };

        if provider == "recaptcha_v3" {
            let attributes: String = self
                .attributes
                .iter()
                .map(|(name, value)| format!(" {}=\"{}\"", escape(name), escape(value)))
                .collect();

            return format!(
                "<input type=\"hidden\" name=\"{field}\" value=\"\"{attributes} data-laracaptcha=\"recaptcha_v3\" data-script=\"{script}\" data-sitekey=\"{key}\" data-action=\"{action}\" data-laracaptcha-v3{defer}>",
                field = escape(&captcha.response_field()),
                script = escape(&script),
                key = escape(&captcha.site_key()),
                action = escape(action.as_deref().unwrap_or_default()),
            );
        }

        let theme = if provider == "turnstile" {
            theme
        } else if theme == "dark" {
            "dark"
        } else {
            "light"
        };

        let base = if provider == "turnstile" {
            "cf-turnstile"
        } else {
            "g-recaptcha"
        };
        let mut class = base.to_owned();
        let mut attributes = String::new();

        for (name, value) in &self.attributes {
            if name == "class" {
                class = format!("{base} {value}");
            } else {
                attributes.push_str(&format!(" {}=\"{}\"", escape(name), escape(value)));
            }
        }

        let mut html = format!(
            "<div class=\"{class}\"{attributes} data-laracaptcha=\"{provider}\" data-script=\"{script}\" data-sitekey=\"{key}\" data-theme=\"{theme}\"",
            class = escape(&class),
            provider = escape(provider),
            script = escape(&script),
            key = escape(&captcha.site_key()),
            theme = escape(theme),
        );

        if let Some(size) = self.size.as_deref().filter(|size| !size.is_empty()) {
            html.push_str(&format!(" data-size=\"{}\"", escape(size)));
        }

        if let Some(action) = action.as_deref().filter(|action| !action.is_empty()) {
            html.push_str(&format!(" data-action=\"{}\"", escape(action)));
        }

        if let Some(language) = self.language.as_deref().filter(|language| !language.is_empty()) {
            html.push_str(&format!(" data-language=\"{}\"", escape(language)));
        }

        html.push_str(defer);
        html.push_str("></div>");

        html
    }
}

/// The loader script tag, which a page needs once however many widgets it draws.
pub fn loader() -> String {
    format!("<script data-navigate-once data-laracaptcha-loader>\n{LOADER}</script>")
}