geronimo-captcha 2.0.0

A JavaScript-free CAPTCHA for Rust. A speed bump for bulk automation, layered over server-side rate limiting. Not a wall.
Documentation
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use crate::image::warp_tile;
use crate::{CaptchaError, GenerationOptions};

use ab_glyph::{FontArc, InvalidFont, PxScale};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
use image::{GenericImage, ImageBuffer, ImageReader, Limits, Rgba, RgbaImage, imageops};
use imageproc::drawing::draw_text_mut;
use rand::prelude::SliceRandom;
use rand::rngs::ThreadRng;
use rand::{RngExt, rng};
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use std::io::Cursor;
use std::sync::LazyLock;

static FONT: LazyLock<Result<FontArc, InvalidFont>> =
    LazyLock::new(|| FontArc::try_from_slice(include_bytes!("../assets/Roboto-Bold.ttf")));

pub(crate) const SPRITE_BG: Rgba<u8> = Rgba([255, 255, 255, 255]);

const COLS: u32 = 3;
const ROWS: u32 = 3;
const SPACING: u32 = 4;
const TILES: usize = (COLS * ROWS) as usize;

const UPRIGHT_JITTER_DEG: f32 = 5.0;
const MIN_TILE_SCALE: f32 = 0.5;
const MAX_TILE_SCALE: f32 = 0.8;

const INCORRECT_ANGLES: [f32; 11] = [
    38.0, 88.0, 114.0, 138.0, 176.0, 200.0, 229.0, 255.0, 278.0, 314.0, 320.0,
];

const LABELS: [&str; TILES] = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

