-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.js
92 lines (81 loc) · 2.19 KB
/
index.js
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
/**
* reCAPTCHA Cloudflare Worker
* Server-side Google reCAPTCHA validation
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest (request) {
const corsHeaders = setCorsHeaders(new Headers())
try {
const requestMethod = request.method
// Allow CORS
if (requestMethod === 'OPTIONS') {
return new Response('', { headers: corsHeaders })
}
// Ensure POST request
if (requestMethod !== 'POST') {
return new Response('Invalid request method', {
status: 400,
headers: corsHeaders
})
}
// Ensure recaptcha token given
const recaptchaToken = request.headers.get('g-recaptcha')
if (!recaptchaToken) {
return new Response('Invalid reCAPTCHA token', {
status: 400,
headers: corsHeaders
})
}
if (typeof RECAPTCHA_SECRET === 'undefined') {
throw new Error('RECAPTCHA_SECRET secret not set')
}
// Verify token
const recaptchaResponse = await fetch(
`https://www.google.com/recaptcha/api/siteverify`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
secret: RECAPTCHA_SECRET,
response: recaptchaToken
})
}
)
const recaptchaBody = await recaptchaResponse.json()
// Handle failure
if (!recaptchaBody.success) {
return new Response('reCAPTCHA failed', {
status: 400,
headers: corsHeaders
})
}
// Success
return new Response('reCAPTCHA passed', {
status: 202,
headers: corsHeaders
})
} catch (err) {
// Handle unexpected errors
console.error(err)
return new Response(err.stack, { status: 500, headers: corsHeaders })
}
}
// Set the required CORS headers
function setCorsHeaders (headers) {
headers.set('Access-Control-Allow-Origin', '*')
headers.set('Access-Control-Allow-Methods', 'POST')
headers.set(
'Access-Control-Allow-Headers',
'access-control-allow-headers, g-recaptcha'
)
headers.set('Access-Control-Max-Age', 1728185)
return headers
}