laravel_rust_captcha/lib.rs
1//! Self-hosted image captcha for [Laravel for Rust](https://github.com/laravel/rust-framework), based on
2//! the PHP package [mews/captcha](https://github.com/mewebstudio/captcha) (MIT). Community package, not
3//! affiliated with Laravel.
4//!
5//! It covers what mews/captcha does (profiles, the image and JSON routes, session and keyed checks, math
6//! captchas, every drawing option, the helpers and the rules) and fixes its weak points: an opaque id per
7//! challenge, at most one pass per challenge even under concurrency, nothing secret on the client, an
8//! HMAC instead of bcrypt per image, escaped HTML, and limits on image generation.
9//!
10//! ```
11//! use laravel::Application;
12//! use laravel_rust_captcha::{CaptchaConfig, CaptchaServiceProvider, Profile};
13//!
14//! let _builder = Application::configure()
15//! .with_providers(|providers| {
16//! providers.add(CaptchaServiceProvider::new());
17//! })
18//! .with_middleware(|middleware, config| {
19//! CaptchaServiceProvider::configure_input(middleware, config, &[]);
20//! })
21//! .with_config(|config, _| {
22//! config.section_mut::<CaptchaConfig>().profile("contact", Profile::default().length(5u32).size(180, 54));
23//! });
24//! ```
25//!
26//! # Database cache stores
27//!
28//! In production, database cache stores require `CAPTCHA_TRUST_STORE=true`, the `database` feature and a writer-only cache
29//! connection. SQLite needs its own file, even when the app uses a different connection name. See [Laravel's database cache replica reads](https://github.com/laravel/rust-framework/issues/847).
30//! Enable `database-sqlite` to turn on these checks and Laravel's SQLite driver together. Laravel 0.2
31//! requires at least one driver when its database feature is enabled. See [Laravel's driverless database build](https://github.com/laravel/rust-framework/issues/846).
32
33mod assets;
34mod challenge;
35mod color;
36mod config;
37mod html;
38mod http;
39mod input;
40mod manager;
41mod provider;
42mod render;
43mod rule;
44mod store;
45pub mod testing;
46mod verifier;
47#[cfg(feature = "minijinja")]
48mod views;
49
50use std::net::IpAddr;
51
52pub use crate::assets::AssetSet;
53pub use crate::challenge::{Error, Verdict};
54pub use crate::config::{Assets, Attempts, CaptchaConfig, Characters, ConfigError, ImageFormat, Profile, Profiles};
55pub use crate::http::{api, image};
56pub use crate::manager::{CaptchaManager, Challenge, IssuedImage};
57pub use crate::provider::CaptchaServiceProvider;
58pub use crate::render::{DefaultRenderer, Image, RenderInput, Renderer, draw, encode};
59pub use crate::rule::Captcha;
60pub use crate::verifier::{LABEL as VERIFIER_LABEL, MAX_INPUT_BYTES, normalize};
61
62use laravel::http::Request;
63use laravel::session::Session;
64
65/// The image URL for a profile. PHP: `captcha_src($config)`.
66#[must_use]
67pub fn src(profile: &str) -> String {
68 let config = laravel::config().section::<CaptchaConfig>().clone();
69 let path = config.path.trim_matches('/').to_owned();
70 format!(
71 "{}?{}",
72 laravel::url::to(&format!("/{path}/{profile}")),
73 laravel::str::random(8)
74 )
75}
76
77/// An escaped `<img>` tag for a profile's image. PHP: `captcha_img($config, $attrs)`.
78#[must_use]
79pub fn img<'a, I>(profile: &str, attrs: I) -> String
80where
81 I: IntoIterator<Item = (&'a str, &'a str)>,
82{
83 html::img_tag(&src(profile), attrs)
84}
85
86/// Issues a keyed challenge for a handler to pass to a view or an Inertia page. PHP:
87/// `Captcha::create($config, true)`.
88///
89/// # Errors
90///
91/// Unknown profile, too many images from this client, a busy renderer, or a store failure.
92pub async fn issue(request: &Request, profile: &str) -> laravel::Result<Challenge> {
93 laravel::resolve::<CaptchaManager>()
94 .await?
95 .issue(request.ip(), profile)
96 .await
97 .map_err(Error::into_http)
98}
99
100/// Checks an answer against the session's current challenge for `profile`. PHP: `captcha_check($value)`.
101///
102/// # Errors
103///
104/// The request has no session, or the store failed (the check fails closed).
105pub async fn check(request: &Request, profile: &str, value: &str) -> laravel::Result<Verdict> {
106 let session: &Session = request.session().map_err(|_| Error::NoSession.into_http())?;
107 laravel::resolve::<CaptchaManager>()
108 .await?
109 .check(session, request.ip(), profile, value)
110 .await
111 .map_err(Error::into_http)
112}
113
114/// Checks an answer against a keyed challenge. PHP: `captcha_api_check($value, $key, $config)`.
115///
116/// # Errors
117///
118/// The store failed (the check fails closed).
119pub async fn check_keyed(client: IpAddr, key: &str, profile: &str, value: &str) -> laravel::Result<Verdict> {
120 laravel::resolve::<CaptchaManager>()
121 .await?
122 .check_keyed(client, key, profile, value)
123 .await
124 .map_err(Error::into_http)
125}