@nage-api/integrations-recaptcha 1.0.0-beta.2
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 +202 -0
- package/README.md +66 -0
- package/dist/index.d.ts +90 -0
- package/dist/index.js +190 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# @nage-api/integrations-recaptcha
|
|
2
|
+
|
|
3
|
+
Typed reCAPTCHA verification (PLAN.md §8, §12: "fix TLS, reCAPTCHA key/POST").
|
|
4
|
+
|
|
5
|
+
The legacy integration got three things wrong, and each one leaves a captcha
|
|
6
|
+
looking like it works while providing no protection:
|
|
7
|
+
|
|
8
|
+
1. **it read the secret from `RECAPTCHA_SECRET_KET`** (§2.4), a variable nothing
|
|
9
|
+
sets, so no usable secret ever went up the wire. Google answers
|
|
10
|
+
`invalid-input-secret`; code that only checks `success` sees every
|
|
11
|
+
verification fail, and code that ignores the response sees every one pass.
|
|
12
|
+
2. **it was a GET with the secret in the query string** — writing a long-lived
|
|
13
|
+
credential into every access log and proxy log on the path.
|
|
14
|
+
3. **TLS verification was off** across the integration libraries (§5.2), so the
|
|
15
|
+
answer could come from anyone in the middle.
|
|
16
|
+
|
|
17
|
+
This package POSTs the **secret** in a form body, over TLS, to a URL that is not
|
|
18
|
+
configurable — no deployment can point it somewhere plaintext.
|
|
19
|
+
|
|
20
|
+
<!-- docs-example: fragment -->
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { ValidationError } from '@nage-api/core';
|
|
24
|
+
import { RecaptchaVerifier } from '@nage-api/integrations-recaptcha';
|
|
25
|
+
|
|
26
|
+
// The reader's validated environment. The name matters: the legacy library read
|
|
27
|
+
// `RECAPTCHA_SECRET_KET`, so it always got `undefined` and every verification
|
|
28
|
+
// failed the same way a wrong secret does.
|
|
29
|
+
declare const env: { readonly RECAPTCHA_SECRET_KEY: string };
|
|
30
|
+
// Off the request: the token the widget produced, and the caller's address.
|
|
31
|
+
declare const token: string;
|
|
32
|
+
declare const remoteIp: string;
|
|
33
|
+
|
|
34
|
+
const verifier = new RecaptchaVerifier({
|
|
35
|
+
secretKey: env.RECAPTCHA_SECRET_KEY,
|
|
36
|
+
minimumScore: 0.5,
|
|
37
|
+
allowedHostnames: ['example.com'],
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const result = await verifier.assertHuman({ token, action: 'login', remoteIp });
|
|
41
|
+
if (!result.success) throw new ValidationError({ message: 'Captcha failed.' });
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## The decision lives here
|
|
45
|
+
|
|
46
|
+
`verify` returns what Google said. `assertHuman` decides — score threshold,
|
|
47
|
+
action match, hostname allow-list — because a caller that only checks `success`
|
|
48
|
+
has a v3 captcha that passes every bot scoring 0.1, and a token minted on the
|
|
49
|
+
login page and replayed against the payment page is a real and cheap attack.
|
|
50
|
+
|
|
51
|
+
A **failed** captcha is a return value, not an exception: failing is the
|
|
52
|
+
expected outcome for a bot. Only an unreachable Google raises.
|
|
53
|
+
|
|
54
|
+
Anything unparseable reads as _not verified_. A response this code cannot
|
|
55
|
+
understand must never count as a pass — that is the difference between a captcha
|
|
56
|
+
and a decoration.
|
|
57
|
+
|
|
58
|
+
The constructor rejects a key containing markup, which is what a site key pasted
|
|
59
|
+
out of a browser snippet looks like. It cannot tell a site key from a secret
|
|
60
|
+
otherwise: both are public-looking strings of the same shape.
|
|
61
|
+
|
|
62
|
+
## Not yet implemented
|
|
63
|
+
|
|
64
|
+
- reCAPTCHA Enterprise, which has a different endpoint and an API key.
|
|
65
|
+
- hCaptcha and Turnstile, which have compatible-enough shapes to sit behind one
|
|
66
|
+
port later.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@nage-api/integrations-recaptcha` — verifying a reCAPTCHA response
|
|
3
|
+
* (PLAN.md §8, §12: "fix TLS, reCAPTCHA key/POST").
|
|
4
|
+
*
|
|
5
|
+
* The legacy integration got three things wrong, and every one of them is the
|
|
6
|
+
* kind of bug that leaves a captcha looking like it works while providing no
|
|
7
|
+
* protection at all:
|
|
8
|
+
*
|
|
9
|
+
* 1. **the site key was sent instead of the secret** — the endpoint answers
|
|
10
|
+
* `invalid-input-secret`, and code that only checks `success` treats every
|
|
11
|
+
* verification as a failure, or (worse) code that ignores the response
|
|
12
|
+
* treats every one as a pass;
|
|
13
|
+
* 2. **the request was a GET with the secret in the query string** — which
|
|
14
|
+
* writes a long-lived credential into every access log and proxy log
|
|
15
|
+
* between here and Google;
|
|
16
|
+
* 3. **TLS verification was disabled** — so the answer could come from
|
|
17
|
+
* anybody on the path.
|
|
18
|
+
*
|
|
19
|
+
* This package sends the **secret** in a `POST` body over TLS, and treats an
|
|
20
|
+
* unparseable or failed response as "not verified" rather than as an exception
|
|
21
|
+
* a caller might swallow.
|
|
22
|
+
*/
|
|
23
|
+
/** Google's verification endpoint. Not configurable: it is the only one. */
|
|
24
|
+
export declare const RECAPTCHA_VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify";
|
|
25
|
+
/** Error codes the endpoint can return, as a closed set. */
|
|
26
|
+
export type RecaptchaErrorCode = 'missing-input-secret' | 'invalid-input-secret' | 'missing-input-response' | 'invalid-input-response' | 'bad-request' | 'timeout-or-duplicate' | 'unknown';
|
|
27
|
+
export interface RecaptchaVerification {
|
|
28
|
+
readonly success: boolean;
|
|
29
|
+
/** v3 only: 0.0 (bot) to 1.0 (human). */
|
|
30
|
+
readonly score?: number;
|
|
31
|
+
/** v3 only: the action the client claimed to be performing. */
|
|
32
|
+
readonly action?: string;
|
|
33
|
+
readonly hostname?: string;
|
|
34
|
+
readonly errorCodes: readonly RecaptchaErrorCode[];
|
|
35
|
+
}
|
|
36
|
+
export interface RecaptchaOptions {
|
|
37
|
+
/** The **secret** key, not the site key. Never sent in a URL. */
|
|
38
|
+
readonly secretKey: string;
|
|
39
|
+
/**
|
|
40
|
+
* Minimum v3 score to treat as human.
|
|
41
|
+
*
|
|
42
|
+
* 0.5 is Google's suggested starting point. A site that sets this to 0 has
|
|
43
|
+
* a captcha that passes everything.
|
|
44
|
+
*/
|
|
45
|
+
readonly minimumScore?: number;
|
|
46
|
+
/** Require the response's action to match the one the caller expects. */
|
|
47
|
+
readonly enforceAction?: boolean;
|
|
48
|
+
/** Only accept verifications for these hostnames. Empty accepts any. */
|
|
49
|
+
readonly allowedHostnames?: readonly string[];
|
|
50
|
+
readonly timeoutMs?: number;
|
|
51
|
+
/** Injected in tests; defaults to the global `fetch`. */
|
|
52
|
+
readonly fetchImpl?: typeof fetch;
|
|
53
|
+
}
|
|
54
|
+
export interface VerifyInput {
|
|
55
|
+
/** The token the browser widget produced. */
|
|
56
|
+
readonly token: string;
|
|
57
|
+
/** The caller's IP, which Google uses as a signal. Optional. */
|
|
58
|
+
readonly remoteIp?: string;
|
|
59
|
+
/** Expected v3 action, e.g. `login`. */
|
|
60
|
+
readonly action?: string;
|
|
61
|
+
}
|
|
62
|
+
export declare class RecaptchaVerifier {
|
|
63
|
+
#private;
|
|
64
|
+
constructor(options: RecaptchaOptions);
|
|
65
|
+
/**
|
|
66
|
+
* Verify a token.
|
|
67
|
+
*
|
|
68
|
+
* @returns the parsed verification; never throws for a *failed* captcha,
|
|
69
|
+
* because failing is the expected outcome for a bot.
|
|
70
|
+
* @throws ExternalServiceError when Google itself could not be reached
|
|
71
|
+
*/
|
|
72
|
+
verify(input: VerifyInput): Promise<RecaptchaVerification>;
|
|
73
|
+
/**
|
|
74
|
+
* Verify and decide.
|
|
75
|
+
*
|
|
76
|
+
* The decision — score threshold, action match, hostname allow-list — lives
|
|
77
|
+
* here rather than at the call site, because a caller that only checks
|
|
78
|
+
* `success` has a v3 captcha that passes every bot with a score of 0.1.
|
|
79
|
+
*/
|
|
80
|
+
assertHuman(input: VerifyInput): Promise<RecaptchaVerification>;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Read Google's response.
|
|
84
|
+
*
|
|
85
|
+
* Anything unexpected reads as *not verified*. A response this code cannot
|
|
86
|
+
* parse must never be treated as a pass — that is the difference between a
|
|
87
|
+
* captcha and a decoration.
|
|
88
|
+
*/
|
|
89
|
+
export declare function parseVerification(payload: unknown): RecaptchaVerification;
|
|
90
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `@nage-api/integrations-recaptcha` — verifying a reCAPTCHA response
|
|
4
|
+
* (PLAN.md §8, §12: "fix TLS, reCAPTCHA key/POST").
|
|
5
|
+
*
|
|
6
|
+
* The legacy integration got three things wrong, and every one of them is the
|
|
7
|
+
* kind of bug that leaves a captcha looking like it works while providing no
|
|
8
|
+
* protection at all:
|
|
9
|
+
*
|
|
10
|
+
* 1. **the site key was sent instead of the secret** — the endpoint answers
|
|
11
|
+
* `invalid-input-secret`, and code that only checks `success` treats every
|
|
12
|
+
* verification as a failure, or (worse) code that ignores the response
|
|
13
|
+
* treats every one as a pass;
|
|
14
|
+
* 2. **the request was a GET with the secret in the query string** — which
|
|
15
|
+
* writes a long-lived credential into every access log and proxy log
|
|
16
|
+
* between here and Google;
|
|
17
|
+
* 3. **TLS verification was disabled** — so the answer could come from
|
|
18
|
+
* anybody on the path.
|
|
19
|
+
*
|
|
20
|
+
* This package sends the **secret** in a `POST` body over TLS, and treats an
|
|
21
|
+
* unparseable or failed response as "not verified" rather than as an exception
|
|
22
|
+
* a caller might swallow.
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.RecaptchaVerifier = exports.RECAPTCHA_VERIFY_URL = void 0;
|
|
26
|
+
exports.parseVerification = parseVerification;
|
|
27
|
+
const core_1 = require("@nage-api/core");
|
|
28
|
+
/** Google's verification endpoint. Not configurable: it is the only one. */
|
|
29
|
+
exports.RECAPTCHA_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
|
|
30
|
+
const DEFAULT_MINIMUM_SCORE = 0.5;
|
|
31
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
32
|
+
const REDACTED_FIELDS = (0, core_1.redactionSet)(['secret', 'secretkey']);
|
|
33
|
+
class RecaptchaVerifier {
|
|
34
|
+
#secretKey;
|
|
35
|
+
#minimumScore;
|
|
36
|
+
#enforceAction;
|
|
37
|
+
#allowedHostnames;
|
|
38
|
+
#timeoutMs;
|
|
39
|
+
#fetch;
|
|
40
|
+
constructor(options) {
|
|
41
|
+
if (options.secretKey.trim() === '') {
|
|
42
|
+
throw new core_1.ConfigurationError({
|
|
43
|
+
detail: 'A reCAPTCHA secret key is required; set RECAPTCHA_SECRET_KEY',
|
|
44
|
+
meta: { setting: 'recaptcha.secretKey' },
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
// Site keys are public and start with `6L`, exactly like secrets, so the
|
|
48
|
+
// shapes cannot be told apart — but a key pasted from a browser snippet
|
|
49
|
+
// usually still carries its HTML attribute quoting.
|
|
50
|
+
if (/["'<>]/.test(options.secretKey)) {
|
|
51
|
+
throw new core_1.ConfigurationError({
|
|
52
|
+
detail: 'The reCAPTCHA secret key contains markup; it looks like it was copied from a page rather than from the console',
|
|
53
|
+
meta: { setting: 'recaptcha.secretKey' },
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
this.#secretKey = options.secretKey;
|
|
57
|
+
this.#minimumScore = options.minimumScore ?? DEFAULT_MINIMUM_SCORE;
|
|
58
|
+
this.#enforceAction = options.enforceAction ?? true;
|
|
59
|
+
this.#allowedHostnames = new Set(options.allowedHostnames ?? []);
|
|
60
|
+
this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
61
|
+
this.#fetch = options.fetchImpl ?? globalThis.fetch;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Verify a token.
|
|
65
|
+
*
|
|
66
|
+
* @returns the parsed verification; never throws for a *failed* captcha,
|
|
67
|
+
* because failing is the expected outcome for a bot.
|
|
68
|
+
* @throws ExternalServiceError when Google itself could not be reached
|
|
69
|
+
*/
|
|
70
|
+
async verify(input) {
|
|
71
|
+
if (input.token.trim() === '') {
|
|
72
|
+
// Not a network round trip: an empty token is a missing widget, and the
|
|
73
|
+
// answer is already known.
|
|
74
|
+
return { success: false, errorCodes: ['missing-input-response'] };
|
|
75
|
+
}
|
|
76
|
+
const body = new URLSearchParams({
|
|
77
|
+
// The **secret**, in the body of a POST. Never `sitekey`, never a query
|
|
78
|
+
// parameter that a proxy would log.
|
|
79
|
+
secret: this.#secretKey,
|
|
80
|
+
response: input.token,
|
|
81
|
+
...(input.remoteIp === undefined ? {} : { remoteip: input.remoteIp }),
|
|
82
|
+
});
|
|
83
|
+
const payload = await this.#post(body);
|
|
84
|
+
return parseVerification(payload);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Verify and decide.
|
|
88
|
+
*
|
|
89
|
+
* The decision — score threshold, action match, hostname allow-list — lives
|
|
90
|
+
* here rather than at the call site, because a caller that only checks
|
|
91
|
+
* `success` has a v3 captcha that passes every bot with a score of 0.1.
|
|
92
|
+
*/
|
|
93
|
+
async assertHuman(input) {
|
|
94
|
+
const verification = await this.verify(input);
|
|
95
|
+
if (!verification.success)
|
|
96
|
+
return verification;
|
|
97
|
+
if (verification.score !== undefined && verification.score < this.#minimumScore) {
|
|
98
|
+
return { ...verification, success: false, errorCodes: ['unknown'] };
|
|
99
|
+
}
|
|
100
|
+
if (this.#enforceAction &&
|
|
101
|
+
input.action !== undefined &&
|
|
102
|
+
verification.action !== undefined &&
|
|
103
|
+
verification.action !== input.action) {
|
|
104
|
+
// A token minted on the login page and replayed against the payment page
|
|
105
|
+
// is a real and cheap attack.
|
|
106
|
+
return { ...verification, success: false, errorCodes: ['unknown'] };
|
|
107
|
+
}
|
|
108
|
+
if (this.#allowedHostnames.size > 0 &&
|
|
109
|
+
verification.hostname !== undefined &&
|
|
110
|
+
!this.#allowedHostnames.has(verification.hostname)) {
|
|
111
|
+
return { ...verification, success: false, errorCodes: ['unknown'] };
|
|
112
|
+
}
|
|
113
|
+
return verification;
|
|
114
|
+
}
|
|
115
|
+
async #post(body) {
|
|
116
|
+
const controller = new AbortController();
|
|
117
|
+
const timer = setTimeout(() => {
|
|
118
|
+
controller.abort();
|
|
119
|
+
}, this.#timeoutMs);
|
|
120
|
+
timer.unref();
|
|
121
|
+
try {
|
|
122
|
+
const response = await this.#fetch(exports.RECAPTCHA_VERIFY_URL, {
|
|
123
|
+
method: 'POST',
|
|
124
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
125
|
+
body: body.toString(),
|
|
126
|
+
signal: controller.signal,
|
|
127
|
+
});
|
|
128
|
+
if (!response.ok) {
|
|
129
|
+
throw new core_1.ExternalServiceError('recaptcha', {
|
|
130
|
+
detail: `reCAPTCHA verification returned ${String(response.status)}`,
|
|
131
|
+
meta: { status: response.status },
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
return await response.json();
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
if (error instanceof core_1.ExternalServiceError)
|
|
138
|
+
throw error;
|
|
139
|
+
throw new core_1.ExternalServiceError('recaptcha', {
|
|
140
|
+
// The secret is in `body`; the redaction set keeps it out of the log
|
|
141
|
+
// line this error produces.
|
|
142
|
+
detail: `reCAPTCHA verification failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
143
|
+
cause: error,
|
|
144
|
+
meta: (0, core_1.redact)({ request: { secret: '[set]' } }, REDACTED_FIELDS),
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
exports.RecaptchaVerifier = RecaptchaVerifier;
|
|
153
|
+
/**
|
|
154
|
+
* Read Google's response.
|
|
155
|
+
*
|
|
156
|
+
* Anything unexpected reads as *not verified*. A response this code cannot
|
|
157
|
+
* parse must never be treated as a pass — that is the difference between a
|
|
158
|
+
* captcha and a decoration.
|
|
159
|
+
*/
|
|
160
|
+
function parseVerification(payload) {
|
|
161
|
+
if (typeof payload !== 'object' || payload === null) {
|
|
162
|
+
return { success: false, errorCodes: ['bad-request'] };
|
|
163
|
+
}
|
|
164
|
+
const record = payload;
|
|
165
|
+
const success = record['success'] === true;
|
|
166
|
+
const codes = Array.isArray(record['error-codes'])
|
|
167
|
+
? record['error-codes'].filter((code) => typeof code === 'string')
|
|
168
|
+
: [];
|
|
169
|
+
return {
|
|
170
|
+
success,
|
|
171
|
+
...(typeof record['score'] === 'number' ? { score: record['score'] } : {}),
|
|
172
|
+
...(typeof record['action'] === 'string' ? { action: record['action'] } : {}),
|
|
173
|
+
...(typeof record['hostname'] === 'string' ? { hostname: record['hostname'] } : {}),
|
|
174
|
+
errorCodes: codes.map(toErrorCode),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
const KNOWN_CODES = [
|
|
178
|
+
'missing-input-secret',
|
|
179
|
+
'invalid-input-secret',
|
|
180
|
+
'missing-input-response',
|
|
181
|
+
'invalid-input-response',
|
|
182
|
+
'bad-request',
|
|
183
|
+
'timeout-or-duplicate',
|
|
184
|
+
];
|
|
185
|
+
function toErrorCode(code) {
|
|
186
|
+
return KNOWN_CODES.includes(code)
|
|
187
|
+
? code
|
|
188
|
+
: 'unknown';
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=index.js.map
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nage-api/integrations-recaptcha",
|
|
3
|
+
"version": "1.0.0-beta.2",
|
|
4
|
+
"description": "Typed reCAPTCHA verification for @nage-api — secret in the body, POST, no TLS downgrade",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"!dist/.tsbuildinfo",
|
|
20
|
+
"!dist/**/*.map",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@nage-api/contracts": "1.0.0-beta.2",
|
|
28
|
+
"@nage-api/core": "1.0.0-beta.2"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@nestjs/common": "^11.0.0",
|
|
32
|
+
"@nestjs/core": "^11.0.0",
|
|
33
|
+
"reflect-metadata": "^0.2.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@nestjs/common": "11.1.29",
|
|
37
|
+
"@nestjs/core": "11.1.29",
|
|
38
|
+
"@nestjs/testing": "11.1.29",
|
|
39
|
+
"@swc/core": "1.15.47",
|
|
40
|
+
"@types/node": "22.20.1",
|
|
41
|
+
"@vitest/coverage-v8": "4.1.10",
|
|
42
|
+
"reflect-metadata": "0.2.2",
|
|
43
|
+
"rimraf": "6.1.3",
|
|
44
|
+
"rxjs": "7.8.2",
|
|
45
|
+
"typescript": "5.9.3",
|
|
46
|
+
"unplugin-swc": "1.5.11",
|
|
47
|
+
"vitest": "4.1.10"
|
|
48
|
+
},
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=22.0.0"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "tsc -b tsconfig.build.json",
|
|
54
|
+
"clean": "rimraf dist .turbo",
|
|
55
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
56
|
+
"test": "vitest run"
|
|
57
|
+
}
|
|
58
|
+
}
|