ALTCHA captcha for subscribe and message
Read use-api.md first for API basics, sessions and response formats.
A shop can switch on spam protection for the two forms anyone can send without being logged in: the newsletter subscription and the message to the shop. The client then has to solve a small proof-of-work puzzle (ALTCHA, protocol v2, PBKDF2/SHA-256) and send the solution with the form. Solving takes well under a second on a current phone; no picture puzzles, no cookies, no third party.
The switch is per shop (ShopSetup altcha, on by default) and can change at any time. A client
that posts to these endpoints should therefore always ask for a challenge first and only leave
the captcha out when the shop says it is not required. The shop components
oo-subscribe and
oo-mail do exactly that — if you use them,
you don't need this skill; their pages list what your page has to provide (HTTPS, CSP, styling).
| Endpoint | Captcha required when the shop has it switched on |
|---|---|
POST api/client/subscribe |
always |
POST api/client/message |
only for senders who are not logged in (or logged in as guest); a logged-in customer sends without it |
POST api/chat1 |
for guests (not logged in, or logged in as guest), with the question that opens a chat session - see the chat |
the flow
GET api/client/altcha→ a challenge, or{"required": false}- solve the challenge → a base64 string (the payload)
- post the form with the additional parameter
altcha=<payload> - a payload is valid for one post and for 20 minutes: get a new challenge for every send, also after a failed one
getting a challenge
GET api/client/altcha (no parameters, not cached - Cache-Control: no-store)
The shop does not use the captcha:
{"required": false}
The shop uses it - a signed challenge, exactly in the format the ALTCHA widget expects:
{
"parameters": {
"algorithm": "PBKDF2/SHA-256",
"cost": 1000,
"expiresAt": 1793704401,
"keyLength": 32,
"keyPrefix": "04bbabf57858175e7bd000463cd61014",
"nonce": "2feb6d68b65b108085ecfff90f92d522",
"salt": "6b6f49fb19f69dfd119e3a2742a63b91"
},
"signature": "85849c5631a9518331262e904322a0459483acc9b30720493a06092c550b51a6"
}
HTTP 503 {"error": "captcha not configured"} means the shop wants the captcha but the server is
not set up for it; every form will be rejected until that is fixed - report it to the shop.
A challenge belongs to the shop it was fetched from; it does not verify in another shop.
sending the solution
Add the payload as parameter altcha to the usual form parameters (not as msg_altcha - only
msg_* parameters go into the mail to the shop).
Subscribe (the fields oo-subscribe sends; name and firstname may be ANONYM):
POST api/client/subscribe
customers.email=jane@example.org&name=ANONYM&firstname=ANONYM&opener=&customers.anote=&oo-ag=0&altcha=eyJjaGFsbGVuZ2Ui...
Message from a visitor who is not logged in (msg_email is the sender's address and required
then; every further msg_* field is listed in the mail):
POST api/client/message
msg_email=jane@example.org&msg_subject=Question&msg_info=Hello...&altcha=eyJjaGFsbGVuZ2Ui...
results
Both endpoints answer HTTP 200 with the action result in the body and in the header
X-oekobox-result:
{"action": "Newsletter", "result": "captcha"}
| result | meaning |
|---|---|
sent (subscribe), mail_sent (message) |
accepted |
captcha |
the captcha was required and the payload was missing, wrong, expired or already used - fetch a new challenge and let the user try again |
NO_EMAIL (message) |
no valid sender address in msg_email |
rolist (subscribe) |
the address is on the shop's do-not-contact list |
The shop's own text for captcha is in the configuration translations: boss.subscribe.captcha,
boss.mail.captcha (e.g. "Die Sicherheitsprüfung ist fehlgeschlagen. Bitte versuche es noch einmal.").
the chat
POST api/chat1 takes the payload as altcha too, but only once per chat session: send it with
the first question (q). The web session then remembers that the chat session is solved, and later
questions go without it. After c=delete (or when the web session ended) the next question opens a
new chat session and needs a new solution.
The chat answers a rejection with HTTP 410 and the reason in the header X-oekobox-error:
X-oekobox-error |
meaning |
|---|---|
CAPTCHA |
a solution was needed and was missing, wrong, expired or already used - fetch a new challenge, solve it and send the question again |
LIMIT |
too many questions from this guest (30 per hour per web session, 100 per hour per IP address) - try again later; independent of the captcha switch |
The shop's texts: boss.chat.11 (captcha), boss.chat.12 (limit), in the configuration translations.
in the browser: the ALTCHA widget
The open source ALTCHA widget (MIT) solves the challenge
in a web worker and shows the usual "I'm not a robot" checkbox. The shop uses version 3.5.0. Hand it
the challenge you fetched yourself (configure({challenge})) instead of a challengeurl, so the
request goes through your normal API access (session, api key):
<script type="module" src="https://cdn.jsdelivr.net/npm/altcha@3.5.0/dist/main/altcha.min.js"></script>
<!-- novalidate: the widget carries a required checkbox of its own, which would stop the submit before verify() -->
<form id="subscribe" novalidate>
<input name="customers.email" type="email" required>
<altcha-widget id="captcha" hidden></altcha-widget>
<button>Subscribe</button>
</form>
<script type="module">
const SHOP = 'https://oekobox-online.de/v3/shop/<tenant>'; // <tenant>: the shop's system name
const widget = document.getElementById('captcha');
async function challenge() {
const res = await fetch(`${SHOP}/api/client/altcha`, { cache: 'no-store' });
if (!res.ok) throw new Error(`captcha challenge: HTTP ${res.status}`);
const c = await res.json();
return c.parameters ? c : null; // null: the shop does not want the captcha
}
async function prepare() {
const c = await challenge();
widget.hidden = !c;
if (!c) return;
await customElements.whenDefined('altcha-widget');
widget.reset();
widget.configure({ challenge: c, auto: 'off' });
}
document.getElementById('subscribe').addEventListener('submit', async (e) => {
e.preventDefault();
const email = e.target.elements['customers.email'];
if (!email.checkValidity()) return email.reportValidity();
const form = new URLSearchParams(new FormData(e.target));
form.delete('altcha'); // the widget adds a field of its own
for (const [k, v] of Object.entries({ name: 'ANONYM', firstname: 'ANONYM', 'oo-ag': '0' })) form.set(k, v);
if (!widget.hidden) {
const solved = await widget.verify(); // solves if not done yet
if (!solved) return alert('Security check failed, please try again.');
form.set('altcha', solved.payload);
}
const res = await fetch(`${SHOP}/api/client/subscribe`, { method: 'POST', body: form });
const { result } = await res.json();
await prepare(); // single use: a new challenge for the next send
alert(result === 'sent' ? 'Please confirm the mail we sent you.'
: result === 'captcha' ? 'Security check failed, please try again.' : `Error: ${result}`);
});
prepare();
</script>
The widget needs a secure context (HTTPS, WebCrypto); on a plain-HTTP page it can not solve.
Translations: dist/i18n/<lang>.js of the same package, then <altcha-widget language="de">.
without the widget: solving it yourself
The challenge is deterministic: the server picked a secret counter, derived a key from it and
published the first half of that key as keyPrefix. The client counts up from 0 until it finds a
counter whose key starts with keyPrefix:
password = nonce (hex-decoded bytes) + counter as 4-byte unsigned big-endian
key = PBKDF2-HMAC-SHA256(password, salt (hex-decoded bytes), iterations = cost, length = keyLength)
solved when hex(key) starts with keyPrefix
payload = base64( JSON { "challenge": <the challenge exactly as received>,
"solution": { "counter": n, "derivedKey": hex(key), "time": seconds } } )
Node 18+, no dependencies:
import { pbkdf2Sync } from 'node:crypto';
async function fetchChallenge(base) {
const res = await fetch(`${base}/api/client/altcha`, { cache: 'no-store' });
if (!res.ok) throw new Error(`challenge: HTTP ${res.status}`);
const challenge = await res.json();
return challenge.parameters ? challenge : null; // {"required": false} - send without "altcha"
}
/** Solves a PBKDF2/SHA-256 challenge and returns the value for the form parameter "altcha". */
function solve(challenge) {
const p = challenge.parameters;
if (p.algorithm !== 'PBKDF2/SHA-256') throw new Error(`unsupported algorithm ${p.algorithm}`);
const nonce = Buffer.from(p.nonce, 'hex');
const salt = Buffer.from(p.salt, 'hex');
const started = Date.now();
for (let counter = 0; counter <= 0xffffffff; counter++) {
const password = Buffer.alloc(nonce.length + 4);
nonce.copy(password);
password.writeUInt32BE(counter, nonce.length);
const key = pbkdf2Sync(password, salt, p.cost, p.keyLength, 'sha256').toString('hex');
if (key.startsWith(p.keyPrefix)) {
const solution = { counter, derivedKey: key, time: (Date.now() - started) / 1000 };
return Buffer.from(JSON.stringify({ challenge, solution })).toString('base64');
}
}
throw new Error('no solution');
}
const base = 'https://oekobox-online.de/v3/shop/<tenant>';
const challenge = await fetchChallenge(base);
const form = new URLSearchParams({ 'customers.email': 'jane@example.org', name: 'ANONYM', firstname: 'ANONYM', 'oo-ag': '0' });
if (challenge) form.set('altcha', solve(challenge));
const res = await fetch(`${base}/api/client/subscribe`, { method: 'POST', body: form });
console.log(await res.json()); // {"action": "Newsletter", "result": "sent"}
The same works in any language with PBKDF2 (PHP hash_pbkdf2, Python hashlib.pbkdf2_hmac, Java
org.altcha:altcha Altcha.solveChallenge). Solving on a server is fine for a trusted
integration; it is not meant to let a public form skip the work - every payload is single-use.
related
- new-customer-registration.md - registration (
api/client/newclient1) is not covered by the captcha - feature description:
docs/features/FEATURE_SPAM_PROTECTION_ALTCHA.mdin the obox repository