@codebundlesbyvik/simple-maths-captcha
v2.1.0
Published
Easy to use, easy to solve CAPTCHA.
Maintainers
Readme
Simple Maths CAPTCHA
Easy to use, easy to solve CAPTCHA.
Table of Contents
Usage
# Install packages from npm
npm install @codebundlesbyvik/ntp-sync @codebundlesbyvik/simple-maths-captchaIf you're not using a module bundler then:
- Download the latest
@codebundlesbyvik/js-helpersrelease from GitHub or load it directly via jsdelivr. - Download the latest
@codebundlesbyvik/ntp-syncrelease from GitHub or load it directly via jsdelivr. - Download the latest
@codebundlesbyvik/simple-maths-captcharelease from GitHub or load it directly via jsdelivr.
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:
dataHandlerFnfor 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 forsimple-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
