npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@codebundlesbyvik/simple-maths-captcha

v2.1.0

Published

Easy to use, easy to solve CAPTCHA.

Readme

Simple Maths CAPTCHA

npm npm - downloads per week

Easy to use, easy to solve CAPTCHA.

simple-maths-captcha

Table of Contents

  1. Usage
  2. Browser support
  3. Instance options
  4. Methods
  5. Upgrading from 1.x.x
  6. License

Usage

# Install packages from npm
npm install @codebundlesbyvik/ntp-sync @codebundlesbyvik/simple-maths-captcha

If you're not using a module bundler then:

For the example below I assume the main JavaScript file is processed by a module bundler.

import Ntp, { convertUnixTimeFormatToMs } from "@codebundlesbyvik/ntp-sync";
import SimpleMathsCaptcha from "@codebundlesbyvik/simple-maths-captcha";

const ntp = new Ntp({
    t1EndpointUrl: "./api/ntp/get-server-time.php",
    t1CalcFn: async function (response: Response) {
        const fetchedData = (await response.json()) as unknown;

        const isValidData = (data: unknown): data is { received_time: number } =>
            typeof data === "object" && data !== null && "received_time" in data;

        return isValidData(fetchedData)
            ? convertUnixTimeFormatToMs(fetchedData.received_time)
            : null;
    },
    // Providing a t2CalcFn for greater accuracy is recommended but not required.
    t2CalcFn: function (responseHeaders: Headers) {
        // Apache header with timestamp `t` for when the request was received
        // and time it took to begin serving the requestHeader as `D`.
        // Value example: t=1747777363406069 D=110
        const header = responseHeaders.get("Response-Timing");

        if (!header) return null;

        const reqReceivedTime = /\bt=([0-9]+)\b/.exec(header);
        const reqProcessingTime = /\bD=([0-9]+)\b/.exec(header);

        if (!reqReceivedTime || !reqProcessingTime) return null;

        const respTransmitTime =
            Number.parseInt(reqReceivedTime[1]) + Number.parseInt(reqProcessingTime[1]);

        return convertUnixTimeFormatToMs(respTransmitTime);
    },
});
const captcha = new SimpleMathsCaptcha({
    activatorButtonEl: document.querySelector("#simple-maths-captcha-activator-button"),
    dataEndpointUrl: "./api/simple-maths-captcha/generate-problem.php",
    dataHandlerFn: async (response: Response) => {
        const fetchedData = (await response.json()) as unknown;

        const isValidData = (
            data: unknown,
        ): data is {
            digit_1: number;
            digit_2: number;
            generation_time: number;
            valid_for_time: number;
        } =>
            typeof data === "object" &&
            data !== null &&
            "digit_1" in data &&
            "digit_2" in data &&
            "generation_time" in data &&
            "valid_for_time" in data &&
            Object.values(data).every((value) => typeof value === "number");

        if (!isValidData(fetchedData)) return null;

        const { digit_1, digit_2, generation_time, valid_for_time } = fetchedData;

        return {
            digit1: digit_1,
            digit2: digit_2,
            generationTime: generation_time,
            validForTime: valid_for_time,
        };
    },
    ntp,
});

The CAPTCHA initializes on instance creation. On press of the activator button a NTP sync is performed after which a maths problem is requested. The problem is inserted in the DOM, alongside 3 <input>s: the main one in which the user has to provide the answer and 2 hidden ones used to store the problem's individual digits. The CAPTCHA is automatically deactivated after the invalidation time provided by the back end has passed.

The exact implementation of the back end component is up to you. If you need some inspiration you can check out how I did it in PHP for my own website.

Browser support

Requires an ECMAScript 2022 (ES13) compatible browser. Practically speaking, all browsers released in 2021 and onwards are fully supported.

Instance options

| Property | Type | Default | Description | | :------------------------------------------------------------------| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | activatorButtonEl Required | HTMLButtonElement | HTMLInputElement | - | Button which the user presses to activate the CAPTCHA. Must be a child of the <form>. | | id | string | "simple-maths-captcha" | Set as HTML id & name on the <input>s generated by the instance, after automatic addition of the <input>'s role. E.g. id: "contact-form-captcha" results in contact-form-captcha-answer added as HTML id & name to the main <input>. | | ntp Required | @codebundlesbyvik/ntp-sync instance | - | @codebundlesbyvik/ntp-sync instance used for NTP sync before problem generation. | | dataEndpointUrl Required if dataEndpoint not provided. | string | - | URL of the endpoint to retrieve the problem data from. | | dataEndpoint Required if dataEndpointUrl not provided. | @codebundlesbyvik/js-helpers fetchWithTimeout parameters | - | Parameters for the fetcher used to retrieve the problem data. | | dataHandlerFn | (response: Response) => Promise<{ digit1: number; digit2: number; validForTime: number; generationTime: number } \| [number, number, number] \| null> | undefined | Function used to process problem data.Recommended for best accuracy is to return an object with the 2 maths problem digits, a Unix timestamp in milliseconds when the problem was generated and a time in milliseconds for which the problem is valid.For backwards compatibility reasons, an array of length 3 of which the first 2 items are the maths problem digits and the final item is a Unix timestamp in milliseconds after which the problem is invalidated is also accepted. | | answerInputElClass | string | undefined | HTML class to add to the main <input>. | | answerInputElEventHandlers | addEventListener() parameters | undefined | Event handlers to add to the main <input>. | | labelElLoadingText | string | "Loading CAPTCHA" | Text shown as <label> content when loading. | | loaderEl | HTMLElement | undefined | Element to add after the <label> when loading. |

Methods

.activate()

Performs NTP sync, requests a new maths problem, inserts it and the 3 <input>s in the DOM and schedules .deactivate().

.deactivate()

Removes the <input>s from the DOM and inserts the activator button. Automatically called after invalidation time has passed.

Upgrading from 1.x.x

The following changes are breaking:

  • Added: dataHandlerFn for processing problem data endpoint response.
  • Removed: .isCaptchaEl()
  • Removed: Expiry timer element.
  • Renamed: options.generatorEndpoint > options.dataEndpoint
  • Renamed: options.labelElLoadingTextContent > options.labelElLoadingText
  • Changed: options.baseId > options.id - it's now used as ID instead of as a prefix for simple-maths-captcha.
  • Changed: Require NTP instance instead of NTP instance options.
  • Changed: Removed built-in loading spinner element in favor of options.loaderEl.
  • Changed: Undocumented but public class field visibility & mutability.

License

Mozilla Public License 2.0 © 2025 Viktor Chin-Kon-Sung