-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverifyToken.js
More file actions
221 lines (192 loc) · 6.99 KB
/
verifyToken.js
File metadata and controls
221 lines (192 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/**
* Backend CAPTCHA token verification module
* Verifies tokens with Cloudflare Turnstile, reCAPTCHA v2, and reCAPTCHA v3
*
* Usage:
* const { verifyToken } = require('./lib/verifyToken.js');
* const result = await verifyToken(token, provider, secretKey, options);
*/
/**
* Verify a CAPTCHA token with the provider's backend API
* @param {string} token - The CAPTCHA token from the component
* @param {string} provider - 'cloudflare', 'recaptcha2', or 'recaptcha3'
* @param {string} secretKey - Your private/secret key from the CAPTCHA provider
* @param {Object} options - Additional options
* @param {string} options.remoteip - Client IP address (optional, but recommended)
* @param {string} options.action - Action name for reCAPTCHA v3 validation (optional)
* @param {number} options.score_threshold - Minimum score for reCAPTCHA v3 (0.0-1.0, default: 0.5)
* @param {string} options.idempotency_key - UUID for Cloudflare retry safety (optional)
* @param {number} options.timeout - Request timeout in milliseconds (default: 10000)
* @param {string} options.expectedHostname - Expected hostname for Cloudflare (optional)
* @param {string} options.expectedAction - Expected action for Cloudflare (optional)
* @returns {Promise<{success: boolean, score?: number, error?: string, raw?: Object}>}
*/
async function verifyToken(token, provider, secretKey, options = {}) {
if (!token) {
return { success: false, error: 'Token is required' };
}
if (!provider) {
return { success: false, error: 'Provider is required' };
}
if (!secretKey) {
return { success: false, error: 'Secret key is required' };
}
try {
if (provider === 'cloudflare') {
return await verifyCloudflare(token, secretKey, options);
} else if (provider === 'recaptcha2') {
return await verifyRecaptchaV2(token, secretKey, options);
} else if (provider === 'recaptcha3') {
return await verifyRecaptchaV3(token, secretKey, options);
} else {
return { success: false, error: `Unknown provider: ${provider}` };
}
} catch (err) {
console.error(`[captcha-verify] Error verifying ${provider} token:`, err.message);
return { success: false, error: `Verification failed: ${err.message}` };
}
}
/**
* Verify Cloudflare Turnstile token
* https://developers.cloudflare.com/turnstile/get-started/server-side-validation/
*/
async function verifyCloudflare(token, secretKey, options = {}) {
const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
// Validate token format (Cloudflare tokens are max 2048 chars)
if (!token || token.length > 2048) {
return {
success: false,
error_codes: token?.length > 2048 ? ['token-too-long'] : ['missing-input-response'],
raw: null,
};
}
const body = {
secret: secretKey,
response: token,
};
if (options.remoteip) {
body.remoteip = options.remoteip;
}
// Support idempotency_key for safe retries (UUID format recommended)
if (options.idempotency_key) {
body.idempotency_key = options.idempotency_key;
}
try {
const controller = new AbortController();
// Set timeout to 10 seconds (Cloudflare recommends reasonable timeouts)
const timeout = options.timeout || 10000;
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// Additional validation checks (optional, recommended for enhanced security)
let isValid = data.success === true;
let validationReason = null;
// Validate expected hostname if provided
if (isValid && options.expectedHostname && data.hostname !== options.expectedHostname) {
isValid = false;
validationReason = `Hostname mismatch: expected ${options.expectedHostname}, got ${data.hostname}`;
}
// Validate expected action if provided (useful if you use Turnstile actions)
if (isValid && options.expectedAction && data.action !== options.expectedAction) {
isValid = false;
validationReason = `Action mismatch: expected ${options.expectedAction}, got ${data.action}`;
}
// Warn if token is very old (>4 minutes, when 5 minute validity is near expiry)
if (isValid && data.challenge_ts) {
const challengeTime = new Date(data.challenge_ts).getTime();
const now = Date.now();
const ageSeconds = (now - challengeTime) / 1000;
if (ageSeconds > 240) {
console.warn(`[captcha-verify] Cloudflare token is ${ageSeconds.toFixed(1)} seconds old (approaching 5-minute expiry)`);
}
}
return {
success: isValid,
error_codes: data['error-codes'] || [],
challenge_ts: data.challenge_ts,
hostname: data.hostname,
action: data.action,
cdata: data.cdata,
validation_failed_reason: validationReason,
raw: data,
};
} catch (err) {
if (err.name === 'AbortError') {
throw new Error('Cloudflare verification timeout');
}
throw err;
}
}
/**
* Verify reCAPTCHA v2 token
* https://developers.google.com/recaptcha/docs/verify
*/
async function verifyRecaptchaV2(token, secretKey, options = {}) {
const url = 'https://www.google.com/recaptcha/api/siteverify';
const params = new URLSearchParams({
secret: secretKey,
response: token,
});
if (options.remoteip) {
params.append('remoteip', options.remoteip);
}
const response = await fetch(url, {
method: 'POST',
body: params,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return {
success: data.success === true,
challenge_ts: data.challenge_ts,
hostname: data.hostname,
error_codes: data['error-codes'] || [],
raw: data,
};
}
/**
* Verify reCAPTCHA v3 token
* https://developers.google.com/recaptcha/docs/v3
*/
async function verifyRecaptchaV3(token, secretKey, options = {}) {
const url = 'https://www.google.com/recaptcha/api/siteverify';
const params = new URLSearchParams({
secret: secretKey,
response: token,
});
if (options.remoteip) {
params.append('remoteip', options.remoteip);
}
const response = await fetch(url, {
method: 'POST',
body: params,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
const scoreThreshold = options.score_threshold ?? 0.5;
const scoreIsValid = data.score !== undefined && data.score >= scoreThreshold;
return {
success: data.success === true && scoreIsValid,
score: data.score,
action: data.action,
challenge_ts: data.challenge_ts,
hostname: data.hostname,
score_threshold: scoreThreshold,
error_codes: data['error-codes'] || [],
raw: data,
};
}
module.exports = { verifyToken };