/// Destination for the encoded sprite bytes.
pub trait SpriteTarget: Sized {
    fn from_bytes(bytes: Vec<u8>, mime: &'static str) -> Self;
}

/// Sprite as a `data:` URI, ready for `<img src>`.
pub struct SpriteUri(pub String);

impl SpriteTarget for SpriteUri {
    fn from_bytes(bytes: Vec<u8>, mime: &'static str) -> Self {
        SpriteUri(sprite_to_base64(&bytes, mime))
    }
}

/// Sprite as raw encoded bytes plus its MIME type.
pub struct SpriteBinary {
    pub bytes: Vec<u8>,
    pub mime: &'static str,
}

impl SpriteTarget for SpriteBinary {
    fn from_bytes(bytes: Vec<u8>, mime: &'static str) -> Self {
        SpriteBinary { bytes, mime }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum SpriteFormat {
    Jpeg { quality: u8 },
    Webp { quality: u8, lossless: bool },
}

impl Default for SpriteFormat {
    fn default() -> Self {
        SpriteFormat::Jpeg { quality: 70 }
    }
}

impl SpriteFormat {
    pub(crate) fn quality(&self) -> u8 {
        match *self {
            SpriteFormat::Jpeg { quality } => quality,
            SpriteFormat::Webp { quality, .. } => quality,
        }
    }
}

#[derive(Clone, Copy)]
struct Tile {
    angle: f32,
    scale: f32,
    flip: bool,
    correct: bool,
}

pub fn decode_base(
    base_buf: &[u8],
    format: image::ImageFormat,
    opts: &GenerationOptions,
) -> crate::Result<RgbaImage> {
    let mut limits = Limits::default();
    limits.max_image_width = Some(opts.limits.max_width);
    limits.max_image_height = Some(opts.limits.max_height);
    limits.max_alloc = Some(opts.limits.max_alloc);

    let mut reader = ImageReader::with_format(Cursor::new(base_buf), format);
    reader.limits(limits);

    Ok(reader
        .decode()
        .map_err(CaptchaError::Decode)?
        .resize_exact(
            opts.cell_size,
            opts.cell_size,
            imageops::FilterType::Nearest,
        )
        .into_rgba8())
}

pub fn create_sprite(base: &RgbaImage, opts: &GenerationOptions) -> crate::Result<(RgbaImage, u8)> {
    let font = font()?;
    let mut rng = rng();

    let mut wrong = INCORRECT_ANGLES;
    wrong.shuffle(&mut rng);

    let mut tiles = [Tile {
        angle: 0.0,
        scale: 0.0,
        flip: false,
        correct: false,
    }; TILES];

    for (i, tile) in tiles.iter_mut().enumerate() {
        tile.angle = match i {
            0 => rng.random_range(-UPRIGHT_JITTER_DEG..=UPRIGHT_JITTER_DEG),
            _ => wrong[i - 1],
        };
        tile.scale = rng.random_range(MIN_TILE_SCALE..=MAX_TILE_SCALE);
        tile.flip = rng.random_bool(0.5);
        tile.correct = i == 0;
    }

    tiles.shuffle(&mut rng);

    let sprite_width = COLS * opts.cell_size + (COLS - 1) * SPACING;
    let sprite_height = ROWS * opts.cell_size + (ROWS - 1) * SPACING;

    let mut sprite = ImageBuffer::from_pixel(sprite_width, sprite_height, SPRITE_BG);
    let mut correct_number = 0;

    #[cfg(feature = "parallel")]
    let rendered = tiles
        .par_iter()
        .map(|tile| {
            let mut out = RgbaImage::new(0, 0);
            render_tile(base, *tile, opts.cell_size, &mut out).map(|()| out)
        })
        .collect::<crate::Result<Vec<_>>>()?;

    #[cfg(not(feature = "parallel"))]
    let mut scratch = RgbaImage::new(0, 0);

    for (i, tile) in tiles.iter().enumerate() {
        #[cfg(feature = "parallel")]
        let rendered = rendered
            .get(i)
            .ok_or_else(|| CaptchaError::Internal(format!("tile {i} was not rendered")))?;

        #[cfg(not(feature = "parallel"))]
        let rendered = {
            render_tile(base, *tile, opts.cell_size, &mut scratch)?;
            &scratch
        };

        place_tile(&mut sprite, rendered, i, opts.cell_size, &mut rng, font)?;

        if tile.correct {
            correct_number = (i + 1) as u8;
        }
    }

    Ok((sprite, correct_number))
}

fn render_tile(
    base: &RgbaImage,
    tile: Tile,
    cell_size: u32,
    out: &mut RgbaImage,
) -> crate::Result<()> {
    let size = (cell_size as f32 * tile.scale) as u32;

    let mut raw = std::mem::replace(out, RgbaImage::new(0, 0)).into_raw();
    raw.resize(size as usize * size as usize * 4, 0);

    *out = RgbaImage::from_raw(size, size, raw)
        .ok_or_else(|| CaptchaError::Internal("tile buffer does not fit its dimensions".into()))?;

    warp_tile(base, tile.angle, tile.flip, SPRITE_BG, out);

    Ok(())
}

fn place_tile(
    sprite: &mut RgbaImage,
    tile: &RgbaImage,
    index: usize,
    cell_size: u32,
    rng: &mut ThreadRng,
    font: &FontArc,
) -> crate::Result<()> {
    let size = tile.width();

    let col = index as u32 % COLS;
    let row = index as u32 / COLS;

    let base_x = col * (cell_size + SPACING);
    let base_y = row * (cell_size + SPACING);

    let offset = (cell_size - size) / 2;
    let jitter_limit = offset as i32;

    let draw_x =
        (base_x + offset).saturating_add_signed(rng.random_range(-jitter_limit..=jitter_limit));
    let draw_y =
        (base_y + offset).saturating_add_signed(rng.random_range(-jitter_limit..=jitter_limit));

    sprite
        .copy_from(tile, draw_x, draw_y)
        .map_err(|e| CaptchaError::Internal(format!("copy tile into sprite buffer: {e}")))?;

    let label_x = draw_x.saturating_add(size).saturating_sub(16);
    let label_y = draw_y.saturating_add(size).saturating_sub(16);

    let scale = PxScale::from(cell_size as f32 * rng.random_range(0.13..=0.17));
    let color = Rgba([
        rng.random_range(0..100),
        rng.random_range(0..100),
        rng.random_range(0..100),
        255,
    ]);

    draw_text_mut(
        sprite,
        color,
        (label_x + rng.random_range(0..=3)) as i32,
        (label_y + rng.random_range(0..=3)) as i32,
        scale,
        font,
        LABELS[index],
    );

    Ok(())
}

fn sprite_to_base64(buf: &[u8], mime: &str) -> String {
    const PREFIX: &str = "data:";
    const INFIX: &str = ";base64,";

    let mut uri =
        String::with_capacity(PREFIX.len() + mime.len() + INFIX.len() + buf.len().div_ceil(3) * 4);

    uri.push_str(PREFIX);
    uri.push_str(mime);
    uri.push_str(INFIX);

    BASE64_STANDARD.encode_string(buf, &mut uri);

    uri
}

fn font() -> crate::Result<&'static FontArc> {
    FONT.as_ref()
        .map_err(|e| CaptchaError::Internal(format!("load embedded font: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::challenge::{DecodeLimits, generate};
    use crate::image::NoiseOptions;

    const SECRET: &[u8] = b"unit-test-secret-key-32-bytes-min!!";

    fn opts(cell_size: u32, sprite_format: SpriteFormat) -> GenerationOptions {
        GenerationOptions {
            cell_size,
            sprite_format,
            rounds: 1,
            limits: DecodeLimits::default(),
        }
    }

    fn load_base(opts: &GenerationOptions) -> RgbaImage {
        decode_base(
            include_bytes!("../assets/sample1.jpg"),
            image::ImageFormat::Jpeg,
            opts,
        )
        .expect("decode sample")
    }

    fn decode(bytes: &[u8]) {
        ImageReader::new(Cursor::new(bytes))
            .with_guessed_format()
            .expect("guess format")
            .decode()
            .expect("decode sprite");
    }

    fn payload(uri: &str) -> Vec<u8> {
        let b64 = uri.split_once(',').map(|x| x.1).expect("data uri payload");
        BASE64_STANDARD.decode(b64).expect("base64 decode")
    }

    #[test]
    fn sprite_prefix_jpeg_and_decode() {
        let o = opts(120, SpriteFormat::Jpeg { quality: 60 });
        let base = load_base(&o);

        let ch = generate::<SpriteUri>(
            std::slice::from_ref(&base),
            SECRET,
            &o,
            NoiseOptions::default(),
        )
        .expect("jpeg generation failed");

        assert_eq!(ch.sprites.len(), 1);
        assert!(ch.sprites[0].0.starts_with("data:image/jpeg;base64,"));

        decode(&payload(&ch.sprites[0].0));
    }

    #[test]
    fn sprite_prefix_webp_and_decode() {
        let o = opts(
            120,
            SpriteFormat::Webp {
                quality: 75,
                lossless: false,
            },
        );

        let base = load_base(&o);
        let ch = generate::<SpriteUri>(
            std::slice::from_ref(&base),
            SECRET,
            &o,
            NoiseOptions::default(),
        )
        .expect("webp generation failed");

        assert!(ch.sprites[0].0.starts_with("data:image/webp;base64,"));

        decode(&payload(&ch.sprites[0].0));
    }

    #[test]
    fn sprite_binary_jpeg_and_decode() {
        let o = opts(150, SpriteFormat::Jpeg { quality: 70 });
        let base = load_base(&o);

        let ch = generate::<SpriteBinary>(
            std::slice::from_ref(&base),
            SECRET,
            &o,
            NoiseOptions::default(),
        )
        .expect("jpeg binary generation failed");

        assert_eq!(ch.sprites[0].mime, "image/jpeg");
        assert!(!ch.sprites[0].bytes.is_empty());

        decode(&ch.sprites[0].bytes);
    }

    #[test]
    fn sprite_binary_webp_and_decode() {
        let o = opts(
            150,
            SpriteFormat::Webp {
                quality: 70,
                lossless: false,
            },
        );

        let base = load_base(&o);
        let ch = generate::<SpriteBinary>(
            std::slice::from_ref(&base),
            SECRET,
            &o,
            NoiseOptions::default(),
        )
        .expect("webp binary generation failed");

        assert_eq!(ch.sprites[0].mime, "image/webp");
        assert!(!ch.sprites[0].bytes.is_empty());

        decode(&ch.sprites[0].bytes);
    }

    #[test]
    fn tile_silhouette_is_angle_independent() {
        let base_size = 64;
        let fill = Rgba([10, 20, 30, 255]);
        let base = RgbaImage::from_pixel(base_size, base_size, fill);

        let size = 41;
        let corners = [
            (0, 0),
            (size - 1, 0),
            (0, size - 1),
            (size - 1, size - 1),
            (size / 2, 0),
        ];

        let mut areas = Vec::new();
        for angle in [0.0, 3.0, -4.9, 38.0, 88.0, 138.0, 176.0, 278.0, 320.0] {
            for flip in [false, true] {
                let mut tile = RgbaImage::new(size, size);
                warp_tile(&base, angle, flip, SPRITE_BG, &mut tile);

                for (x, y) in corners {
                    assert_eq!(
                        *tile.get_pixel(x, y),
                        SPRITE_BG,
                        "angle {angle} flip {flip} leaves tile content at ({x}, {y})"
                    );
                }

                assert_eq!(*tile.get_pixel(size / 2, size / 2), fill);

                areas.push(tile.pixels().filter(|p| **p != SPRITE_BG).count());
            }
        }

        assert!(
            areas.windows(2).all(|w| w[0] == w[1]),
            "tile area varies with angle or flip, silhouette leaks the answer: {areas:?}"
        );
    }

    #[test]
    fn render_tile_reuses_scratch_capacity() {
        let o = opts(80, SpriteFormat::Jpeg { quality: 70 });
        let base = load_base(&o);

        let mut scratch = RgbaImage::new(0, 0);
        let mut capacities = Vec::new();

        for scale in [MAX_TILE_SCALE, MIN_TILE_SCALE, 0.65, MAX_TILE_SCALE] {
            let tile = Tile {
                angle: 38.0,
                scale,
                flip: false,
                correct: false,
            };

            render_tile(&base, tile, o.cell_size, &mut scratch).expect("render");

            let expected = (o.cell_size as f32 * scale) as u32;
            assert_eq!(scratch.dimensions(), (expected, expected));

            capacities.push(scratch.as_raw().capacity());
        }

        assert!(
            capacities.windows(2).all(|w| w[0] == w[1]),
            "scratch reallocated between tiles: {capacities:?}"
        );
    }

    #[test]
    fn noise_blends_without_writing_alpha() {
        let o = opts(80, SpriteFormat::Jpeg { quality: 70 });
        let base = load_base(&o);

        let (sprite, _) = create_sprite(&base, &o).expect("sprite");

        let mut noised = sprite.clone();
        crate::image::watermark_with_noise(&mut noised, NoiseOptions::default());

        let alpha_before: Vec<u8> = sprite.pixels().map(|p| p.0[3]).collect();
        let alpha_after: Vec<u8> = noised.pixels().map(|p| p.0[3]).collect();

        assert_eq!(
            alpha_before, alpha_after,
            "noise must blend, never write into the alpha channel"
        );
        assert_ne!(
            sprite.as_raw(),
            noised.as_raw(),
            "noise must actually modify the sprite"
        );
    }

    #[test]
    fn correct_number_is_within_grid() {
        let o = opts(80, SpriteFormat::Jpeg { quality: 70 });
        let base = load_base(&o);

        for _ in 0..16 {
            let (_, correct) = create_sprite(&base, &o).expect("sprite");
            assert!(
                (1..=9).contains(&correct),
                "correct number {correct} out of grid"
            );
        }
    }
}