@owlmeans/captcha-recaptcha 0.0.0-stage → 0.2.0
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/README.md +94 -2
- package/agent-meta/manifest.json +16 -0
- package/agent-meta/skills/captcha-recaptcha/SKILL.md +79 -0
- package/build/append.d.ts +12 -0
- package/build/append.d.ts.map +1 -0
- package/build/append.js +16 -0
- package/build/append.js.map +1 -0
- package/build/consts.d.ts +20 -0
- package/build/consts.d.ts.map +1 -0
- package/build/consts.js +20 -0
- package/build/consts.js.map +1 -0
- package/build/index.d.ts +7 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +6 -0
- package/build/index.js.map +1 -0
- package/build/keys.d.ts +9 -0
- package/build/keys.d.ts.map +1 -0
- package/build/keys.js +18 -0
- package/build/keys.js.map +1 -0
- package/build/provider.d.ts +13 -0
- package/build/provider.d.ts.map +1 -0
- package/build/provider.js +46 -0
- package/build/provider.js.map +1 -0
- package/build/types.d.ts +74 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/build/verifier.d.ts +8 -0
- package/build/verifier.d.ts.map +1 -0
- package/build/verifier.js +54 -0
- package/build/verifier.js.map +1 -0
- package/package.json +51 -4
- package/src/append.ts +21 -0
- package/src/consts.ts +23 -0
- package/src/index.ts +6 -0
- package/src/keys.ts +28 -0
- package/src/provider.ts +57 -0
- package/src/types.ts +81 -0
- package/src/verifier.ts +60 -0
- package/tests/append.spec.ts +50 -0
- package/tests/context.ts +36 -0
- package/tests/provider.spec.ts +60 -0
- package/tests/verifier.spec.ts +46 -0
- package/tsconfig.json +16 -0
package/README.md
CHANGED
|
@@ -1,3 +1,95 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @owlmeans/captcha-recaptcha
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Google reCAPTCHA provider for `@owlmeans/captcha`: Google's siteverify, its answer mapped onto
|
|
4
|
+
the neutral `CaptchaVerdict`, the provider's config records and the helper that registers it in a
|
|
5
|
+
context's captcha host. With it registered, the captcha guest sign-in of `@owlmeans/server-auth`
|
|
6
|
+
(where the host record `MOD_CAPTCHA` names it) and a strict `makeCaptchaCheck` (e-mail sign-in, a
|
|
7
|
+
route that acts on a token) judge reCAPTCHA v2 and v3 tokens. The browser half is
|
|
8
|
+
`@owlmeans/web-captcha-recaptcha`.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
bun add @owlmeans/captcha-recaptcha@^0.2.0
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Concepts
|
|
17
|
+
|
|
18
|
+
- **Provider** — `makeRecaptchaProvider(options)` is a `CaptchaProvider` with id `'recaptcha'`
|
|
19
|
+
(`RECAPTCHA_PROVIDER`). `verify` posts the siteverify form (`secret`, `response`, `remoteip`) and
|
|
20
|
+
answers `{ success, score, action, hostname, at, errors }`; `clientSettings()` answers
|
|
21
|
+
`{ provider: 'recaptcha', siteKey }`.
|
|
22
|
+
- **Keys** — the secret and the site key come from fixed options or from `keys` getters read per
|
|
23
|
+
call. `appendRecaptcha(ctx)` defaults `keys` to the context's records: `MOD_RECAPTCHA`
|
|
24
|
+
(`'_external:re-captcha'`, the secret in `value`, an optional `siteKey`) and `CMOD_RECAPTCHA`
|
|
25
|
+
(`'_client-external:re-captcha'`, the advertised site key). An empty or unresolved value counts as
|
|
26
|
+
none.
|
|
27
|
+
- **Fail closed** — without a secret `verify` asks nothing and throws
|
|
28
|
+
`AuthUnavailable('captcha:config')`; an unreachable or unreadable Google is
|
|
29
|
+
`AuthUnavailable('captcha')`; a refused token is a verdict (`success: false`).
|
|
30
|
+
- **Explicit** — registering is a call in the context set-up; importing the package registers
|
|
31
|
+
nothing, and registering turns nothing on by itself.
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { MOD_CAPTCHA } from '@owlmeans/captcha'
|
|
37
|
+
import { appendRecaptcha, CMOD_RECAPTCHA, MOD_RECAPTCHA, RECAPTCHA_PROVIDER } from '@owlmeans/captcha-recaptcha'
|
|
38
|
+
import { clientPlugin, plugin } from '@owlmeans/config'
|
|
39
|
+
|
|
40
|
+
// config: the provider's records, and the host record of the guest sign-in
|
|
41
|
+
plugin(cfg, { value: '/etc/master-secret/recaptcha-secret' }, MOD_RECAPTCHA)
|
|
42
|
+
clientPlugin(cfg, '/etc/app-config/recaptcha-site-key', CMOD_RECAPTCHA)
|
|
43
|
+
plugin(cfg, { provider: RECAPTCHA_PROVIDER, hostnames: 'example.org', minScore: '0.5', actions: 'inquiry' }, MOD_CAPTCHA)
|
|
44
|
+
|
|
45
|
+
// context
|
|
46
|
+
appendRecaptcha(context)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
A strict check with keys held in another config block:
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
appendRecaptcha(context, { keys: { secret: () => cfg.captcha.secret, siteKey: () => cfg.captcha.siteKey } })
|
|
53
|
+
const check = makeCaptchaCheck(context, { provider: RECAPTCHA_PROVIDER, hostnames: 'example.org', minScore: 0.5 })
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## API
|
|
57
|
+
|
|
58
|
+
| Export | Description |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `appendRecaptcha(ctx, options?)` | Register the provider in `ensureCaptchaService(ctx)`; returns the context |
|
|
61
|
+
| `makeRecaptchaProvider(options?)` | The provider; `options.id`, `secret`, `siteKey`, `keys`, `url` (https only), `fetch`, `timeout` |
|
|
62
|
+
| `makeRecaptchaKeys(ctx)` | The keys of the context's `MOD_RECAPTCHA` / `CMOD_RECAPTCHA` records, read per call |
|
|
63
|
+
| `createRecaptchaVerifier(options?)` | The siteverify call alone: `verify({ secret, response, remoteip? })` → Google's answer |
|
|
64
|
+
| `RECAPTCHA_PROVIDER` | `'recaptcha'` |
|
|
65
|
+
| `MOD_RECAPTCHA`, `CMOD_RECAPTCHA` | `'_external:re-captcha'`, `'_client-external:re-captcha'` |
|
|
66
|
+
| `RECAPTCHA_SITEVERIFY_URL`, `RECAPTCHA_VERIFY_TIMEOUT` | `https://www.google.com/recaptcha/api/siteverify`, `10_000` |
|
|
67
|
+
| `RecaptchaProviderOptions`, `RecaptchaKeys`, `RecaptchaRecord`, `RecaptchaResponse`, `RecaptchaRequest`, `RecaptchaFetch`, `RecaptchaVerifier`, `RecaptchaVerifierOptions`, `RecaptchaProvider` | Types |
|
|
68
|
+
|
|
69
|
+
## Related packages
|
|
70
|
+
|
|
71
|
+
- [`@owlmeans/captcha`](https://github.com/owlmeans/common/tree/main/packages/captcha) (common) — the provider host, the `MOD_CAPTCHA` policy and `makeCaptchaCheck`
|
|
72
|
+
- [`@owlmeans/server-auth`](https://github.com/owlmeans/common/tree/main/packages/server-auth) (common) — the captcha guest sign-in that judges this provider's verdicts
|
|
73
|
+
- [`@owlmeans/server-auth-email`](https://github.com/owlmeans/common/tree/main/packages/server-auth-email) (common) — e-mail sign-in, a strict check over this provider
|
|
74
|
+
- [`@owlmeans/config`](https://github.com/owlmeans/common/tree/main/packages/config) (common) — `plugin` and `clientPlugin` for the `MOD_RECAPTCHA` / `CMOD_RECAPTCHA` records
|
|
75
|
+
- [`@owlmeans/web-captcha-recaptcha`](../web-captcha-recaptcha) — the browser half
|
|
76
|
+
|
|
77
|
+
## License
|
|
78
|
+
|
|
79
|
+
MIT
|
|
80
|
+
|
|
81
|
+
<!-- owlmeans:agent-guidance:start -->
|
|
82
|
+
## Agent guidance
|
|
83
|
+
|
|
84
|
+
This package ships embedded agent skills under `agent-meta/`. After installing your
|
|
85
|
+
`@owlmeans/*` packages, run the OwlMeans agent-skills installer to place them into
|
|
86
|
+
your project's skill store (`.agents/skills/`):
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
npx @owlmeans/agent-skills@^0.2.0
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The embedded files are version-matched to this package release. Do not edit them
|
|
93
|
+
directly — they are regenerated on each publish. To contribute guidance edits,
|
|
94
|
+
open a PR against the source monorepo.
|
|
95
|
+
<!-- owlmeans:agent-guidance:end -->
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 3,
|
|
3
|
+
"package": "@owlmeans/captcha-recaptcha",
|
|
4
|
+
"version": "0.2.0",
|
|
5
|
+
"generatedAt": "2026-11-15T13:38:38.779Z",
|
|
6
|
+
"canonicalRepo": "https://github.com/owlmeans/connect",
|
|
7
|
+
"entries": [
|
|
8
|
+
{
|
|
9
|
+
"kind": "skill",
|
|
10
|
+
"name": "captcha-recaptcha",
|
|
11
|
+
"category": "package-specific",
|
|
12
|
+
"file": "skills/captcha-recaptcha/SKILL.md",
|
|
13
|
+
"canonicalPath": ".agents/skills/captcha-recaptcha/SKILL.md"
|
|
14
|
+
}
|
|
15
|
+
]
|
|
16
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: captcha-recaptcha
|
|
3
|
+
description: How to use @owlmeans/captcha-recaptcha (OwlMeans connect) — the Google reCAPTCHA provider for the @owlmeans/captcha host. makeRecaptchaProvider (siteverify mapped onto the neutral CaptchaVerdict), appendRecaptcha (explicit registration in the context's captcha host), the MOD_RECAPTCHA / CMOD_RECAPTCHA config records and per-call keys, createRecaptchaVerifier (one https form POST, injectable fetch, 10 s). Auto-invoked when a server must verify Google reCAPTCHA tokens — the captcha guest sign-in, a strict per-route check, e-mail sign-in — when declaring the reCAPTCHA secret or site key, or when debugging a refused or unavailable reCAPTCHA check.
|
|
4
|
+
user-invocable: false
|
|
5
|
+
---
|
|
6
|
+
<!-- AUTO-GENERATED — do not edit. Regenerate via sync-agent-meta. -->
|
|
7
|
+
|
|
8
|
+
# @owlmeans/captcha-recaptcha
|
|
9
|
+
|
|
10
|
+
**Layer:** Server
|
|
11
|
+
**Repo:** OwlMeans connect (`@owlmeans/captcha-recaptcha`) — the Google-specific half; the host, the
|
|
12
|
+
policies and the guest sign-in are common's `@owlmeans/captcha` and `@owlmeans/server-auth`
|
|
13
|
+
**Install:** `"@owlmeans/captcha-recaptcha": "^0.2.0"` in `dependencies`
|
|
14
|
+
**Browser half:** `@owlmeans/web-captcha-recaptcha` (the v3 loader client, Google's notice, the v2 checkbox)
|
|
15
|
+
|
|
16
|
+
## Public API surface
|
|
17
|
+
|
|
18
|
+
| Symbol | Kind | Purpose |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| `appendRecaptcha(ctx, opts?)` | fn | Registers the provider in `ensureCaptchaService(ctx)`; keys default to the context's records, read per call |
|
|
21
|
+
| `makeRecaptchaProvider(opts?)` | fn | The `CaptchaProvider`: `verify(token, { action?, remoteIp? })` → `CaptchaVerdict`, `clientSettings()` → `{ provider: 'recaptcha', siteKey }` |
|
|
22
|
+
| `makeRecaptchaKeys(ctx)` | fn | `RecaptchaKeys` over the context's records: `secret()` = `MOD_RECAPTCHA.value`, `siteKey()` = `MOD_RECAPTCHA.siteKey` else `CMOD_RECAPTCHA.value` |
|
|
23
|
+
| `createRecaptchaVerifier(opts?)` | fn | siteverify: one form POST (`url` https only, `fetch` injectable, `timeout` default 10 s) |
|
|
24
|
+
| `RECAPTCHA_PROVIDER` | const | `'recaptcha'` — the provider id (settings, `MOD_CAPTCHA.provider`, the browser client) |
|
|
25
|
+
| `MOD_RECAPTCHA`, `CMOD_RECAPTCHA` | const | `'_external:re-captcha'` (Backend: secret in `value`, optional `siteKey`), `'_client-external:re-captcha'` (Frontend: site key in `value`) — stored ids, unchanged since 0.1 |
|
|
26
|
+
| `RECAPTCHA_SITEVERIFY_URL`, `RECAPTCHA_VERIFY_TIMEOUT` | const | `https://www.google.com/recaptcha/api/siteverify`, `10_000` |
|
|
27
|
+
| `RecaptchaProviderOptions` | interface | `{ id?, secret?, siteKey?, keys?, url?, fetch?, timeout? }` — fixed values win over `keys` |
|
|
28
|
+
| `RecaptchaKeys`, `RecaptchaRecord`, `RecaptchaResponse`, `RecaptchaRequest`, `RecaptchaFetch`, `RecaptchaVerifier`, `RecaptchaVerifierOptions`, `RecaptchaProvider` | types | |
|
|
29
|
+
|
|
30
|
+
## Wiring
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
// config.ts — the provider's records; the host record MOD_CAPTCHA only where the guest sign-in is wanted
|
|
34
|
+
plugin(cfg, { value: backendConfigHelper.mounted('/etc/master-secret/recaptcha-secret') ?? '' }, MOD_RECAPTCHA)
|
|
35
|
+
clientPlugin(cfg, '/etc/app-config/recaptcha-site-key', CMOD_RECAPTCHA) // advertised to the browser
|
|
36
|
+
plugin(cfg, { provider: RECAPTCHA_PROVIDER, hostnames: '…', minScore: '…', actions: 'inquiry' }, MOD_CAPTCHA)
|
|
37
|
+
|
|
38
|
+
// context.ts — explicit registration, never a side-effect import
|
|
39
|
+
appendRecaptcha(context)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Keys held elsewhere (a config block resolved in place) go in as getters, read per call:
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
appendRecaptcha(context, { keys: { secret: () => cfg.emailAuth.captcha.secret, siteKey: () => cfg.emailAuth.captcha.siteKey } })
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Behaviour
|
|
49
|
+
|
|
50
|
+
- **Verdict mapping** — `success`; `score`, `action`, `hostname` as Google reports them (a v2 checkbox
|
|
51
|
+
answer has no score or action); `challenge_ts` → `at`; `error-codes` → `errors`. The policies of
|
|
52
|
+
`@owlmeans/captcha` then judge it (`captcha:<errors>`, `captcha:score`, …).
|
|
53
|
+
- **No secret, no question** — `verify` without a secret throws `AuthUnavailable('captcha:config')`,
|
|
54
|
+
logged once (`auth.captcha.config`); Google is never asked with an empty secret.
|
|
55
|
+
- **Unreachable or unreadable Google** — `AuthUnavailable('captcha')` (503), logged at warn
|
|
56
|
+
(`auth.captcha.unavailable`); a refused token is a verdict, never an error.
|
|
57
|
+
- **Keys per call** — a record value that is empty or still an unresolved `/…` path counts as none,
|
|
58
|
+
so a deployment without the mounted secret boots and answers 503 instead of crash-looping.
|
|
59
|
+
- **Registering turns nothing on by itself** — the guest sign-in needs the host's `MOD_CAPTCHA`
|
|
60
|
+
record, a strict check its own `CaptchaSettings`. A process that must not offer the guest sign-in
|
|
61
|
+
(e.g. one serving ungated `/authentication/*` routes) registers the provider and declares no
|
|
62
|
+
`MOD_CAPTCHA`.
|
|
63
|
+
- `RECAPTCHA_PROVIDER` is the wire id the browser picks its client by: keep it equal to
|
|
64
|
+
`@owlmeans/web-captcha-recaptcha`'s.
|
|
65
|
+
|
|
66
|
+
## Tests
|
|
67
|
+
|
|
68
|
+
`bun test ./tests` — category A: siteverify over an injected `fetch` (no network), the verdict
|
|
69
|
+
mapping, the keys, and `appendRecaptcha` against the real captcha host and `makeCaptchaCheck`.
|
|
70
|
+
|
|
71
|
+
## External docs
|
|
72
|
+
|
|
73
|
+
- https://developers.google.com/recaptcha/docs/verify — siteverify: form-encoded `secret` + `response` (+ `remoteip`); answers `success`, `challenge_ts`, `hostname`, `score`, `action`, `error-codes`; a token is verifiable once, within two minutes
|
|
74
|
+
- https://developers.google.com/recaptcha/docs/v3 — scores 0.0–1.0 and the action come back from siteverify; the site picks the threshold
|
|
75
|
+
|
|
76
|
+
## Related
|
|
77
|
+
|
|
78
|
+
`captcha` (the host and policies, common) · `server-auth` (the guest `captcha` plugin and guard) ·
|
|
79
|
+
`server-auth-email` (the strict check) · `web-captcha-recaptcha` (the browser half)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { BasicConfig, BasicContext } from '@owlmeans/context';
|
|
2
|
+
import type { RecaptchaProviderOptions } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Register the reCAPTCHA provider in the context's captcha host. Its keys default to the context's
|
|
5
|
+
* `MOD_RECAPTCHA` record (secret in `value`, optional `siteKey`) and `CMOD_RECAPTCHA` client record
|
|
6
|
+
* (site key), read per call; `options.secret` / `options.siteKey` / `options.keys` replace them.
|
|
7
|
+
*
|
|
8
|
+
* Registering the provider turns nothing on by itself: the captcha guest sign-in needs the host's
|
|
9
|
+
* `MOD_CAPTCHA` record, a strict check its own settings.
|
|
10
|
+
*/
|
|
11
|
+
export declare const appendRecaptcha: <C extends BasicConfig, T extends BasicContext<C>>(context: T, options?: RecaptchaProviderOptions) => T;
|
|
12
|
+
//# sourceMappingURL=append.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"append.d.ts","sourceRoot":"","sources":["../src/append.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAGlE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAE1D;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,CAAC,SAAS,WAAW,EAAE,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC,WACrE,CAAC,YAAW,wBAAwB,KAC5C,CAIF,CAAA"}
|
package/build/append.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ensureCaptchaService } from '@owlmeans/captcha';
|
|
2
|
+
import { makeRecaptchaKeys } from './keys.js';
|
|
3
|
+
import { makeRecaptchaProvider } from './provider.js';
|
|
4
|
+
/**
|
|
5
|
+
* Register the reCAPTCHA provider in the context's captcha host. Its keys default to the context's
|
|
6
|
+
* `MOD_RECAPTCHA` record (secret in `value`, optional `siteKey`) and `CMOD_RECAPTCHA` client record
|
|
7
|
+
* (site key), read per call; `options.secret` / `options.siteKey` / `options.keys` replace them.
|
|
8
|
+
*
|
|
9
|
+
* Registering the provider turns nothing on by itself: the captcha guest sign-in needs the host's
|
|
10
|
+
* `MOD_CAPTCHA` record, a strict check its own settings.
|
|
11
|
+
*/
|
|
12
|
+
export const appendRecaptcha = (context, options = {}) => {
|
|
13
|
+
ensureCaptchaService(context).register(makeRecaptchaProvider({ keys: makeRecaptchaKeys(context), ...options }));
|
|
14
|
+
return context;
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=append.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"append.js","sourceRoot":"","sources":["../src/append.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAA;AAExD,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAA;AAGrD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,OAAU,EAAE,OAAO,GAA6B,EAAE,EAC/C,EAAE;IACL,oBAAoB,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,IAAI,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAA;IAE/G,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider id of Google reCAPTCHA — what `MOD_CAPTCHA.provider`, captcha settings and the
|
|
3
|
+
* browser client (`@owlmeans/web-captcha-recaptcha`) name it by.
|
|
4
|
+
*/
|
|
5
|
+
export declare const RECAPTCHA_PROVIDER = "recaptcha";
|
|
6
|
+
/**
|
|
7
|
+
* The provider's record of a server config (`RecaptchaRecord`): the siteverify secret in `value`
|
|
8
|
+
* and, optionally, the site key. A Backend record — never advertised.
|
|
9
|
+
*/
|
|
10
|
+
export declare const MOD_RECAPTCHA = "_external:re-captcha";
|
|
11
|
+
/**
|
|
12
|
+
* The client record a browser reads its site key from (`value`), advertised to the browser as a
|
|
13
|
+
* Frontend record; the provider reads it too when `MOD_RECAPTCHA` carries no site key.
|
|
14
|
+
*/
|
|
15
|
+
export declare const CMOD_RECAPTCHA = "_client-external:re-captcha";
|
|
16
|
+
/** Google's siteverify endpoint — always https. */
|
|
17
|
+
export declare const RECAPTCHA_SITEVERIFY_URL = "https://www.google.com/recaptcha/api/siteverify";
|
|
18
|
+
/** How long the verifier waits for Google, in ms. */
|
|
19
|
+
export declare const RECAPTCHA_VERIFY_TIMEOUT = 10000;
|
|
20
|
+
//# sourceMappingURL=consts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,kBAAkB,cAAc,CAAA;AAE7C;;;GAGG;AACH,eAAO,MAAM,aAAa,yBAAyB,CAAA;AAEnD;;;GAGG;AACH,eAAO,MAAM,cAAc,gCAAgC,CAAA;AAE3D,mDAAmD;AACnD,eAAO,MAAM,wBAAwB,oDAAoD,CAAA;AAEzF,qDAAqD;AACrD,eAAO,MAAM,wBAAwB,QAAS,CAAA"}
|
package/build/consts.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider id of Google reCAPTCHA — what `MOD_CAPTCHA.provider`, captcha settings and the
|
|
3
|
+
* browser client (`@owlmeans/web-captcha-recaptcha`) name it by.
|
|
4
|
+
*/
|
|
5
|
+
export const RECAPTCHA_PROVIDER = 'recaptcha';
|
|
6
|
+
/**
|
|
7
|
+
* The provider's record of a server config (`RecaptchaRecord`): the siteverify secret in `value`
|
|
8
|
+
* and, optionally, the site key. A Backend record — never advertised.
|
|
9
|
+
*/
|
|
10
|
+
export const MOD_RECAPTCHA = '_external:re-captcha';
|
|
11
|
+
/**
|
|
12
|
+
* The client record a browser reads its site key from (`value`), advertised to the browser as a
|
|
13
|
+
* Frontend record; the provider reads it too when `MOD_RECAPTCHA` carries no site key.
|
|
14
|
+
*/
|
|
15
|
+
export const CMOD_RECAPTCHA = '_client-external:re-captcha';
|
|
16
|
+
/** Google's siteverify endpoint — always https. */
|
|
17
|
+
export const RECAPTCHA_SITEVERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
|
|
18
|
+
/** How long the verifier waits for Google, in ms. */
|
|
19
|
+
export const RECAPTCHA_VERIFY_TIMEOUT = 10_000;
|
|
20
|
+
//# sourceMappingURL=consts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consts.js","sourceRoot":"","sources":["../src/consts.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,WAAW,CAAA;AAE7C;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,sBAAsB,CAAA;AAEnD;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,6BAA6B,CAAA;AAE3D,mDAAmD;AACnD,MAAM,CAAC,MAAM,wBAAwB,GAAG,iDAAiD,CAAA;AAEzF,qDAAqD;AACrD,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAA"}
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mBAAmB,YAAY,CAAA;AAC/B,cAAc,aAAa,CAAA;AAC3B,cAAc,eAAe,CAAA;AAC7B,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,aAAa,CAAA"}
|
package/build/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,aAAa,CAAA;AAC3B,cAAc,eAAe,CAAA;AAC7B,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,aAAa,CAAA"}
|
package/build/keys.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { BasicConfig, BasicContext } from '@owlmeans/context';
|
|
2
|
+
import type { RecaptchaKeys } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* The keys of a context's reCAPTCHA records, read per call: the secret is `MOD_RECAPTCHA.value`, the
|
|
5
|
+
* site key `MOD_RECAPTCHA.siteKey` or else the `CMOD_RECAPTCHA` client record's `value`. A value that
|
|
6
|
+
* is empty — or still an unresolved `/…` file path — counts as none.
|
|
7
|
+
*/
|
|
8
|
+
export declare const makeRecaptchaKeys: <C extends BasicConfig, T extends BasicContext<C>>(context: T) => RecaptchaKeys;
|
|
9
|
+
//# sourceMappingURL=keys.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAElE,OAAO,KAAK,EAAE,aAAa,EAAmB,MAAM,YAAY,CAAA;AAEhE;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,WAAW,EAAE,CAAC,SAAS,YAAY,CAAC,CAAC,CAAC,WAAW,CAAC,KAAG,aAgBhG,CAAA"}
|
package/build/keys.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { PLUGIN_RECORD } from '@owlmeans/config';
|
|
2
|
+
import { CMOD_RECAPTCHA, MOD_RECAPTCHA } from './consts.js';
|
|
3
|
+
/**
|
|
4
|
+
* The keys of a context's reCAPTCHA records, read per call: the secret is `MOD_RECAPTCHA.value`, the
|
|
5
|
+
* site key `MOD_RECAPTCHA.siteKey` or else the `CMOD_RECAPTCHA` client record's `value`. A value that
|
|
6
|
+
* is empty — or still an unresolved `/…` file path — counts as none.
|
|
7
|
+
*/
|
|
8
|
+
export const makeRecaptchaKeys = (context) => {
|
|
9
|
+
const recordOf = (id) => context.cfg[PLUGIN_RECORD]?.find(entry => entry.id === id);
|
|
10
|
+
const textOf = (value) => {
|
|
11
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
12
|
+
return text !== '' && !text.startsWith('/') ? text : null;
|
|
13
|
+
};
|
|
14
|
+
const secret = () => textOf(recordOf(MOD_RECAPTCHA)?.value);
|
|
15
|
+
const siteKey = () => textOf(recordOf(MOD_RECAPTCHA)?.siteKey) ?? textOf(recordOf(CMOD_RECAPTCHA)?.value);
|
|
16
|
+
return { secret, siteKey };
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=keys.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAGhD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAG3D;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAmD,OAAU,EAAiB,EAAE;IAC/G,MAAM,QAAQ,GAAG,CAAC,EAAU,EAA+B,EAAE,CAC1D,OAAO,CAAC,GAA4C,CAAC,aAAa,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC,CAAA;IAEtG,MAAM,MAAM,GAAG,CAAC,KAAc,EAAiB,EAAE;QAC/C,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAE1D,OAAO,IAAI,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAA;IAC3D,CAAC,CAAA;IAED,MAAM,MAAM,GAA4B,GAAG,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,KAAK,CAAC,CAAA;IAEpF,MAAM,OAAO,GAA6B,GAAG,EAAE,CAC7C,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,KAAK,CAAC,CAAA;IAErF,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAA;AAC5B,CAAC,CAAA"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { RecaptchaProvider, RecaptchaProviderOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The Google reCAPTCHA provider of `@owlmeans/captcha`: siteverify for a checkbox (v2) or a
|
|
4
|
+
* score-based (v3) token, its answer mapped onto the neutral verdict (`score`, `action`,
|
|
5
|
+
* `hostname`, `challenge_ts` → `at`, `error-codes` → `errors`). The keys come from the options —
|
|
6
|
+
* fixed values first, then `keys` read per call.
|
|
7
|
+
*
|
|
8
|
+
* Without a secret nothing is asked: `AuthUnavailable('captcha:config')`, logged once.
|
|
9
|
+
*
|
|
10
|
+
* @throws {SyntaxError} for a siteverify address that is not https.
|
|
11
|
+
*/
|
|
12
|
+
export declare const makeRecaptchaProvider: (options?: RecaptchaProviderOptions) => RecaptchaProvider;
|
|
13
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,wBAAwB,EAAqB,MAAM,YAAY,CAAA;AAKhG;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,aAAa,wBAAwB,KAAQ,iBAqC9E,CAAA"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { AuthUnavailable } from '@owlmeans/auth';
|
|
2
|
+
import { logger } from '@owlmeans/log';
|
|
3
|
+
import { RECAPTCHA_PROVIDER } from './consts.js';
|
|
4
|
+
import { createRecaptchaVerifier } from './verifier.js';
|
|
5
|
+
const log = logger('captcha-recaptcha');
|
|
6
|
+
/**
|
|
7
|
+
* The Google reCAPTCHA provider of `@owlmeans/captcha`: siteverify for a checkbox (v2) or a
|
|
8
|
+
* score-based (v3) token, its answer mapped onto the neutral verdict (`score`, `action`,
|
|
9
|
+
* `hostname`, `challenge_ts` → `at`, `error-codes` → `errors`). The keys come from the options —
|
|
10
|
+
* fixed values first, then `keys` read per call.
|
|
11
|
+
*
|
|
12
|
+
* Without a secret nothing is asked: `AuthUnavailable('captcha:config')`, logged once.
|
|
13
|
+
*
|
|
14
|
+
* @throws {SyntaxError} for a siteverify address that is not https.
|
|
15
|
+
*/
|
|
16
|
+
export const makeRecaptchaProvider = (options = {}) => {
|
|
17
|
+
const id = options.id ?? RECAPTCHA_PROVIDER;
|
|
18
|
+
const verifier = createRecaptchaVerifier(options);
|
|
19
|
+
let reported = false;
|
|
20
|
+
const textOf = (value) => typeof value === 'string' ? value.trim() : '';
|
|
21
|
+
const secretOf = () => textOf(options.secret) || textOf(options.keys?.secret());
|
|
22
|
+
const siteKeyOf = () => textOf(options.siteKey) || textOf(options.keys?.siteKey());
|
|
23
|
+
const verdictOf = (answer) => ({
|
|
24
|
+
success: answer.success === true,
|
|
25
|
+
...(typeof answer.score === 'number' ? { score: answer.score } : {}),
|
|
26
|
+
...(typeof answer.action === 'string' ? { action: answer.action } : {}),
|
|
27
|
+
...(typeof answer.hostname === 'string' ? { hostname: answer.hostname } : {}),
|
|
28
|
+
...(typeof answer.challenge_ts === 'string' && answer.challenge_ts !== '' ? { at: answer.challenge_ts } : {}),
|
|
29
|
+
...(Array.isArray(answer['error-codes']) ? { errors: answer['error-codes'] } : {}),
|
|
30
|
+
});
|
|
31
|
+
const verify = async (token, verifyOptions) => {
|
|
32
|
+
const secret = secretOf();
|
|
33
|
+
if (secret === '') {
|
|
34
|
+
if (!reported) {
|
|
35
|
+
reported = true;
|
|
36
|
+
log.error('reCAPTCHA has no secret: no token can be verified', { provider: id }, { event: 'auth.captcha.config' });
|
|
37
|
+
}
|
|
38
|
+
throw new AuthUnavailable('captcha:config');
|
|
39
|
+
}
|
|
40
|
+
const remoteip = textOf(verifyOptions?.remoteIp);
|
|
41
|
+
return verdictOf(await verifier.verify({ secret, response: token, ...(remoteip !== '' ? { remoteip } : {}) }));
|
|
42
|
+
};
|
|
43
|
+
const clientSettings = () => ({ provider: id, siteKey: siteKeyOf() });
|
|
44
|
+
return { id, verify, clientSettings };
|
|
45
|
+
};
|
|
46
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAEhD,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAA;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAEhD,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAA;AAEvD,MAAM,GAAG,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAA;AAEvC;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,OAAO,GAA6B,EAAE,EAAqB,EAAE;IACjG,MAAM,EAAE,GAAG,OAAO,CAAC,EAAE,IAAI,kBAAkB,CAAA;IAC3C,MAAM,QAAQ,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAA;IACjD,IAAI,QAAQ,GAAG,KAAK,CAAA;IAEpB,MAAM,MAAM,GAAG,CAAC,KAAgC,EAAU,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;IAE1G,MAAM,QAAQ,GAAG,GAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;IAEvF,MAAM,SAAS,GAAG,GAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAA;IAE1F,MAAM,SAAS,GAAG,CAAC,MAAyB,EAAkB,EAAE,CAAC,CAAC;QAChE,OAAO,EAAE,MAAM,CAAC,OAAO,KAAK,IAAI;QAChC,GAAG,CAAC,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACpE,GAAG,CAAC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvE,GAAG,CAAC,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7E,GAAG,CAAC,OAAO,MAAM,CAAC,YAAY,KAAK,QAAQ,IAAI,MAAM,CAAC,YAAY,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7G,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACnF,CAAC,CAAA;IAEF,MAAM,MAAM,GAAgC,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QACzE,MAAM,MAAM,GAAG,QAAQ,EAAE,CAAA;QACzB,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YAClB,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,QAAQ,GAAG,IAAI,CAAA;gBACf,GAAG,CAAC,KAAK,CAAC,mDAAmD,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,qBAAqB,EAAE,CAAC,CAAA;YACpH,CAAC;YACD,MAAM,IAAI,eAAe,CAAC,gBAAgB,CAAC,CAAA;QAC7C,CAAC;QACD,MAAM,QAAQ,GAAG,MAAM,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAA;QAEhD,OAAO,SAAS,CAAC,MAAM,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;IAChH,CAAC,CAAA;IAED,MAAM,cAAc,GAAwC,GAAG,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,CAAC,CAAA;IAE1G,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,cAAc,EAAE,CAAA;AACvC,CAAC,CAAA"}
|
package/build/types.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { CaptchaProvider } from '@owlmeans/captcha';
|
|
2
|
+
import type { PluginConfig } from '@owlmeans/config';
|
|
3
|
+
/** Google's siteverify answer, for a checkbox (v2) or a score-based (v3) token. */
|
|
4
|
+
export interface RecaptchaResponse {
|
|
5
|
+
success: boolean;
|
|
6
|
+
/** When the challenge was solved, as an ISO date-time string. */
|
|
7
|
+
challenge_ts: string;
|
|
8
|
+
/** The host of the page the token was solved on. */
|
|
9
|
+
hostname: string;
|
|
10
|
+
/** Score-based keys only: 0.0 (a bot) … 1.0 (a person). */
|
|
11
|
+
score?: number;
|
|
12
|
+
/** Score-based keys only: the action the page named when it asked for the token. */
|
|
13
|
+
action?: string;
|
|
14
|
+
'error-codes'?: string[];
|
|
15
|
+
}
|
|
16
|
+
/** The siteverify form: the key's secret, the token the browser got, optionally the browser's IP. */
|
|
17
|
+
export interface RecaptchaRequest {
|
|
18
|
+
secret: string;
|
|
19
|
+
response: string;
|
|
20
|
+
remoteip?: string;
|
|
21
|
+
}
|
|
22
|
+
/** The one call the verifier makes — `fetch`, or a stand-in a test injects. */
|
|
23
|
+
export interface RecaptchaFetch {
|
|
24
|
+
(url: string, init: RequestInit): Promise<Response>;
|
|
25
|
+
}
|
|
26
|
+
export interface RecaptchaVerifierOptions {
|
|
27
|
+
/** The siteverify address; must be https. Default `RECAPTCHA_SITEVERIFY_URL`. */
|
|
28
|
+
url?: string;
|
|
29
|
+
/** Default: the global `fetch`. */
|
|
30
|
+
fetch?: RecaptchaFetch;
|
|
31
|
+
/** Milliseconds before the call is abandoned. Default `RECAPTCHA_VERIFY_TIMEOUT`. */
|
|
32
|
+
timeout?: number;
|
|
33
|
+
}
|
|
34
|
+
/** One form POST to Google's siteverify. It holds no state and touches no context. */
|
|
35
|
+
export interface RecaptchaVerifier {
|
|
36
|
+
/**
|
|
37
|
+
* Google's answer for one token. A refusal is an answer (`success: false`), not an error.
|
|
38
|
+
*
|
|
39
|
+
* @throws {AuthUnavailable} `captcha` when Google cannot be asked or answers something unreadable.
|
|
40
|
+
*/
|
|
41
|
+
verify: (request: RecaptchaRequest) => Promise<RecaptchaResponse>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The `MOD_RECAPTCHA` record of a server config: the siteverify secret in `value` (a mounted secret
|
|
45
|
+
* file) and, optionally, the browser's site key. The policy is the host's `MOD_CAPTCHA` record.
|
|
46
|
+
*/
|
|
47
|
+
export interface RecaptchaRecord extends PluginConfig {
|
|
48
|
+
/** The public site key; absent = the `CMOD_RECAPTCHA` client record's `value`. */
|
|
49
|
+
siteKey?: string;
|
|
50
|
+
}
|
|
51
|
+
/** Where the provider reads its keys — per call, so a config value resolved in place is seen. */
|
|
52
|
+
export interface RecaptchaKeys {
|
|
53
|
+
/** The siteverify secret; `null` when this environment holds none. */
|
|
54
|
+
secret: () => string | null;
|
|
55
|
+
/** The public site key; `null` when none is configured. */
|
|
56
|
+
siteKey: () => string | null;
|
|
57
|
+
}
|
|
58
|
+
export interface RecaptchaProviderOptions extends RecaptchaVerifierOptions {
|
|
59
|
+
/** The provider id. Default `RECAPTCHA_PROVIDER`. */
|
|
60
|
+
id?: string;
|
|
61
|
+
/** A fixed secret; wins over `keys`. */
|
|
62
|
+
secret?: string;
|
|
63
|
+
/** A fixed site key; wins over `keys`. */
|
|
64
|
+
siteKey?: string;
|
|
65
|
+
/**
|
|
66
|
+
* Where the keys are read per call. `appendRecaptcha` defaults it to the context's
|
|
67
|
+
* `MOD_RECAPTCHA` / `CMOD_RECAPTCHA` records; without it only `secret` / `siteKey` count.
|
|
68
|
+
*/
|
|
69
|
+
keys?: RecaptchaKeys;
|
|
70
|
+
}
|
|
71
|
+
/** The reCAPTCHA provider of `@owlmeans/captcha`. */
|
|
72
|
+
export interface RecaptchaProvider extends CaptchaProvider {
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAEpD,mFAAmF;AACnF,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAA;IAChB,iEAAiE;IACjE,YAAY,EAAE,MAAM,CAAA;IACpB,oDAAoD;IACpD,QAAQ,EAAE,MAAM,CAAA;IAChB,2DAA2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,oFAAoF;IACpF,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,CAAC,EAAE,MAAM,EAAE,CAAA;CACzB;AAED,qGAAqG;AACrG,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,+EAA+E;AAC/E,MAAM,WAAW,cAAc;IAC7B,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAA;CACpD;AAED,MAAM,WAAW,wBAAwB;IACvC,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,mCAAmC;IACnC,KAAK,CAAC,EAAE,cAAc,CAAA;IACtB,qFAAqF;IACrF,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,sFAAsF;AACtF,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,MAAM,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAA;CAClE;AAED;;;GAGG;AACH,MAAM,WAAW,eAAgB,SAAQ,YAAY;IACnD,kFAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,iGAAiG;AACjG,MAAM,WAAW,aAAa;IAC5B,sEAAsE;IACtE,MAAM,EAAE,MAAM,MAAM,GAAG,IAAI,CAAA;IAC3B,2DAA2D;IAC3D,OAAO,EAAE,MAAM,MAAM,GAAG,IAAI,CAAA;CAC7B;AAED,MAAM,WAAW,wBAAyB,SAAQ,wBAAwB;IACxE,qDAAqD;IACrD,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,IAAI,CAAC,EAAE,aAAa,CAAA;CACrB;AAED,qDAAqD;AACrD,MAAM,WAAW,iBAAkB,SAAQ,eAAe;CAAG"}
|
package/build/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RecaptchaVerifier, RecaptchaVerifierOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Google's siteverify: one https form POST per token.
|
|
4
|
+
*
|
|
5
|
+
* @throws {SyntaxError} for a siteverify address that is not https.
|
|
6
|
+
*/
|
|
7
|
+
export declare const createRecaptchaVerifier: (options?: RecaptchaVerifierOptions) => RecaptchaVerifier;
|
|
8
|
+
//# sourceMappingURL=verifier.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verifier.d.ts","sourceRoot":"","sources":["../src/verifier.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAqB,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAIhG;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,aAAa,wBAAwB,KAAQ,iBA+ChF,CAAA"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { AuthUnavailable } from '@owlmeans/auth';
|
|
2
|
+
import { logger } from '@owlmeans/log';
|
|
3
|
+
import { RECAPTCHA_SITEVERIFY_URL, RECAPTCHA_VERIFY_TIMEOUT } from './consts.js';
|
|
4
|
+
const log = logger('captcha-recaptcha');
|
|
5
|
+
/**
|
|
6
|
+
* Google's siteverify: one https form POST per token.
|
|
7
|
+
*
|
|
8
|
+
* @throws {SyntaxError} for a siteverify address that is not https.
|
|
9
|
+
*/
|
|
10
|
+
export const createRecaptchaVerifier = (options = {}) => {
|
|
11
|
+
const url = options.url ?? RECAPTCHA_SITEVERIFY_URL;
|
|
12
|
+
if (!url.startsWith('https://')) {
|
|
13
|
+
throw new SyntaxError(`reCAPTCHA siteverify must be https: ${url}`);
|
|
14
|
+
}
|
|
15
|
+
const timeout = options.timeout ?? RECAPTCHA_VERIFY_TIMEOUT;
|
|
16
|
+
/** The answer, when it has the shape of one. */
|
|
17
|
+
const readAnswer = async (response) => {
|
|
18
|
+
try {
|
|
19
|
+
const answer = await response.json();
|
|
20
|
+
return answer != null && typeof answer === 'object' && typeof answer.success === 'boolean' ? answer : null;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const verify = async (request) => {
|
|
27
|
+
const body = new URLSearchParams({ secret: request.secret, response: request.response });
|
|
28
|
+
if (request.remoteip != null && request.remoteip !== '') {
|
|
29
|
+
body.set('remoteip', request.remoteip);
|
|
30
|
+
}
|
|
31
|
+
const send = options.fetch ?? fetch;
|
|
32
|
+
let response;
|
|
33
|
+
try {
|
|
34
|
+
response = await send(url, {
|
|
35
|
+
method: 'POST',
|
|
36
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
37
|
+
body,
|
|
38
|
+
signal: AbortSignal.timeout(timeout),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
log.warn('reCAPTCHA siteverify unreachable', { error }, { event: 'auth.captcha.unavailable' });
|
|
43
|
+
throw new AuthUnavailable('captcha');
|
|
44
|
+
}
|
|
45
|
+
const answer = response.ok ? await readAnswer(response) : null;
|
|
46
|
+
if (answer == null) {
|
|
47
|
+
log.warn('reCAPTCHA siteverify answered unusably', { status: response.status }, { event: 'auth.captcha.unavailable' });
|
|
48
|
+
throw new AuthUnavailable('captcha');
|
|
49
|
+
}
|
|
50
|
+
return answer;
|
|
51
|
+
};
|
|
52
|
+
return { verify };
|
|
53
|
+
};
|
|
54
|
+
//# sourceMappingURL=verifier.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verifier.js","sourceRoot":"","sources":["../src/verifier.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAA;AACtC,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA;AAGhF,MAAM,GAAG,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAA;AAEvC;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,OAAO,GAA6B,EAAE,EAAqB,EAAE;IACnG,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,wBAAwB,CAAA;IACnD,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAChC,MAAM,IAAI,WAAW,CAAC,uCAAuC,GAAG,EAAE,CAAC,CAAA;IACrE,CAAC;IACD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,wBAAwB,CAAA;IAE3D,gDAAgD;IAChD,MAAM,UAAU,GAAG,KAAK,EAAE,QAAkB,EAAqC,EAAE;QACjF,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAA8B,CAAA;YAChE,OAAO,MAAM,IAAI,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAA;QAC5G,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC,CAAA;IAED,MAAM,MAAM,GAAgC,KAAK,EAAC,OAAO,EAAC,EAAE;QAC1D,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAA;QACxF,IAAI,OAAO,CAAC,QAAQ,IAAI,IAAI,IAAI,OAAO,CAAC,QAAQ,KAAK,EAAE,EAAE,CAAC;YACxD,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAA;QACxC,CAAC;QAED,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAA;QACnC,IAAI,QAAkB,CAAA;QACtB,IAAI,CAAC;YACH,QAAQ,GAAG,MAAM,IAAI,CAAC,GAAG,EAAE;gBACzB,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE,EAAE,cAAc,EAAE,mCAAmC,EAAE;gBAChE,IAAI;gBACJ,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC;aACrC,CAAC,CAAA;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,IAAI,CAAC,kCAAkC,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,0BAA0B,EAAE,CAAC,CAAA;YAC9F,MAAM,IAAI,eAAe,CAAC,SAAS,CAAC,CAAA;QACtC,CAAC;QAED,MAAM,MAAM,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;QAC9D,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;YACnB,GAAG,CAAC,IAAI,CAAC,wCAAwC,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,0BAA0B,EAAE,CAAC,CAAA;YACtH,MAAM,IAAI,eAAe,CAAC,SAAS,CAAC,CAAA;QACtC,CAAC;QAED,OAAO,MAAM,CAAA;IACf,CAAC,CAAA;IAED,OAAO,EAAE,MAAM,EAAE,CAAA;AACnB,CAAC,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owlmeans/captcha-recaptcha",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Google reCAPTCHA provider for @owlmeans/captcha: siteverify mapped onto the neutral verdict, its config records and the append helper that registers it.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://owlmeans.com/docs/",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/owlmeans/connect.git",
|
|
10
|
+
"directory": "packages/captcha-recaptcha"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/owlmeans/connect/issues"
|
|
14
|
+
},
|
|
15
|
+
"author": "Igor Tkachenko <igor.tkachenko@owlmeans.com> (https://owlmeans.com)",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -b",
|
|
19
|
+
"dev": "sleep 4 && nodemon -e ts,tsx,json --watch src --exec \"tsc -p ./tsconfig.json\"",
|
|
20
|
+
"watch": "tsc -b -w --preserveWatchOutput --pretty",
|
|
21
|
+
"test": "bun test ./tests"
|
|
22
|
+
},
|
|
23
|
+
"main": "build/index.js",
|
|
24
|
+
"module": "build/index.js",
|
|
25
|
+
"types": "build/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"import": "./build/index.js",
|
|
29
|
+
"require": "./build/index.js",
|
|
30
|
+
"default": "./build/index.js",
|
|
31
|
+
"module": "./build/index.js",
|
|
32
|
+
"types": "./build/index.d.ts"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@owlmeans/auth": "^0.2.0",
|
|
37
|
+
"@owlmeans/captcha": "^0.2.0",
|
|
38
|
+
"@owlmeans/config": "^0.2.0",
|
|
39
|
+
"@owlmeans/context": "^0.2.0",
|
|
40
|
+
"@owlmeans/log": "^0.2.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@owlmeans/dep-config": "^0.2.0",
|
|
44
|
+
"@owlmeans/test": "^0.2.0",
|
|
45
|
+
"@types/bun": "^1.4.4",
|
|
46
|
+
"@types/node": "^26.6.5",
|
|
47
|
+
"nodemon": "^3.1.14",
|
|
48
|
+
"typescript": "^7.0.2"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/append.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ensureCaptchaService } from '@owlmeans/captcha'
|
|
2
|
+
import type { BasicConfig, BasicContext } from '@owlmeans/context'
|
|
3
|
+
import { makeRecaptchaKeys } from './keys.js'
|
|
4
|
+
import { makeRecaptchaProvider } from './provider.js'
|
|
5
|
+
import type { RecaptchaProviderOptions } from './types.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Register the reCAPTCHA provider in the context's captcha host. Its keys default to the context's
|
|
9
|
+
* `MOD_RECAPTCHA` record (secret in `value`, optional `siteKey`) and `CMOD_RECAPTCHA` client record
|
|
10
|
+
* (site key), read per call; `options.secret` / `options.siteKey` / `options.keys` replace them.
|
|
11
|
+
*
|
|
12
|
+
* Registering the provider turns nothing on by itself: the captcha guest sign-in needs the host's
|
|
13
|
+
* `MOD_CAPTCHA` record, a strict check its own settings.
|
|
14
|
+
*/
|
|
15
|
+
export const appendRecaptcha = <C extends BasicConfig, T extends BasicContext<C>>(
|
|
16
|
+
context: T, options: RecaptchaProviderOptions = {}
|
|
17
|
+
): T => {
|
|
18
|
+
ensureCaptchaService(context).register(makeRecaptchaProvider({ keys: makeRecaptchaKeys(context), ...options }))
|
|
19
|
+
|
|
20
|
+
return context
|
|
21
|
+
}
|
package/src/consts.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider id of Google reCAPTCHA — what `MOD_CAPTCHA.provider`, captcha settings and the
|
|
3
|
+
* browser client (`@owlmeans/web-captcha-recaptcha`) name it by.
|
|
4
|
+
*/
|
|
5
|
+
export const RECAPTCHA_PROVIDER = 'recaptcha'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The provider's record of a server config (`RecaptchaRecord`): the siteverify secret in `value`
|
|
9
|
+
* and, optionally, the site key. A Backend record — never advertised.
|
|
10
|
+
*/
|
|
11
|
+
export const MOD_RECAPTCHA = '_external:re-captcha'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The client record a browser reads its site key from (`value`), advertised to the browser as a
|
|
15
|
+
* Frontend record; the provider reads it too when `MOD_RECAPTCHA` carries no site key.
|
|
16
|
+
*/
|
|
17
|
+
export const CMOD_RECAPTCHA = '_client-external:re-captcha'
|
|
18
|
+
|
|
19
|
+
/** Google's siteverify endpoint — always https. */
|
|
20
|
+
export const RECAPTCHA_SITEVERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'
|
|
21
|
+
|
|
22
|
+
/** How long the verifier waits for Google, in ms. */
|
|
23
|
+
export const RECAPTCHA_VERIFY_TIMEOUT = 10_000
|
package/src/index.ts
ADDED
package/src/keys.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { PLUGIN_RECORD } from '@owlmeans/config'
|
|
2
|
+
import type { PluginConfig } from '@owlmeans/config'
|
|
3
|
+
import type { BasicConfig, BasicContext } from '@owlmeans/context'
|
|
4
|
+
import { CMOD_RECAPTCHA, MOD_RECAPTCHA } from './consts.js'
|
|
5
|
+
import type { RecaptchaKeys, RecaptchaRecord } from './types.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The keys of a context's reCAPTCHA records, read per call: the secret is `MOD_RECAPTCHA.value`, the
|
|
9
|
+
* site key `MOD_RECAPTCHA.siteKey` or else the `CMOD_RECAPTCHA` client record's `value`. A value that
|
|
10
|
+
* is empty — or still an unresolved `/…` file path — counts as none.
|
|
11
|
+
*/
|
|
12
|
+
export const makeRecaptchaKeys = <C extends BasicConfig, T extends BasicContext<C>>(context: T): RecaptchaKeys => {
|
|
13
|
+
const recordOf = (id: string): RecaptchaRecord | undefined =>
|
|
14
|
+
(context.cfg as { [PLUGIN_RECORD]?: PluginConfig[] })[PLUGIN_RECORD]?.find(entry => entry.id === id)
|
|
15
|
+
|
|
16
|
+
const textOf = (value: unknown): string | null => {
|
|
17
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
18
|
+
|
|
19
|
+
return text !== '' && !text.startsWith('/') ? text : null
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const secret: RecaptchaKeys['secret'] = () => textOf(recordOf(MOD_RECAPTCHA)?.value)
|
|
23
|
+
|
|
24
|
+
const siteKey: RecaptchaKeys['siteKey'] = () =>
|
|
25
|
+
textOf(recordOf(MOD_RECAPTCHA)?.siteKey) ?? textOf(recordOf(CMOD_RECAPTCHA)?.value)
|
|
26
|
+
|
|
27
|
+
return { secret, siteKey }
|
|
28
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { AuthUnavailable } from '@owlmeans/auth'
|
|
2
|
+
import type { CaptchaVerdict } from '@owlmeans/captcha'
|
|
3
|
+
import { logger } from '@owlmeans/log'
|
|
4
|
+
import { RECAPTCHA_PROVIDER } from './consts.js'
|
|
5
|
+
import type { RecaptchaProvider, RecaptchaProviderOptions, RecaptchaResponse } from './types.js'
|
|
6
|
+
import { createRecaptchaVerifier } from './verifier.js'
|
|
7
|
+
|
|
8
|
+
const log = logger('captcha-recaptcha')
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The Google reCAPTCHA provider of `@owlmeans/captcha`: siteverify for a checkbox (v2) or a
|
|
12
|
+
* score-based (v3) token, its answer mapped onto the neutral verdict (`score`, `action`,
|
|
13
|
+
* `hostname`, `challenge_ts` → `at`, `error-codes` → `errors`). The keys come from the options —
|
|
14
|
+
* fixed values first, then `keys` read per call.
|
|
15
|
+
*
|
|
16
|
+
* Without a secret nothing is asked: `AuthUnavailable('captcha:config')`, logged once.
|
|
17
|
+
*
|
|
18
|
+
* @throws {SyntaxError} for a siteverify address that is not https.
|
|
19
|
+
*/
|
|
20
|
+
export const makeRecaptchaProvider = (options: RecaptchaProviderOptions = {}): RecaptchaProvider => {
|
|
21
|
+
const id = options.id ?? RECAPTCHA_PROVIDER
|
|
22
|
+
const verifier = createRecaptchaVerifier(options)
|
|
23
|
+
let reported = false
|
|
24
|
+
|
|
25
|
+
const textOf = (value: string | null | undefined): string => typeof value === 'string' ? value.trim() : ''
|
|
26
|
+
|
|
27
|
+
const secretOf = (): string => textOf(options.secret) || textOf(options.keys?.secret())
|
|
28
|
+
|
|
29
|
+
const siteKeyOf = (): string => textOf(options.siteKey) || textOf(options.keys?.siteKey())
|
|
30
|
+
|
|
31
|
+
const verdictOf = (answer: RecaptchaResponse): CaptchaVerdict => ({
|
|
32
|
+
success: answer.success === true,
|
|
33
|
+
...(typeof answer.score === 'number' ? { score: answer.score } : {}),
|
|
34
|
+
...(typeof answer.action === 'string' ? { action: answer.action } : {}),
|
|
35
|
+
...(typeof answer.hostname === 'string' ? { hostname: answer.hostname } : {}),
|
|
36
|
+
...(typeof answer.challenge_ts === 'string' && answer.challenge_ts !== '' ? { at: answer.challenge_ts } : {}),
|
|
37
|
+
...(Array.isArray(answer['error-codes']) ? { errors: answer['error-codes'] } : {}),
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
const verify: RecaptchaProvider['verify'] = async (token, verifyOptions) => {
|
|
41
|
+
const secret = secretOf()
|
|
42
|
+
if (secret === '') {
|
|
43
|
+
if (!reported) {
|
|
44
|
+
reported = true
|
|
45
|
+
log.error('reCAPTCHA has no secret: no token can be verified', { provider: id }, { event: 'auth.captcha.config' })
|
|
46
|
+
}
|
|
47
|
+
throw new AuthUnavailable('captcha:config')
|
|
48
|
+
}
|
|
49
|
+
const remoteip = textOf(verifyOptions?.remoteIp)
|
|
50
|
+
|
|
51
|
+
return verdictOf(await verifier.verify({ secret, response: token, ...(remoteip !== '' ? { remoteip } : {}) }))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const clientSettings: RecaptchaProvider['clientSettings'] = () => ({ provider: id, siteKey: siteKeyOf() })
|
|
55
|
+
|
|
56
|
+
return { id, verify, clientSettings }
|
|
57
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { CaptchaProvider } from '@owlmeans/captcha'
|
|
2
|
+
import type { PluginConfig } from '@owlmeans/config'
|
|
3
|
+
|
|
4
|
+
/** Google's siteverify answer, for a checkbox (v2) or a score-based (v3) token. */
|
|
5
|
+
export interface RecaptchaResponse {
|
|
6
|
+
success: boolean
|
|
7
|
+
/** When the challenge was solved, as an ISO date-time string. */
|
|
8
|
+
challenge_ts: string
|
|
9
|
+
/** The host of the page the token was solved on. */
|
|
10
|
+
hostname: string
|
|
11
|
+
/** Score-based keys only: 0.0 (a bot) … 1.0 (a person). */
|
|
12
|
+
score?: number
|
|
13
|
+
/** Score-based keys only: the action the page named when it asked for the token. */
|
|
14
|
+
action?: string
|
|
15
|
+
'error-codes'?: string[]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The siteverify form: the key's secret, the token the browser got, optionally the browser's IP. */
|
|
19
|
+
export interface RecaptchaRequest {
|
|
20
|
+
secret: string
|
|
21
|
+
response: string
|
|
22
|
+
remoteip?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The one call the verifier makes — `fetch`, or a stand-in a test injects. */
|
|
26
|
+
export interface RecaptchaFetch {
|
|
27
|
+
(url: string, init: RequestInit): Promise<Response>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface RecaptchaVerifierOptions {
|
|
31
|
+
/** The siteverify address; must be https. Default `RECAPTCHA_SITEVERIFY_URL`. */
|
|
32
|
+
url?: string
|
|
33
|
+
/** Default: the global `fetch`. */
|
|
34
|
+
fetch?: RecaptchaFetch
|
|
35
|
+
/** Milliseconds before the call is abandoned. Default `RECAPTCHA_VERIFY_TIMEOUT`. */
|
|
36
|
+
timeout?: number
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** One form POST to Google's siteverify. It holds no state and touches no context. */
|
|
40
|
+
export interface RecaptchaVerifier {
|
|
41
|
+
/**
|
|
42
|
+
* Google's answer for one token. A refusal is an answer (`success: false`), not an error.
|
|
43
|
+
*
|
|
44
|
+
* @throws {AuthUnavailable} `captcha` when Google cannot be asked or answers something unreadable.
|
|
45
|
+
*/
|
|
46
|
+
verify: (request: RecaptchaRequest) => Promise<RecaptchaResponse>
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The `MOD_RECAPTCHA` record of a server config: the siteverify secret in `value` (a mounted secret
|
|
51
|
+
* file) and, optionally, the browser's site key. The policy is the host's `MOD_CAPTCHA` record.
|
|
52
|
+
*/
|
|
53
|
+
export interface RecaptchaRecord extends PluginConfig {
|
|
54
|
+
/** The public site key; absent = the `CMOD_RECAPTCHA` client record's `value`. */
|
|
55
|
+
siteKey?: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Where the provider reads its keys — per call, so a config value resolved in place is seen. */
|
|
59
|
+
export interface RecaptchaKeys {
|
|
60
|
+
/** The siteverify secret; `null` when this environment holds none. */
|
|
61
|
+
secret: () => string | null
|
|
62
|
+
/** The public site key; `null` when none is configured. */
|
|
63
|
+
siteKey: () => string | null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface RecaptchaProviderOptions extends RecaptchaVerifierOptions {
|
|
67
|
+
/** The provider id. Default `RECAPTCHA_PROVIDER`. */
|
|
68
|
+
id?: string
|
|
69
|
+
/** A fixed secret; wins over `keys`. */
|
|
70
|
+
secret?: string
|
|
71
|
+
/** A fixed site key; wins over `keys`. */
|
|
72
|
+
siteKey?: string
|
|
73
|
+
/**
|
|
74
|
+
* Where the keys are read per call. `appendRecaptcha` defaults it to the context's
|
|
75
|
+
* `MOD_RECAPTCHA` / `CMOD_RECAPTCHA` records; without it only `secret` / `siteKey` count.
|
|
76
|
+
*/
|
|
77
|
+
keys?: RecaptchaKeys
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The reCAPTCHA provider of `@owlmeans/captcha`. */
|
|
81
|
+
export interface RecaptchaProvider extends CaptchaProvider {}
|
package/src/verifier.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { AuthUnavailable } from '@owlmeans/auth'
|
|
2
|
+
import { logger } from '@owlmeans/log'
|
|
3
|
+
import { RECAPTCHA_SITEVERIFY_URL, RECAPTCHA_VERIFY_TIMEOUT } from './consts.js'
|
|
4
|
+
import type { RecaptchaResponse, RecaptchaVerifier, RecaptchaVerifierOptions } from './types.js'
|
|
5
|
+
|
|
6
|
+
const log = logger('captcha-recaptcha')
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Google's siteverify: one https form POST per token.
|
|
10
|
+
*
|
|
11
|
+
* @throws {SyntaxError} for a siteverify address that is not https.
|
|
12
|
+
*/
|
|
13
|
+
export const createRecaptchaVerifier = (options: RecaptchaVerifierOptions = {}): RecaptchaVerifier => {
|
|
14
|
+
const url = options.url ?? RECAPTCHA_SITEVERIFY_URL
|
|
15
|
+
if (!url.startsWith('https://')) {
|
|
16
|
+
throw new SyntaxError(`reCAPTCHA siteverify must be https: ${url}`)
|
|
17
|
+
}
|
|
18
|
+
const timeout = options.timeout ?? RECAPTCHA_VERIFY_TIMEOUT
|
|
19
|
+
|
|
20
|
+
/** The answer, when it has the shape of one. */
|
|
21
|
+
const readAnswer = async (response: Response): Promise<RecaptchaResponse | null> => {
|
|
22
|
+
try {
|
|
23
|
+
const answer = await response.json() as RecaptchaResponse | null
|
|
24
|
+
return answer != null && typeof answer === 'object' && typeof answer.success === 'boolean' ? answer : null
|
|
25
|
+
} catch {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const verify: RecaptchaVerifier['verify'] = async request => {
|
|
31
|
+
const body = new URLSearchParams({ secret: request.secret, response: request.response })
|
|
32
|
+
if (request.remoteip != null && request.remoteip !== '') {
|
|
33
|
+
body.set('remoteip', request.remoteip)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const send = options.fetch ?? fetch
|
|
37
|
+
let response: Response
|
|
38
|
+
try {
|
|
39
|
+
response = await send(url, {
|
|
40
|
+
method: 'POST',
|
|
41
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
42
|
+
body,
|
|
43
|
+
signal: AbortSignal.timeout(timeout),
|
|
44
|
+
})
|
|
45
|
+
} catch (error) {
|
|
46
|
+
log.warn('reCAPTCHA siteverify unreachable', { error }, { event: 'auth.captcha.unavailable' })
|
|
47
|
+
throw new AuthUnavailable('captcha')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const answer = response.ok ? await readAnswer(response) : null
|
|
51
|
+
if (answer == null) {
|
|
52
|
+
log.warn('reCAPTCHA siteverify answered unusably', { status: response.status }, { event: 'auth.captcha.unavailable' })
|
|
53
|
+
throw new AuthUnavailable('captcha')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return answer
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return { verify }
|
|
60
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { AuthenFailed } from '@owlmeans/auth'
|
|
3
|
+
import { captchaResolverOf, makeCaptchaCheck, MOD_CAPTCHA } from '@owlmeans/captcha'
|
|
4
|
+
import { AppType } from '@owlmeans/context'
|
|
5
|
+
import { appendRecaptcha } from '../src/append.js'
|
|
6
|
+
import { CMOD_RECAPTCHA, MOD_RECAPTCHA, RECAPTCHA_PROVIDER } from '../src/consts.js'
|
|
7
|
+
import { makeRecaptchaKeys } from '../src/keys.js'
|
|
8
|
+
import { answering, GOOD, makeTestCtx } from './context.js'
|
|
9
|
+
import type { Call } from './context.js'
|
|
10
|
+
|
|
11
|
+
describe('@owlmeans/captcha-recaptcha — appendRecaptcha', () => {
|
|
12
|
+
test('registers the provider in the context\'s captcha host, keys read from the records', async () => {
|
|
13
|
+
const calls: Call[] = []
|
|
14
|
+
const context = await makeTestCtx([
|
|
15
|
+
{ id: MOD_RECAPTCHA, type: AppType.Backend, value: 'recaptcha-secret' },
|
|
16
|
+
{ id: CMOD_RECAPTCHA, type: AppType.Frontend, value: 'site-key' },
|
|
17
|
+
], ctx => { appendRecaptcha(ctx, { fetch: answering(200, GOOD, calls) }) })
|
|
18
|
+
|
|
19
|
+
const provider = captchaResolverOf(context).provider(RECAPTCHA_PROVIDER)
|
|
20
|
+
expect(provider.clientSettings()).toEqual({ provider: RECAPTCHA_PROVIDER, siteKey: 'site-key' })
|
|
21
|
+
|
|
22
|
+
const check = makeCaptchaCheck(context, { provider: RECAPTCHA_PROVIDER, hostnames: 'owlmeans.org', minScore: 0.5 })
|
|
23
|
+
expect(check.clientSettings()).toEqual({ provider: 'recaptcha', siteKey: 'site-key' })
|
|
24
|
+
await check.assert({ token: 'token', action: 'email_pin', remoteIp: '203.0.113.7' })
|
|
25
|
+
expect(Object.fromEntries(calls[0].init.body as URLSearchParams))
|
|
26
|
+
.toEqual({ secret: 'recaptcha-secret', response: 'token', remoteip: '203.0.113.7' })
|
|
27
|
+
await expect(check.assert({ token: 'token', action: 'email_password' })).rejects.toBeInstanceOf(AuthenFailed)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
test('the record\'s own site key wins; an empty or unresolved value counts as none', async () => {
|
|
31
|
+
const context = await makeTestCtx([
|
|
32
|
+
{ id: MOD_RECAPTCHA, value: '/etc/master-secret/recaptcha-secret', siteKey: 'own-key' },
|
|
33
|
+
{ id: CMOD_RECAPTCHA, value: 'client-key' },
|
|
34
|
+
])
|
|
35
|
+
const keys = makeRecaptchaKeys(context)
|
|
36
|
+
|
|
37
|
+
expect(keys.siteKey()).toBe('own-key')
|
|
38
|
+
expect(keys.secret()).toBeNull()
|
|
39
|
+
expect(makeRecaptchaKeys(await makeTestCtx([{ id: CMOD_RECAPTCHA, value: ' ' }])).siteKey()).toBeNull()
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('options replace the records, and the host record boots only with the provider registered', async () => {
|
|
43
|
+
const declared = { id: MOD_CAPTCHA, provider: RECAPTCHA_PROVIDER, hostnames: 'owlmeans.org' }
|
|
44
|
+
const context = await makeTestCtx([declared], ctx => { appendRecaptcha(ctx, { secret: 's', siteKey: 'fixed' }) })
|
|
45
|
+
|
|
46
|
+
expect(captchaResolverOf(context).find()?.clientSettings()).toEqual({ provider: 'recaptcha', siteKey: 'fixed' })
|
|
47
|
+
await expect(makeTestCtx([declared], ctx => { appendRecaptcha(ctx, { id: 'recaptcha-enterprise' }) }))
|
|
48
|
+
.rejects.toThrow('captcha:provider:recaptcha')
|
|
49
|
+
})
|
|
50
|
+
})
|
package/tests/context.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { PLUGIN_RECORD } from '@owlmeans/config'
|
|
2
|
+
import type { PluginConfig } from '@owlmeans/config'
|
|
3
|
+
import { AppType, makeBasicContext } from '@owlmeans/context'
|
|
4
|
+
import type { BasicConfig, BasicContext } from '@owlmeans/context'
|
|
5
|
+
import type { RecaptchaFetch, RecaptchaResponse } from '../src/types.js'
|
|
6
|
+
|
|
7
|
+
export interface Call {
|
|
8
|
+
url: string
|
|
9
|
+
init: RequestInit
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A `fetch` stand-in answering `status` with `body`, recording each call — no network. */
|
|
13
|
+
export const answering = (status: number, body: unknown, calls: Call[] = []): RecaptchaFetch =>
|
|
14
|
+
async (url, init) => {
|
|
15
|
+
calls.push({ url, init })
|
|
16
|
+
return new Response(JSON.stringify(body), { status })
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const GOOD: RecaptchaResponse = {
|
|
20
|
+
success: true, challenge_ts: '2026-10-06T10:00:00Z', hostname: 'vib-dev-1.owlmeans.org', score: 0.9, action: 'email_pin',
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A backend context with these plugin records; `setup` runs before it is configured and initialized. */
|
|
24
|
+
export const makeTestCtx = async (
|
|
25
|
+
plugins: PluginConfig[] = [], setup?: (context: BasicContext<BasicConfig>) => void
|
|
26
|
+
): Promise<BasicContext<BasicConfig>> => {
|
|
27
|
+
const context = makeBasicContext<BasicConfig>({
|
|
28
|
+
ready: false, service: 'captcha-recaptcha-tests', type: AppType.Backend, services: {},
|
|
29
|
+
[PLUGIN_RECORD]: plugins.map(record => ({ ...record })),
|
|
30
|
+
} as BasicConfig)
|
|
31
|
+
setup?.(context)
|
|
32
|
+
context.configure()
|
|
33
|
+
await context.init()
|
|
34
|
+
|
|
35
|
+
return context
|
|
36
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { AuthUnavailable } from '@owlmeans/auth'
|
|
3
|
+
import { addLogPlugin, memoryPlugin } from '@owlmeans/log'
|
|
4
|
+
import { CMOD_RECAPTCHA, MOD_RECAPTCHA, RECAPTCHA_PROVIDER } from '../src/consts.js'
|
|
5
|
+
import { makeRecaptchaProvider } from '../src/provider.js'
|
|
6
|
+
import { answering, GOOD } from './context.js'
|
|
7
|
+
import type { Call } from './context.js'
|
|
8
|
+
|
|
9
|
+
describe('@owlmeans/captcha-recaptcha — the provider', () => {
|
|
10
|
+
test('maps Google\'s answer onto the neutral verdict, asking with the secret, the token and the IP', async () => {
|
|
11
|
+
const calls: Call[] = []
|
|
12
|
+
const provider = makeRecaptchaProvider({ secret: 'secret', siteKey: 'site-key', fetch: answering(200, GOOD, calls) })
|
|
13
|
+
|
|
14
|
+
expect(provider.id).toBe(RECAPTCHA_PROVIDER)
|
|
15
|
+
// Shared with the browser client (`@owlmeans/web-captcha-recaptcha`) and stored in deployed configs.
|
|
16
|
+
expect([RECAPTCHA_PROVIDER, MOD_RECAPTCHA, CMOD_RECAPTCHA]).toEqual(['recaptcha', '_external:re-captcha', '_client-external:re-captcha'])
|
|
17
|
+
expect(await provider.verify('token', { action: 'email_pin', remoteIp: '203.0.113.7' })).toEqual({
|
|
18
|
+
success: true, score: 0.9, action: 'email_pin', hostname: 'vib-dev-1.owlmeans.org', at: '2026-10-06T10:00:00Z',
|
|
19
|
+
})
|
|
20
|
+
expect(Object.fromEntries(calls[0].init.body as URLSearchParams)).toEqual({ secret: 'secret', response: 'token', remoteip: '203.0.113.7' })
|
|
21
|
+
|
|
22
|
+
const refused = makeRecaptchaProvider({
|
|
23
|
+
secret: 'secret', fetch: answering(200, { success: false, challenge_ts: '', hostname: '', 'error-codes': ['timeout-or-duplicate'] }),
|
|
24
|
+
})
|
|
25
|
+
expect(await refused.verify('token')).toEqual({ success: false, hostname: '', errors: ['timeout-or-duplicate'] })
|
|
26
|
+
|
|
27
|
+
const checkbox = makeRecaptchaProvider({ secret: 'secret', fetch: answering(200, { success: true, challenge_ts: '2026-10-06T10:00:00Z', hostname: 'a.org' }) })
|
|
28
|
+
expect(await checkbox.verify('token')).toEqual({ success: true, hostname: 'a.org', at: '2026-10-06T10:00:00Z' })
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
test('advertises its id and site key; fixed values win over keys read per call', () => {
|
|
32
|
+
let siteKey: string | null = null
|
|
33
|
+
const keys = { secret: () => 'from-keys', siteKey: () => siteKey }
|
|
34
|
+
const provider = makeRecaptchaProvider({ keys })
|
|
35
|
+
|
|
36
|
+
expect(provider.clientSettings()).toEqual({ provider: 'recaptcha', siteKey: '' })
|
|
37
|
+
siteKey = 'resolved-later'
|
|
38
|
+
expect(provider.clientSettings()).toEqual({ provider: 'recaptcha', siteKey: 'resolved-later' })
|
|
39
|
+
expect(makeRecaptchaProvider({ keys, siteKey: 'fixed', id: 'recaptcha-enterprise' }).clientSettings())
|
|
40
|
+
.toEqual({ provider: 'recaptcha-enterprise', siteKey: 'fixed' })
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test('without a secret nothing is asked: unavailability, logged once', async () => {
|
|
44
|
+
const memory = memoryPlugin('recaptcha-secret')
|
|
45
|
+
const remove = addLogPlugin(memory)
|
|
46
|
+
try {
|
|
47
|
+
const calls: Call[] = []
|
|
48
|
+
const provider = makeRecaptchaProvider({ keys: { secret: () => null, siteKey: () => 'k' }, fetch: answering(200, GOOD, calls) })
|
|
49
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
50
|
+
const error = await provider.verify('token').catch((e: unknown) => e)
|
|
51
|
+
expect(error).toBeInstanceOf(AuthUnavailable)
|
|
52
|
+
expect((error as Error).message).toContain('captcha:config')
|
|
53
|
+
}
|
|
54
|
+
expect(calls).toHaveLength(0)
|
|
55
|
+
expect(memory.records.filter(record => record.event === 'auth.captcha.config')).toHaveLength(1)
|
|
56
|
+
} finally {
|
|
57
|
+
remove()
|
|
58
|
+
}
|
|
59
|
+
})
|
|
60
|
+
})
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { AuthUnavailable } from '@owlmeans/auth'
|
|
3
|
+
import { RECAPTCHA_SITEVERIFY_URL, RECAPTCHA_VERIFY_TIMEOUT } from '../src/consts.js'
|
|
4
|
+
import type { RecaptchaFetch, RecaptchaResponse } from '../src/types.js'
|
|
5
|
+
import { createRecaptchaVerifier } from '../src/verifier.js'
|
|
6
|
+
import { answering, GOOD } from './context.js'
|
|
7
|
+
import type { Call } from './context.js'
|
|
8
|
+
|
|
9
|
+
describe('@owlmeans/captcha-recaptcha — siteverify', () => {
|
|
10
|
+
test('posts the siteverify form to Google over https', async () => {
|
|
11
|
+
const calls: Call[] = []
|
|
12
|
+
const verifier = createRecaptchaVerifier({ fetch: answering(200, GOOD, calls) })
|
|
13
|
+
|
|
14
|
+
expect(await verifier.verify({ secret: 's', response: 'r', remoteip: '203.0.113.7' })).toEqual(GOOD)
|
|
15
|
+
expect(await verifier.verify({ secret: 's', response: 'r', remoteip: '' })).toEqual(GOOD)
|
|
16
|
+
expect(calls).toHaveLength(2)
|
|
17
|
+
expect(calls[0].url).toBe(RECAPTCHA_SITEVERIFY_URL)
|
|
18
|
+
expect(RECAPTCHA_SITEVERIFY_URL).toBe('https://www.google.com/recaptcha/api/siteverify')
|
|
19
|
+
expect(calls[0].init.method).toBe('POST')
|
|
20
|
+
expect(new Headers(calls[0].init.headers).get('content-type')).toBe('application/x-www-form-urlencoded')
|
|
21
|
+
expect(calls[0].init.signal).toBeInstanceOf(AbortSignal)
|
|
22
|
+
expect(Object.fromEntries(calls[0].init.body as URLSearchParams)).toEqual({ secret: 's', response: 'r', remoteip: '203.0.113.7' })
|
|
23
|
+
expect(Object.fromEntries(calls[1].init.body as URLSearchParams)).toEqual({ secret: 's', response: 'r' })
|
|
24
|
+
expect(RECAPTCHA_VERIFY_TIMEOUT).toBe(10_000)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
test('an unreachable or unreadable Google is unavailability, not a refusal', async () => {
|
|
28
|
+
const failing: RecaptchaFetch = async () => { throw new Error('offline') }
|
|
29
|
+
const garbage: RecaptchaFetch = async () => new Response('<html>', { status: 200 })
|
|
30
|
+
for (const fetch of [failing, garbage, answering(500, GOOD), answering(200, { nothing: true }), answering(200, null)]) {
|
|
31
|
+
const error = await createRecaptchaVerifier({ fetch }).verify({ secret: 's', response: 'r' }).catch((e: unknown) => e)
|
|
32
|
+
expect(error).toBeInstanceOf(AuthUnavailable)
|
|
33
|
+
expect((error as Error).message).toEndWith('unavailable:captcha')
|
|
34
|
+
}
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('a refusal is an answer, not an error', async () => {
|
|
38
|
+
const refusal: RecaptchaResponse = { ...GOOD, success: false, 'error-codes': ['invalid-input-response'] }
|
|
39
|
+
|
|
40
|
+
expect(await createRecaptchaVerifier({ fetch: answering(200, refusal) }).verify({ secret: 's', response: 'r' })).toEqual(refusal)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test('refuses a siteverify address that is not https', () => {
|
|
44
|
+
expect(() => createRecaptchaVerifier({ url: 'http://www.google.com/recaptcha/api/siteverify' })).toThrow(SyntaxError)
|
|
45
|
+
})
|
|
46
|
+
})
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": [
|
|
3
|
+
"@owlmeans/dep-config/tsconfig.base.json",
|
|
4
|
+
"@owlmeans/dep-config/tsconfig.node.json"
|
|
5
|
+
],
|
|
6
|
+
"compilerOptions": {
|
|
7
|
+
"rootDir": "./src/",
|
|
8
|
+
"outDir": "./build/"
|
|
9
|
+
},
|
|
10
|
+
"exclude": [
|
|
11
|
+
"./dist/**/*",
|
|
12
|
+
"./build/**/*",
|
|
13
|
+
"./tests/**/*",
|
|
14
|
+
"./*.ts"
|
|
15
|
+
]
|
|
16
|
+
}
|