@farm.js/bot 0.0.0-stage → 0.1.0-beta.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 +22 -0
- package/README.md +240 -2
- package/dist/build-mode.d.ts +3 -0
- package/dist/build-mode.d.ts.map +1 -0
- package/dist/build-mode.js +4 -0
- package/dist/captcha/index.d.ts +4 -0
- package/dist/captcha/index.d.ts.map +1 -0
- package/dist/captcha/index.js +2 -0
- package/dist/captcha/providers.d.ts +11 -0
- package/dist/captcha/providers.d.ts.map +1 -0
- package/dist/captcha/providers.js +90 -0
- package/dist/captcha/siteverify.d.ts +37 -0
- package/dist/captcha/siteverify.d.ts.map +1 -0
- package/dist/captcha/siteverify.js +88 -0
- package/dist/captcha/widget.d.ts +19 -0
- package/dist/captcha/widget.d.ts.map +1 -0
- package/dist/captcha/widget.js +52 -0
- package/dist/client.d.ts +69 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +235 -0
- package/dist/csp.d.ts +15 -0
- package/dist/csp.d.ts.map +1 -0
- package/dist/csp.js +99 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +9 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +128 -0
- package/dist/keys.d.ts +44 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +67 -0
- package/dist/preact.d.ts +10 -0
- package/dist/preact.d.ts.map +1 -0
- package/dist/preact.js +31 -0
- package/dist/provider-widget.d.ts +3 -0
- package/dist/provider-widget.d.ts.map +1 -0
- package/dist/provider-widget.js +5 -0
- package/dist/provider.d.ts +70 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +83 -0
- package/dist/react.d.ts +8 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +31 -0
- package/dist/runtime.d.ts +5 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +8 -0
- package/dist/server.d.ts +9 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +14 -0
- package/dist/solid.d.ts +9 -0
- package/dist/solid.d.ts.map +1 -0
- package/dist/solid.js +34 -0
- package/dist/svelte.d.ts +12 -0
- package/dist/svelte.d.ts.map +1 -0
- package/dist/svelte.js +22 -0
- package/dist/testing.d.ts +22 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +102 -0
- package/dist/verify.d.ts +39 -0
- package/dist/verify.d.ts.map +1 -0
- package/dist/verify.js +113 -0
- package/dist/vue.d.ts +20 -0
- package/dist/vue.d.ts.map +1 -0
- package/dist/vue.js +32 -0
- package/package.json +122 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Farm.js Team
|
|
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.
|
|
22
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,241 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @farm.js/bot
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Stop bots at your forms, with any checker.**
|
|
4
|
+
|
|
5
|
+
The check runs in the browser and every submission is verified on the server. A form that skips the check is refused. Your `security.csp` is updated for the provider you pick.
|
|
6
|
+
|
|
7
|
+
The core knows no vendor. A provider tells it how a checker works. `@farm.js/bot/captcha` has Turnstile, hCaptcha, and reCAPTCHA, and you can write your own in a few lines. They add no dependencies, and code you don't import stays out of your bundle.
|
|
8
|
+
|
|
9
|
+
It doesn't rate limit, block IPs, or decide what to do with a suspicious visitor. It answers one question for one submission.
|
|
10
|
+
|
|
11
|
+
## Use it
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
// farm.config.ts
|
|
15
|
+
import { bot } from "@farm.js/bot";
|
|
16
|
+
import { turnstile } from "@farm.js/bot/captcha";
|
|
17
|
+
import { defineConfig } from "@farm.js/core";
|
|
18
|
+
|
|
19
|
+
export default defineConfig({
|
|
20
|
+
plugins: [bot({ provider: turnstile(), hostnames: ["example.com"] })],
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```tsx
|
|
25
|
+
// inside the form
|
|
26
|
+
import { BotCheck } from "@farm.js/bot/react";
|
|
27
|
+
|
|
28
|
+
<BotCheck onVerify={() => setVerified(true)} />;
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
// src/app/api/signup/route.ts
|
|
33
|
+
import { verifyBot } from "@farm.js/bot/server";
|
|
34
|
+
|
|
35
|
+
export async function POST(request: Request) {
|
|
36
|
+
const form = await request.formData();
|
|
37
|
+
const check = await verifyBot(form);
|
|
38
|
+
|
|
39
|
+
if (!check.success) {
|
|
40
|
+
return Response.json({ error: check.message }, { status: check.status });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Create the account.
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
| Option | Default | What it does |
|
|
48
|
+
| ----------- | ---------------------------- | ------------------------------------------------------------------- |
|
|
49
|
+
| `provider` | Required | The checker to use |
|
|
50
|
+
| `hostnames` | Required outside development | The hostnames a check may come from. Development uses the request's |
|
|
51
|
+
| `timeoutMs` | `5000` | How long to wait for the provider |
|
|
52
|
+
|
|
53
|
+
## What comes back
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
| { success: true, provider, hostname, testKeys, data }
|
|
57
|
+
| { success: false, provider, code, message, status, providerCodes }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`message` is safe to show. `status` is 403, or 503 when the provider can't be reached. `code` is one of `missing_token`, `rejected`, `expired`, `hostname_mismatch`, or `unavailable`.
|
|
61
|
+
|
|
62
|
+
A configuration mistake, such as a missing or wrong key, is your bug and not the visitor's, so it throws a `BotError` and the submission fails.
|
|
63
|
+
|
|
64
|
+
`verifyBot` also takes a token string, for a JSON API. It works in API routes and server actions.
|
|
65
|
+
|
|
66
|
+
## Captchas
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { hcaptcha, recaptcha, turnstile } from "@farm.js/bot/captcha";
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
| Provider | Site key | Secret key |
|
|
73
|
+
| ------------- | -------------------- | ---------------------- |
|
|
74
|
+
| `turnstile()` | `TURNSTILE_SITE_KEY` | `TURNSTILE_SECRET_KEY` |
|
|
75
|
+
| `hcaptcha()` | `HCAPTCHA_SITE_KEY` | `HCAPTCHA_SECRET_KEY` |
|
|
76
|
+
| `recaptcha()` | `RECAPTCHA_SITE_KEY` | `RECAPTCHA_SECRET_KEY` |
|
|
77
|
+
|
|
78
|
+
Each takes `{ siteKey, secretKey, testKeys }`.
|
|
79
|
+
|
|
80
|
+
In development they work with no keys, on the service's always-passing test keys. A production build needs the site key and the server needs the secret. Both fail with a message naming the variable when they're missing. A built server never uses test keys unless you pass `testKeys: true`, for a staging deployment.
|
|
81
|
+
|
|
82
|
+
Any other service with a script widget and a siteverify endpoint is a description. These three are built this way.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { createSiteverifyProvider } from "@farm.js/bot/captcha";
|
|
86
|
+
|
|
87
|
+
export const acme = (keys?: BotProviderKeys) =>
|
|
88
|
+
createSiteverifyProvider(
|
|
89
|
+
{
|
|
90
|
+
name: "acme",
|
|
91
|
+
tokenField: "acme-response",
|
|
92
|
+
verifyUrl: "https://api.acme.dev/siteverify",
|
|
93
|
+
widget: { scriptUrl: "https://js.acme.dev/api.js", global: "acme" },
|
|
94
|
+
siteKeyEnv: "ACME_SITE_KEY",
|
|
95
|
+
secretKeyEnv: "ACME_SECRET_KEY",
|
|
96
|
+
csp: { "script-src": ["https://js.acme.dev"] },
|
|
97
|
+
},
|
|
98
|
+
keys,
|
|
99
|
+
);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The script must offer `render(element, options)`, `reset(id)`, and optionally `remove(id)`, and call `options.callback(token)`.
|
|
103
|
+
|
|
104
|
+
## Other renderers
|
|
105
|
+
|
|
106
|
+
| Renderer | Import | Reset |
|
|
107
|
+
| -------- | --------------------- | ----------------------------- |
|
|
108
|
+
| React | `@farm.js/bot/react` | `ref` gives `{ reset() }` |
|
|
109
|
+
| Preact | `@farm.js/bot/preact` | `ref` gives `{ reset() }` |
|
|
110
|
+
| Vue | `@farm.js/bot/vue` | template `ref` gives `reset` |
|
|
111
|
+
| Solid | `@farm.js/bot/solid` | `ref` callback |
|
|
112
|
+
| Svelte | `@farm.js/bot/svelte` | `ref` in the action's options |
|
|
113
|
+
|
|
114
|
+
Svelte uses an action: `<div use:botCheck={{ onVerify }}></div>`. Anything else can call `mountBotCheck(element, options)` from `@farm.js/bot/client`.
|
|
115
|
+
|
|
116
|
+
Tokens are single-use, so call `reset()` after a submit that fails. Pass `settings` for anything specific to a provider, such as `{ size: "compact" }`.
|
|
117
|
+
|
|
118
|
+
## Write your own checker
|
|
119
|
+
|
|
120
|
+
A checker is a plain object. `name` and `verify` are all it needs.
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import { defineBotProvider } from "@farm.js/bot";
|
|
124
|
+
|
|
125
|
+
export const honeypot = defineBotProvider({
|
|
126
|
+
name: "honeypot",
|
|
127
|
+
async verify({ form }) {
|
|
128
|
+
return form?.get("website") ? { success: false, code: "rejected" } : { success: true };
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// farm.config.ts: plugins: [bot({ provider: honeypot, hostnames: ["example.com"] })]
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`verify` receives `{ token, form, request, remoteIp, signal }` and returns `{ success: true, data }` or `{ success: false, code }`.
|
|
136
|
+
|
|
137
|
+
`verifyBot` can't see your provider's types, so `check.data` is `unknown`. For a typed `check.data`, keep the plugin in a variable, add it to `plugins`, and call its `verify`:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
// src/bot.ts
|
|
141
|
+
export const protection = bot({ provider: acme(), hostnames: ["example.com"] });
|
|
142
|
+
|
|
143
|
+
// farm.config.ts: plugins: [protection]
|
|
144
|
+
// your route: const check = await protection.verify(form);
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Farm handles the rules you shouldn't have to repeat. It reads the token, enforces `timeoutMs`, refuses a hostname that isn't yours when you report one, writes the visitor's message, and refuses anything that isn't a valid verdict. Throw only for a configuration mistake.
|
|
148
|
+
|
|
149
|
+
| Your checker | What you write |
|
|
150
|
+
| ---------------------------------------------- | -------------------------------------------------------------------------- |
|
|
151
|
+
| Runs on the server only | `verify` |
|
|
152
|
+
| Has browser code | `verify`, `client`, and a widget module |
|
|
153
|
+
| Has browser code but draws nothing | The same, with a widget that returns nothing |
|
|
154
|
+
| A captcha script with `render` and its own API | `verify`, and `widget: "@farm.js/bot/captcha/widget"` |
|
|
155
|
+
| A captcha script and a siteverify endpoint | A description, with `createSiteverifyProvider` from `@farm.js/bot/captcha` |
|
|
156
|
+
| An existing provider with one more rule | `{ ...turnstile(), verify }`, calling the original `verify` |
|
|
157
|
+
|
|
158
|
+
### Add browser code
|
|
159
|
+
|
|
160
|
+
Name a module in `client`. It's an ordinary file, so it can import anything and use its own variables. Secrets stay in the server half.
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
// src/acme.ts
|
|
164
|
+
import { createBotKeys, defineBotProvider, type BotProviderKeys } from "@farm.js/bot";
|
|
165
|
+
|
|
166
|
+
export function acme(options?: BotProviderKeys) {
|
|
167
|
+
const keys = createBotKeys(
|
|
168
|
+
{ name: "acme", siteKeyEnv: "ACME_SITE_KEY", secretKeyEnv: "ACME_SECRET_KEY" },
|
|
169
|
+
options,
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
return defineBotProvider({
|
|
173
|
+
name: "acme",
|
|
174
|
+
tokenField: "acme-token",
|
|
175
|
+
csp: { "script-src": ["https://js.acme.example"] },
|
|
176
|
+
client: () => ({ widget: "/src/acme.widget.ts", public: { siteKey: keys.siteKey() } }),
|
|
177
|
+
|
|
178
|
+
async verify({ token, signal }) {
|
|
179
|
+
const secret = keys.secretKey().value;
|
|
180
|
+
try {
|
|
181
|
+
const response = await fetch("https://api.acme.example/check", {
|
|
182
|
+
method: "POST",
|
|
183
|
+
headers: { authorization: `Bearer ${secret}` },
|
|
184
|
+
body: token,
|
|
185
|
+
signal,
|
|
186
|
+
});
|
|
187
|
+
if (!response.ok) return { success: false, code: "unavailable" };
|
|
188
|
+
const { human, score } = await response.json();
|
|
189
|
+
return human ? { success: true, data: { score } } : { success: false, code: "rejected" };
|
|
190
|
+
} catch {
|
|
191
|
+
return { success: false, code: "unavailable" };
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
// src/acme.widget.ts
|
|
200
|
+
import { defineBotWidget, loadBotScript } from "@farm.js/bot/client";
|
|
201
|
+
|
|
202
|
+
export default defineBotWidget<{ siteKey: string }>(({ siteKey }) => ({
|
|
203
|
+
async mount(element, { onVerify, onExpire, onError }) {
|
|
204
|
+
const api = await loadBotScript<AcmeApi>("https://js.acme.example/v1.js", { global: "acme" });
|
|
205
|
+
const id = api.render(element, { siteKey, done: onVerify, expired: onExpire, failed: onError });
|
|
206
|
+
return { reset: () => api.reset(id), remove: () => api.remove(id) };
|
|
207
|
+
},
|
|
208
|
+
}));
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Call `onVerify(token)` and Farm puts the token in the form under `tokenField`, and takes it out again on `onExpire`, `reset`, and `remove`. A published checker names its widget by package path, such as `acme-bot/widget`. Inside an app, use a path from the app root, as above.
|
|
212
|
+
|
|
213
|
+
`createBotKeys` gives your checker the same key options and safety as the ones in `@farm.js/bot/captcha`. It takes `{ siteKey, secretKey, testKeys }`, reads Cloudflare bindings as well as `process.env`, and refuses a test key in production. Prefer it to reading `process.env` in `verify`, which finds nothing on some Workers.
|
|
214
|
+
|
|
215
|
+
`examples/bot-demo/src/time-trap.ts` is a complete checker with its own browser code.
|
|
216
|
+
|
|
217
|
+
### Test it
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { checkBotProvider } from "@farm.js/bot/testing";
|
|
221
|
+
import acmeWidget from "./acme.widget";
|
|
222
|
+
|
|
223
|
+
expect(
|
|
224
|
+
await checkBotProvider(acme({ secretKey: "my-secret" }), {
|
|
225
|
+
secrets: ["my-secret"],
|
|
226
|
+
widget: acmeWidget,
|
|
227
|
+
}),
|
|
228
|
+
).toEqual([]);
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
It returns every problem as a sentence: a secret in the browser config, a `verify` that accepts a bad token, a widget that leaves elements behind when it's removed. The providers in `@farm.js/bot/captcha` pass it. Pass `widget` only for code you can run in a DOM such as jsdom, and stub `fetch` if `verify` calls a service.
|
|
232
|
+
|
|
233
|
+
## Limits
|
|
234
|
+
|
|
235
|
+
- **Server components in `rsc` mode.** Farm runs only a plugin's browser hooks there, not its `configure`, so the build has no widget for `<BotCheck>` and the page logs a `BotError` that says so. A production server doesn't load farm.config.ts either, so `verifyBot` throws a `BotError`, although `farm dev` finds the plugin. To check forms on the server, create the plugin in a module your routes import, such as `src/bot.ts`, and add that instance to `plugins`. `islands` mode works.
|
|
236
|
+
- **Cloudflare Pages with `@farm.js/core` 0.1.66 or earlier.** That output exposes no bindings at runtime, so secrets aren't found and every check fails with a `BotError`. Upgrade core, or use compatibility date `2025-04-01` or later, the `cloudflare-module` preset, or pass `secretKey`.
|
|
237
|
+
- **reCAPTCHA** means the v2 checkbox. v3 has no widget, so it needs its own provider.
|
|
238
|
+
- **One checker per app.** The plugin can be added once, so two forms can't use two different checkers.
|
|
239
|
+
- **A checker can't add routes.** One that issues challenges from the server needs a route in the app for it.
|
|
240
|
+
- **A checker with no browser half has no `<BotCheck>`.** Leave the component out, or nothing tells the page it passed.
|
|
241
|
+
- **The hostname check** relies on the provider's report, which test keys don't give. Outside development it accepts only `hostnames`, because a client can set the request's host on a server it reaches directly, so `farm build` fails without it. In development it compares against the request's host. Each provider's own domain allowlist still applies.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-mode.d.ts","sourceRoot":"","sources":["../src/build-mode.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { hcaptcha, recaptcha, turnstile } from "./providers.js";
|
|
2
|
+
export { createSiteverifyProvider, type SiteverifyProviderConfig, type SiteverifyResponse, } from "./siteverify.js";
|
|
3
|
+
export type { ScriptWidgetConfig } from "./widget.js";
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/captcha/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChE,OAAO,EACL,wBAAwB,EACxB,KAAK,wBAAwB,EAC7B,KAAK,kBAAkB,GACxB,MAAM,iBAAiB,CAAC;AACzB,YAAY,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { BotProvider, BotProviderKeys } from "../index.js";
|
|
2
|
+
import { type SiteverifyResponse } from "./siteverify.js";
|
|
3
|
+
type SiteverifyProvider = BotProvider<SiteverifyResponse>;
|
|
4
|
+
/** Cloudflare Turnstile. Keys default to `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`. */
|
|
5
|
+
export declare function turnstile(keys?: BotProviderKeys): SiteverifyProvider;
|
|
6
|
+
/** hCaptcha. Keys default to `HCAPTCHA_SITE_KEY` and `HCAPTCHA_SECRET_KEY`. */
|
|
7
|
+
export declare function hcaptcha(keys?: BotProviderKeys): SiteverifyProvider;
|
|
8
|
+
/** reCAPTCHA v2 checkbox. Keys default to `RECAPTCHA_SITE_KEY` and `RECAPTCHA_SECRET_KEY`. */
|
|
9
|
+
export declare function recaptcha(keys?: BotProviderKeys): SiteverifyProvider;
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=providers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"providers.d.ts","sourceRoot":"","sources":["../../src/captcha/providers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAA4B,KAAK,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAEpF,KAAK,kBAAkB,GAAG,WAAW,CAAC,kBAAkB,CAAC,CAAC;AAK1D,6FAA6F;AAC7F,wBAAgB,SAAS,CAAC,IAAI,CAAC,EAAE,eAAe,GAAG,kBAAkB,CA2BpE;AAED,+EAA+E;AAC/E,wBAAgB,QAAQ,CAAC,IAAI,CAAC,EAAE,eAAe,GAAG,kBAAkB,CAmCnE;AAED,8FAA8F;AAC9F,wBAAgB,SAAS,CAAC,IAAI,CAAC,EAAE,eAAe,GAAG,kBAAkB,CA4BpE"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { createSiteverifyProvider } from "./siteverify.js";
|
|
2
|
+
const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
|
|
3
|
+
const HCAPTCHA_SOURCES = ["https://hcaptcha.com", "https://*.hcaptcha.com"];
|
|
4
|
+
/** Cloudflare Turnstile. Keys default to `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`. */
|
|
5
|
+
export function turnstile(keys) {
|
|
6
|
+
return createSiteverifyProvider({
|
|
7
|
+
name: "turnstile",
|
|
8
|
+
tokenField: "cf-turnstile-response",
|
|
9
|
+
maxTokenLength: 2048,
|
|
10
|
+
verifyUrl: `${TURNSTILE_ORIGIN}/turnstile/v0/siteverify`,
|
|
11
|
+
widget: {
|
|
12
|
+
scriptUrl: `${TURNSTILE_ORIGIN}/turnstile/v0/api.js?render=explicit`,
|
|
13
|
+
global: "turnstile",
|
|
14
|
+
autoTheme: true,
|
|
15
|
+
readyCallback: true,
|
|
16
|
+
},
|
|
17
|
+
siteKeyEnv: "TURNSTILE_SITE_KEY",
|
|
18
|
+
secretKeyEnv: "TURNSTILE_SECRET_KEY",
|
|
19
|
+
csp: {
|
|
20
|
+
"script-src": [TURNSTILE_ORIGIN],
|
|
21
|
+
"frame-src": [TURNSTILE_ORIGIN],
|
|
22
|
+
},
|
|
23
|
+
testKeys: {
|
|
24
|
+
siteKey: "1x00000000000000000000AA",
|
|
25
|
+
secretKey: "1x0000000000000000000000000000000AA",
|
|
26
|
+
isTestSecret: (secret) => /^[123]x0{31}AA$/.test(secret),
|
|
27
|
+
},
|
|
28
|
+
}, keys);
|
|
29
|
+
}
|
|
30
|
+
/** hCaptcha. Keys default to `HCAPTCHA_SITE_KEY` and `HCAPTCHA_SECRET_KEY`. */
|
|
31
|
+
export function hcaptcha(keys) {
|
|
32
|
+
return createSiteverifyProvider({
|
|
33
|
+
name: "hcaptcha",
|
|
34
|
+
tokenField: "h-captcha-response",
|
|
35
|
+
verifyUrl: "https://api.hcaptcha.com/siteverify",
|
|
36
|
+
widget: {
|
|
37
|
+
scriptUrl: "https://js.hcaptcha.com/1/api.js?render=explicit",
|
|
38
|
+
global: "hcaptcha",
|
|
39
|
+
readyCallback: true,
|
|
40
|
+
},
|
|
41
|
+
siteKeyEnv: "HCAPTCHA_SITE_KEY",
|
|
42
|
+
secretKeyEnv: "HCAPTCHA_SECRET_KEY",
|
|
43
|
+
csp: {
|
|
44
|
+
"script-src": HCAPTCHA_SOURCES,
|
|
45
|
+
"frame-src": HCAPTCHA_SOURCES,
|
|
46
|
+
"style-src": HCAPTCHA_SOURCES,
|
|
47
|
+
"connect-src": HCAPTCHA_SOURCES,
|
|
48
|
+
},
|
|
49
|
+
testKeys: {
|
|
50
|
+
siteKey: "10000000-ffff-ffff-ffff-000000000001",
|
|
51
|
+
secretKey: "0x0000000000000000000000000000000000000000",
|
|
52
|
+
},
|
|
53
|
+
codes: {
|
|
54
|
+
expired: [
|
|
55
|
+
"expired-input-response",
|
|
56
|
+
"already-seen-response",
|
|
57
|
+
"invalid-or-already-seen-response",
|
|
58
|
+
],
|
|
59
|
+
},
|
|
60
|
+
// hCaptcha documents this value for periods of unusually high traffic.
|
|
61
|
+
unknownHostnames: ["not-provided"],
|
|
62
|
+
}, keys);
|
|
63
|
+
}
|
|
64
|
+
/** reCAPTCHA v2 checkbox. Keys default to `RECAPTCHA_SITE_KEY` and `RECAPTCHA_SECRET_KEY`. */
|
|
65
|
+
export function recaptcha(keys) {
|
|
66
|
+
return createSiteverifyProvider({
|
|
67
|
+
name: "recaptcha",
|
|
68
|
+
tokenField: "g-recaptcha-response",
|
|
69
|
+
verifyUrl: "https://www.google.com/recaptcha/api/siteverify",
|
|
70
|
+
widget: {
|
|
71
|
+
scriptUrl: "https://www.google.com/recaptcha/api.js?render=explicit",
|
|
72
|
+
global: "grecaptcha",
|
|
73
|
+
readyCallback: true,
|
|
74
|
+
},
|
|
75
|
+
siteKeyEnv: "RECAPTCHA_SITE_KEY",
|
|
76
|
+
secretKeyEnv: "RECAPTCHA_SECRET_KEY",
|
|
77
|
+
csp: {
|
|
78
|
+
"script-src": ["https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/"],
|
|
79
|
+
"frame-src": [
|
|
80
|
+
"https://www.google.com/recaptcha/",
|
|
81
|
+
"https://recaptcha.google.com/recaptcha/",
|
|
82
|
+
],
|
|
83
|
+
"connect-src": ["https://www.google.com/recaptcha/"],
|
|
84
|
+
},
|
|
85
|
+
testKeys: {
|
|
86
|
+
siteKey: "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI",
|
|
87
|
+
secretKey: "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe",
|
|
88
|
+
},
|
|
89
|
+
}, keys);
|
|
90
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type BotCspSources, type BotKeysConfig, type BotProvider, type BotProviderKeys } from "../index.js";
|
|
2
|
+
import type { ScriptWidgetConfig } from "./widget.js";
|
|
3
|
+
/** The JSON a siteverify endpoint answers with. Field names are the provider's own. */
|
|
4
|
+
export interface SiteverifyResponse {
|
|
5
|
+
success?: unknown;
|
|
6
|
+
hostname?: unknown;
|
|
7
|
+
challenge_ts?: unknown;
|
|
8
|
+
"error-codes"?: unknown;
|
|
9
|
+
[field: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
export interface SiteverifyProviderConfig extends BotKeysConfig {
|
|
12
|
+
/** The form field the widget fills with its token. */
|
|
13
|
+
tokenField: string;
|
|
14
|
+
maxTokenLength?: number;
|
|
15
|
+
verifyUrl: string;
|
|
16
|
+
/** The provider's script. Leave it out and set `client` yourself for your own browser code. */
|
|
17
|
+
widget?: Omit<ScriptWidgetConfig, "name" | "siteKey">;
|
|
18
|
+
secretKeyEnv: string;
|
|
19
|
+
csp: BotCspSources;
|
|
20
|
+
/** Provider error codes beyond the ones most siteverify endpoints share. */
|
|
21
|
+
codes?: {
|
|
22
|
+
/** The token expired or was already used. */
|
|
23
|
+
expired?: readonly string[];
|
|
24
|
+
/** The secret key itself is wrong, which the app owner has to fix. */
|
|
25
|
+
secret?: readonly string[];
|
|
26
|
+
/** The provider failed, so the visitor isn't at fault. */
|
|
27
|
+
unavailable?: readonly string[];
|
|
28
|
+
};
|
|
29
|
+
/** Values the provider reports when it doesn't know the hostname. */
|
|
30
|
+
unknownHostnames?: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Build a provider for a checker that has a script widget and a siteverify endpoint: a form POST
|
|
34
|
+
* of `secret` and `response` that answers `{ success, hostname, "error-codes" }`.
|
|
35
|
+
*/
|
|
36
|
+
export declare function createSiteverifyProvider(config: SiteverifyProviderConfig, options?: BotProviderKeys): BotProvider<SiteverifyResponse>;
|
|
37
|
+
//# sourceMappingURL=siteverify.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"siteverify.d.ts","sourceRoot":"","sources":["../../src/captcha/siteverify.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,eAAe,EAGrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEtD,uFAAuF;AACvF,MAAM,WAAW,kBAAkB;IACjC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,wBAAyB,SAAQ,aAAa;IAC7D,sDAAsD;IACtD,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,+FAA+F;IAC/F,MAAM,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IACtD,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,EAAE,aAAa,CAAC;IACnB,4EAA4E;IAC5E,KAAK,CAAC,EAAE;QACN,6CAA6C;QAC7C,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QAC5B,sEAAsE;QACtE,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QAC3B,0DAA0D;QAC1D,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;KACjC,CAAC;IACF,qEAAqE;IACrE,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC;AAQD;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,wBAAwB,EAChC,OAAO,CAAC,EAAE,eAAe,GACxB,WAAW,CAAC,kBAAkB,CAAC,CAwFjC"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { BotError, createBotKeys, defineBotProvider, } from "../index.js";
|
|
2
|
+
const SHARED_CODES = {
|
|
3
|
+
expired: ["timeout-or-duplicate"],
|
|
4
|
+
secret: ["missing-input-secret", "invalid-input-secret"],
|
|
5
|
+
unavailable: ["bad-request", "internal-error"],
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Build a provider for a checker that has a script widget and a siteverify endpoint: a form POST
|
|
9
|
+
* of `secret` and `response` that answers `{ success, hostname, "error-codes" }`.
|
|
10
|
+
*/
|
|
11
|
+
export function createSiteverifyProvider(config, options) {
|
|
12
|
+
const keys = createBotKeys(config, options);
|
|
13
|
+
const hasCode = (codes, kind) => codes.some((code) => SHARED_CODES[kind].includes(code) || config.codes?.[kind]?.includes(code));
|
|
14
|
+
async function verify(input) {
|
|
15
|
+
const unavailable = (code) => ({
|
|
16
|
+
success: false,
|
|
17
|
+
code: "unavailable",
|
|
18
|
+
providerCodes: [code],
|
|
19
|
+
});
|
|
20
|
+
const { value: secret, isTest: testSecret } = keys.secretKey();
|
|
21
|
+
const body = new URLSearchParams({ secret, response: input.token ?? "" });
|
|
22
|
+
if (input.remoteIp)
|
|
23
|
+
body.set("remoteip", input.remoteIp);
|
|
24
|
+
let data;
|
|
25
|
+
let ok;
|
|
26
|
+
let status;
|
|
27
|
+
try {
|
|
28
|
+
const response = await fetch(config.verifyUrl, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
body,
|
|
31
|
+
signal: input.signal,
|
|
32
|
+
});
|
|
33
|
+
ok = response.ok;
|
|
34
|
+
status = response.status;
|
|
35
|
+
// Turnstile answers a wrong secret with HTTP 400 and the reason in the body.
|
|
36
|
+
data = (await response.json().catch(() => undefined));
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
const name = error?.name;
|
|
40
|
+
return unavailable(typeof name === "string" ? name : "error");
|
|
41
|
+
}
|
|
42
|
+
const providerCodes = data && Array.isArray(data["error-codes"])
|
|
43
|
+
? data["error-codes"].filter((code) => typeof code === "string")
|
|
44
|
+
: [];
|
|
45
|
+
if (!ok && providerCodes.length === 0)
|
|
46
|
+
return unavailable(`http_${status}`);
|
|
47
|
+
if (!data || typeof data !== "object")
|
|
48
|
+
return unavailable("invalid_response");
|
|
49
|
+
if (!ok || data.success !== true) {
|
|
50
|
+
if (hasCode(providerCodes, "secret")) {
|
|
51
|
+
throw new BotError("invalid_secret_key", `${config.name} rejected the secret key. Check \`${config.secretKeyEnv}\` against the key in your ${config.name} dashboard.`);
|
|
52
|
+
}
|
|
53
|
+
if (hasCode(providerCodes, "unavailable")) {
|
|
54
|
+
return { success: false, code: "unavailable", providerCodes };
|
|
55
|
+
}
|
|
56
|
+
if (hasCode(providerCodes, "expired")) {
|
|
57
|
+
return { success: false, code: "expired", providerCodes };
|
|
58
|
+
}
|
|
59
|
+
return { success: false, code: "rejected", providerCodes };
|
|
60
|
+
}
|
|
61
|
+
// Test keys report a fixed placeholder hostname, so only real keys can be checked.
|
|
62
|
+
if (testSecret)
|
|
63
|
+
return { success: true, testKeys: true, data };
|
|
64
|
+
const hostname = typeof data.hostname === "string" ? data.hostname : undefined;
|
|
65
|
+
if (hostname !== undefined && config.unknownHostnames?.includes(hostname)) {
|
|
66
|
+
return { success: true, data };
|
|
67
|
+
}
|
|
68
|
+
if (hostname === undefined)
|
|
69
|
+
return { success: false, code: "hostname_mismatch", providerCodes };
|
|
70
|
+
return { success: true, hostname, data };
|
|
71
|
+
}
|
|
72
|
+
const { widget } = config;
|
|
73
|
+
return defineBotProvider({
|
|
74
|
+
name: config.name,
|
|
75
|
+
tokenField: config.tokenField,
|
|
76
|
+
...(config.maxTokenLength === undefined ? {} : { maxTokenLength: config.maxTokenLength }),
|
|
77
|
+
csp: config.csp,
|
|
78
|
+
verify,
|
|
79
|
+
...(widget
|
|
80
|
+
? {
|
|
81
|
+
client: () => ({
|
|
82
|
+
widget: "@farm.js/bot/captcha/widget",
|
|
83
|
+
public: { ...widget, name: config.name, siteKey: keys.siteKey() },
|
|
84
|
+
}),
|
|
85
|
+
}
|
|
86
|
+
: {}),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type BotWidgetDriver } from "../client.js";
|
|
2
|
+
/** JSON describing a widget loaded from a provider's script. */
|
|
3
|
+
export interface ScriptWidgetConfig {
|
|
4
|
+
name: string;
|
|
5
|
+
siteKey: string;
|
|
6
|
+
/** Should request explicit rendering, so Farm controls when the widget mounts. */
|
|
7
|
+
scriptUrl: string;
|
|
8
|
+
/** The browser global the script defines. */
|
|
9
|
+
global: string;
|
|
10
|
+
/** The provider accepts `theme: "auto"`. Otherwise Farm resolves it from the color scheme. */
|
|
11
|
+
autoTheme?: boolean;
|
|
12
|
+
/** The script signals readiness through an `onload` callback instead of its load event. */
|
|
13
|
+
readyCallback?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/** The browser half for a captcha whose script offers `render`, `reset`, and maybe `remove`. */
|
|
16
|
+
export declare function createScriptWidget(config: ScriptWidgetConfig): BotWidgetDriver;
|
|
17
|
+
declare const _default: import("../client.js").BotWidgetFactory<ScriptWidgetConfig>;
|
|
18
|
+
export default _default;
|
|
19
|
+
//# sourceMappingURL=widget.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"widget.d.ts","sourceRoot":"","sources":["../../src/captcha/widget.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,eAAe,EACrB,MAAM,cAAc,CAAC;AAEtB,gEAAgE;AAChE,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,kFAAkF;IAClF,SAAS,EAAE,MAAM,CAAC;IAClB,6CAA6C;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,8FAA8F;IAC9F,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,2FAA2F;IAC3F,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAoBD,gGAAgG;AAChG,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,GAAG,eAAe,CAyC9E;;AAED,wBAAuE"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { defineBotWidget, loadBotScript, } from "../client.js";
|
|
2
|
+
const NOOP_WIDGET = { reset() { }, remove() { } };
|
|
3
|
+
function resolveTheme(theme, autoTheme, runtimeWindow) {
|
|
4
|
+
if (theme !== "auto" || autoTheme)
|
|
5
|
+
return theme;
|
|
6
|
+
return runtimeWindow.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
|
7
|
+
}
|
|
8
|
+
/** The browser half for a captcha whose script offers `render`, `reset`, and maybe `remove`. */
|
|
9
|
+
export function createScriptWidget(config) {
|
|
10
|
+
return {
|
|
11
|
+
async mount(element, mount) {
|
|
12
|
+
const { ownerDocument: document } = element;
|
|
13
|
+
const runtimeWindow = document.defaultView;
|
|
14
|
+
const api = await loadBotScript(config.scriptUrl, config, runtimeWindow);
|
|
15
|
+
if (mount.signal.aborted)
|
|
16
|
+
return NOOP_WIDGET;
|
|
17
|
+
// reCAPTCHA can't render twice into one element, so every widget gets its own host.
|
|
18
|
+
const host = document.createElement("div");
|
|
19
|
+
element.append(host);
|
|
20
|
+
let widgetId;
|
|
21
|
+
try {
|
|
22
|
+
widgetId = api.render(host, {
|
|
23
|
+
...mount.settings,
|
|
24
|
+
sitekey: config.siteKey,
|
|
25
|
+
theme: resolveTheme(mount.theme, config.autoTheme, runtimeWindow),
|
|
26
|
+
callback: mount.onVerify,
|
|
27
|
+
"expired-callback": mount.onExpire,
|
|
28
|
+
"error-callback": (code) => {
|
|
29
|
+
const detail = code === undefined ? "" : ` with code ${String(code)}`;
|
|
30
|
+
mount.onError(new Error(`The ${config.name} widget failed${detail}.`));
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
host.remove();
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
reset() {
|
|
40
|
+
if (widgetId !== undefined)
|
|
41
|
+
api.reset(widgetId);
|
|
42
|
+
},
|
|
43
|
+
remove() {
|
|
44
|
+
if (widgetId !== undefined)
|
|
45
|
+
api.remove?.(widgetId);
|
|
46
|
+
host.remove();
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export default defineBotWidget(createScriptWidget);
|