@mistriwork/challenge-turnstile 0.0.1 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +62 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +57 -0
- package/dist/stub.d.ts +25 -0
- package/dist/stub.js +119 -0
- package/package.json +42 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Baljinder Randhawa
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# `@mistriwork/challenge-turnstile`
|
|
2
|
+
|
|
3
|
+
Cloudflare Turnstile human-check pack for [mistri](https://mistriwork.dev) Apps' public doors (`auth.challenge`), with a local loopback stub for automated node and browser tests and zero external dependencies.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @mistriwork/challenge-turnstile
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Declare the verifier in your App's `commands.ts`:
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { defineChallenges } from '@mistriwork/mistri/commands';
|
|
17
|
+
import { turnstile } from '@mistriwork/challenge-turnstile';
|
|
18
|
+
|
|
19
|
+
export const challenges = defineChallenges({
|
|
20
|
+
verifyHuman: turnstile({
|
|
21
|
+
siteKey: process.env.TURNSTILE_SITE_KEY!,
|
|
22
|
+
secret: process.env.TURNSTILE_SECRET!,
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Then enable it in `app.ts`:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
auth: {
|
|
31
|
+
challenge: 'verifyHuman',
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Local Testing (`turnstileStub`)
|
|
36
|
+
|
|
37
|
+
Use `turnstileStub()` in node and Playwright tests to run a local loopback siteverify endpoint and widget script without hitting Cloudflare:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { turnstile, turnstileStub } from '@mistriwork/challenge-turnstile';
|
|
41
|
+
|
|
42
|
+
const stub = await turnstileStub();
|
|
43
|
+
const verifyHuman = turnstile({
|
|
44
|
+
siteKey: 'test-site-key',
|
|
45
|
+
secret: stub.secret,
|
|
46
|
+
verifyUrl: stub.verifyUrl,
|
|
47
|
+
scriptUrl: stub.scriptUrl,
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Options (`TurnstileOptions`)
|
|
52
|
+
|
|
53
|
+
| Option | Description |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| `siteKey` | Public Turnstile site key rendered in the browser widget. |
|
|
56
|
+
| `secret` | Server-side secret key sent to Cloudflare siteverify (never exposed to the client). |
|
|
57
|
+
| `hostnames` | Allowed hostnames for issued tokens (defaults to the request's `Host`). |
|
|
58
|
+
| `action` | Expected Turnstile widget action name. |
|
|
59
|
+
| `timeoutMs` | Verification request timeout in milliseconds (default `4000`). |
|
|
60
|
+
| `verifyUrl` | Custom siteverify URL (for `turnstileStub()`). |
|
|
61
|
+
| `scriptUrl` | Custom widget script URL (for `turnstileStub()`). |
|
|
62
|
+
| `fetch` | Custom `fetch` implementation for unit tests. |
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @mistriwork/challenge-turnstile: Cloudflare Turnstile as the human check an App's public doors ask (`auth.challenge`).
|
|
3
|
+
*
|
|
4
|
+
* Core ships the seam only (packages/mistri/src/server/commands/challenges.ts): a named verifier the commands module
|
|
5
|
+
* exports, asked before a public form's submit or a public page's command is read, and a slot in the stock public
|
|
6
|
+
* form that draws the verifier's widget. This pack is one such verifier — it never reads a row, and core never
|
|
7
|
+
* imports it:
|
|
8
|
+
*
|
|
9
|
+
* import { defineChallenges } from '@mistriwork/mistri/commands';
|
|
10
|
+
* import { turnstile } from '@mistriwork/challenge-turnstile';
|
|
11
|
+
* export const challenges = defineChallenges({
|
|
12
|
+
* verifyHuman: turnstile({ siteKey: process.env.TURNSTILE_SITE_KEY!, secret: process.env.TURNSTILE_SECRET! }),
|
|
13
|
+
* });
|
|
14
|
+
*
|
|
15
|
+
* `turnstileStub()` (./stub.ts) stands in for Cloudflare in a test: a local siteverify and a widget script, so a
|
|
16
|
+
* test — node or browser — makes no live call.
|
|
17
|
+
*/
|
|
18
|
+
import type { HumanCheck } from '@mistriwork/mistri/commands';
|
|
19
|
+
export { turnstileStub } from './stub.js';
|
|
20
|
+
export type { TurnstileStub, TurnstileStubOptions } from './stub.js';
|
|
21
|
+
/** Cloudflare's: where a token is verified, and the widget's script, rendered explicitly into the form's slot. */
|
|
22
|
+
export declare const TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
|
23
|
+
export declare const TURNSTILE_SCRIPT_URL = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
|
24
|
+
export interface TurnstileOptions {
|
|
25
|
+
/** The widget's public key: drawn in the page, so it is no secret. */
|
|
26
|
+
siteKey: string;
|
|
27
|
+
/** The secret siteverify takes. Read it from the environment; it is never sent to the browser. */
|
|
28
|
+
secret: string;
|
|
29
|
+
/** The host names a token may have been issued on; any other is a no. Absent: the host the request was made to
|
|
30
|
+
(`ChallengeRequest.host`), so a token solved on another site is refused. Name them where a proxy rewrites the
|
|
31
|
+
Host, or where Cloudflare's testing keys answer with a host of their own. */
|
|
32
|
+
hostnames?: readonly string[];
|
|
33
|
+
/** The widget's `action`, where the App sets one: drawn into the stock form's widget, and a token issued for
|
|
34
|
+
another is a no. */
|
|
35
|
+
action?: string;
|
|
36
|
+
/** How long siteverify is waited on, in milliseconds (default 4000, under core's own 5 s deadline). */
|
|
37
|
+
timeoutMs?: number;
|
|
38
|
+
/** For a test: another siteverify (`turnstileStub().verifyUrl`) and another widget script. */
|
|
39
|
+
verifyUrl?: string;
|
|
40
|
+
scriptUrl?: string;
|
|
41
|
+
/** For a test: the fetch siteverify is asked with. */
|
|
42
|
+
fetch?: typeof fetch;
|
|
43
|
+
}
|
|
44
|
+
/** A Turnstile verifier for `defineChallenges`. */
|
|
45
|
+
export declare function turnstile(options: TurnstileOptions): HumanCheck;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export { turnstileStub } from './stub.js';
|
|
2
|
+
/** Cloudflare's: where a token is verified, and the widget's script, rendered explicitly into the form's slot. */
|
|
3
|
+
export const TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
|
|
4
|
+
export const TURNSTILE_SCRIPT_URL = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
|
|
5
|
+
/** A Turnstile token is at most 2048 characters (Cloudflare's documentation); a longer one is not asked about. */
|
|
6
|
+
const TOKEN_MOST = 2048;
|
|
7
|
+
function required(value, name) {
|
|
8
|
+
if (typeof value !== 'string' || !value.trim())
|
|
9
|
+
throw new TypeError(`turnstile({ ${name} }) is a non-empty string.`);
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
/** A Turnstile verifier for `defineChallenges`. */
|
|
13
|
+
export function turnstile(options) {
|
|
14
|
+
const siteKey = required(options?.siteKey, 'siteKey');
|
|
15
|
+
const secret = required(options.secret, 'secret');
|
|
16
|
+
const verifyUrl = options.verifyUrl ?? TURNSTILE_VERIFY_URL;
|
|
17
|
+
const timeoutMs = options.timeoutMs ?? 4_000;
|
|
18
|
+
const hostnames = options.hostnames ? new Set(options.hostnames.map((name) => name.toLowerCase())) : undefined;
|
|
19
|
+
const ask = options.fetch ?? fetch;
|
|
20
|
+
return {
|
|
21
|
+
widget: {
|
|
22
|
+
script: options.scriptUrl ?? TURNSTILE_SCRIPT_URL,
|
|
23
|
+
api: 'turnstile',
|
|
24
|
+
siteKey,
|
|
25
|
+
...(options.action ? { action: options.action } : {}),
|
|
26
|
+
},
|
|
27
|
+
async verify(token, request) {
|
|
28
|
+
if (typeof token !== 'string' || !token || token.length > TOKEN_MOST)
|
|
29
|
+
return false;
|
|
30
|
+
let answer;
|
|
31
|
+
try {
|
|
32
|
+
const response = await ask(verifyUrl, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: { 'content-type': 'application/json' },
|
|
35
|
+
body: JSON.stringify({ secret, response: token, ...(request?.ip ? { remoteip: request.ip } : {}) }),
|
|
36
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
37
|
+
redirect: 'error',
|
|
38
|
+
});
|
|
39
|
+
if (!response.ok)
|
|
40
|
+
return false;
|
|
41
|
+
answer = (await response.json());
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// Cloudflare unreachable, slow or answering nonsense: not a person we could confirm.
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
if (answer?.success !== true)
|
|
48
|
+
return false;
|
|
49
|
+
const allowed = hostnames ?? (request?.host ? new Set([request.host.toLowerCase()]) : undefined);
|
|
50
|
+
if (allowed && !(typeof answer.hostname === 'string' && allowed.has(answer.hostname.toLowerCase())))
|
|
51
|
+
return false;
|
|
52
|
+
if (options.action !== undefined && answer.action !== options.action)
|
|
53
|
+
return false;
|
|
54
|
+
return true;
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
package/dist/stub.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface TurnstileStubOptions {
|
|
2
|
+
/** The secret siteverify accepts; any other is answered `invalid-input-secret`. Default `stub-secret`. */
|
|
3
|
+
secret?: string;
|
|
4
|
+
/** The tokens that are people's. Default: `person`. */
|
|
5
|
+
people?: readonly string[];
|
|
6
|
+
/** The person the stub widget's tokens are issued to: each token it hands out is this, a random part and the page's
|
|
7
|
+
host name. Default: the first of `people`. */
|
|
8
|
+
widgetToken?: string;
|
|
9
|
+
/** The host name siteverify says one of `people` was issued on. Default `localhost`. A widget's token says its own. */
|
|
10
|
+
hostname?: string;
|
|
11
|
+
/** The action siteverify says a token was issued for. */
|
|
12
|
+
action?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface TurnstileStub {
|
|
15
|
+
verifyUrl: string;
|
|
16
|
+
scriptUrl: string;
|
|
17
|
+
/** What siteverify was asked, in order: the token, the address and whether the secret was right. */
|
|
18
|
+
asked: Array<{
|
|
19
|
+
response: unknown;
|
|
20
|
+
remoteip: unknown;
|
|
21
|
+
secretOk: boolean;
|
|
22
|
+
}>;
|
|
23
|
+
close(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export declare function turnstileStub(options?: TurnstileStubOptions): Promise<TurnstileStub>;
|
package/dist/stub.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A stand-in for Cloudflare's Turnstile in tests: a local server with a siteverify that says yes to the tokens it
|
|
3
|
+
* was told are people's, and a widget script that registers `window.turnstile` and hands the form a person's token
|
|
4
|
+
* at once. Point the verifier at it — `turnstile({ siteKey, secret, verifyUrl: stub.verifyUrl, scriptUrl:
|
|
5
|
+
* stub.scriptUrl })` — and neither a node test nor a browser test calls Cloudflare.
|
|
6
|
+
*
|
|
7
|
+
* As Cloudflare's, a token is good once: siteverify answers a token it has already seen `timeout-or-duplicate`. The
|
|
8
|
+
* widget hands out a fresh one on each render and each `reset(id)` (the person's token, a random part and the page's
|
|
9
|
+
* host name, which siteverify answers as the token's `hostname`), so a form that retries must ask for a new one.
|
|
10
|
+
*/
|
|
11
|
+
import { createServer } from 'node:http';
|
|
12
|
+
async function bodyOf(req) {
|
|
13
|
+
const chunks = [];
|
|
14
|
+
for await (const chunk of req)
|
|
15
|
+
chunks.push(chunk);
|
|
16
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
17
|
+
if ((req.headers['content-type'] ?? '').startsWith('application/json'))
|
|
18
|
+
return JSON.parse(text || '{}');
|
|
19
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
20
|
+
}
|
|
21
|
+
export async function turnstileStub(options = {}) {
|
|
22
|
+
const secret = options.secret ?? 'stub-secret';
|
|
23
|
+
const people = new Set(options.people ?? ['person']);
|
|
24
|
+
const widgetToken = options.widgetToken ?? [...people][0] ?? 'person';
|
|
25
|
+
const asked = [];
|
|
26
|
+
const spent = new Set();
|
|
27
|
+
const script = `(() => {
|
|
28
|
+
let next = 0;
|
|
29
|
+
const widgets = new Map();
|
|
30
|
+
const issue = (options) => {
|
|
31
|
+
const token = ${JSON.stringify(widgetToken)} + '~' + Math.random().toString(36).slice(2) + '~' + location.hostname;
|
|
32
|
+
setTimeout(() => options.callback && options.callback(token), 0);
|
|
33
|
+
};
|
|
34
|
+
window.turnstile = {
|
|
35
|
+
render(element, options) {
|
|
36
|
+
const id = 'stub-' + next++;
|
|
37
|
+
const box = document.createElement('div');
|
|
38
|
+
box.setAttribute('data-turnstile-stub', options.sitekey);
|
|
39
|
+
if (options.action) box.setAttribute('data-action', options.action);
|
|
40
|
+
box.textContent = 'Verified';
|
|
41
|
+
element.append(box);
|
|
42
|
+
widgets.set(id, options);
|
|
43
|
+
issue(options);
|
|
44
|
+
return id;
|
|
45
|
+
},
|
|
46
|
+
reset(id) {
|
|
47
|
+
const options = widgets.get(id);
|
|
48
|
+
if (options) issue(options);
|
|
49
|
+
},
|
|
50
|
+
remove(id) {
|
|
51
|
+
widgets.delete(id);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
})();`;
|
|
55
|
+
/* One of `people`, or one a widget issued to the person: its host name, or undefined for any other token. */
|
|
56
|
+
const issuedOn = (token) => {
|
|
57
|
+
if (typeof token !== 'string')
|
|
58
|
+
return undefined;
|
|
59
|
+
if (people.has(token))
|
|
60
|
+
return options.hostname ?? 'localhost';
|
|
61
|
+
const [who, nonce, host] = token.split('~');
|
|
62
|
+
return who === widgetToken && nonce && host ? host : undefined;
|
|
63
|
+
};
|
|
64
|
+
const server = createServer(async (req, res) => {
|
|
65
|
+
const path = new URL(req.url ?? '/', 'http://stub').pathname;
|
|
66
|
+
if (req.method === 'GET' && path === '/turnstile/v0/api.js') {
|
|
67
|
+
res.writeHead(200, { 'content-type': 'text/javascript', 'cache-control': 'no-store', 'access-control-allow-origin': '*' });
|
|
68
|
+
res.end(script);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (req.method === 'POST' && path === '/turnstile/v0/siteverify') {
|
|
72
|
+
let body = {};
|
|
73
|
+
try {
|
|
74
|
+
body = await bodyOf(req);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
/* an unreadable body is a missing token */
|
|
78
|
+
}
|
|
79
|
+
const secretOk = body.secret === secret;
|
|
80
|
+
asked.push({ response: body.response, remoteip: body.remoteip, secretOk });
|
|
81
|
+
const host = issuedOn(body.response);
|
|
82
|
+
const duplicate = typeof body.response === 'string' && spent.has(body.response);
|
|
83
|
+
const success = secretOk && host !== undefined && !duplicate;
|
|
84
|
+
if (secretOk && typeof body.response === 'string')
|
|
85
|
+
spent.add(body.response);
|
|
86
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
87
|
+
res.end(JSON.stringify({
|
|
88
|
+
success,
|
|
89
|
+
'error-codes': success
|
|
90
|
+
? []
|
|
91
|
+
: [!secretOk ? 'invalid-input-secret' : duplicate ? 'timeout-or-duplicate' : 'invalid-input-response'],
|
|
92
|
+
...(success
|
|
93
|
+
? {
|
|
94
|
+
hostname: host,
|
|
95
|
+
challenge_ts: new Date().toISOString(),
|
|
96
|
+
...(options.action ? { action: options.action } : {}),
|
|
97
|
+
}
|
|
98
|
+
: {}),
|
|
99
|
+
}));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
res.writeHead(404).end();
|
|
103
|
+
});
|
|
104
|
+
server.listen(0, '127.0.0.1');
|
|
105
|
+
await new Promise((resolve) => server.once('listening', () => resolve()));
|
|
106
|
+
// A stand-in never keeps a process alive by itself: a test that forgot close(), or a module that only loads it.
|
|
107
|
+
server.unref();
|
|
108
|
+
const { port } = server.address();
|
|
109
|
+
const base = `http://127.0.0.1:${port}`;
|
|
110
|
+
return {
|
|
111
|
+
verifyUrl: `${base}/turnstile/v0/siteverify`,
|
|
112
|
+
scriptUrl: `${base}/turnstile/v0/api.js`,
|
|
113
|
+
asked,
|
|
114
|
+
close: () => new Promise((resolve) => {
|
|
115
|
+
server.closeAllConnections();
|
|
116
|
+
server.close(() => resolve());
|
|
117
|
+
}),
|
|
118
|
+
};
|
|
119
|
+
}
|
package/package.json
CHANGED
|
@@ -1 +1,42 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "@mistriwork/challenge-turnstile",
|
|
3
|
+
"version": "1.2.1",
|
|
4
|
+
"description": "Cloudflare Turnstile human-check pack for mistri Apps' public doors (auth.challenge), with a local test stub and zero extra dependencies.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mistri",
|
|
7
|
+
"turnstile",
|
|
8
|
+
"cloudflare",
|
|
9
|
+
"captcha",
|
|
10
|
+
"challenge",
|
|
11
|
+
"human-check"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://mistriwork.dev",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/rbaljinder/mistri/issues"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"author": "Baljinder Randhawa",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/rbaljinder/mistri.git",
|
|
22
|
+
"directory": "packages/challenge-turnstile"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"type": "module",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@mistriwork/mistri": "1.2.1"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=24"
|
|
41
|
+
}
|
|
42
|
+
}
|