Skip to content

Commit 0afb152

Browse files
committed
feat: add turnstile verification
1 parent 6127306 commit 0afb152

File tree

2 files changed

+49
-14
lines changed

2 files changed

+49
-14
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
async function handleTurnstile(request: Request) {
2+
const body = await request.formData()
3+
// Turnstile injects a token in "cf-turnstile-response".
4+
const token = body.get('cf-turnstile-response')
5+
const ip = request.headers.get('CF-Connecting-IP')
6+
7+
// Validate the token by calling the
8+
// "/siteverify" API endpoint.
9+
const formData = new FormData()
10+
formData.append('secret', Netlify.env.get('TURNSTILE_SECRET'))
11+
if (token)
12+
formData.append('response', token)
13+
if (ip)
14+
formData.append('remoteip', ip)
15+
16+
const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
17+
const result = await fetch(url, {
18+
body: formData,
19+
method: 'POST',
20+
})
21+
22+
const outcome = await result.json()
23+
return !!outcome.success
24+
}
25+
26+
export default async (request: Request) => {
27+
const userAgent = request.headers.get('user-agent') || ''
28+
const turnstileWidget = '<body><script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer="defer"></script><div class="cf-turnstile" data-sitekey="0x4AAAAAAAxDMjtUWpd9d64q" data-callback="javascriptCallback"></div><script></script></body>'
29+
30+
if (!userAgent.length) {
31+
return new Response('Access Denied: User-Agent is required', {
32+
status: 403,
33+
headers: {
34+
'Content-Type': 'text/plain',
35+
},
36+
})
37+
}
38+
39+
if (!(await handleTurnstile(request))) {
40+
return new Response(turnstileWidget, {
41+
status: 200,
42+
headers: {
43+
'Content-Type': 'text/html',
44+
},
45+
})
46+
}
47+
}
48+
49+
export const config = { path: '/*' }

netlify/edge-functions/handle-null-ua.ts

Lines changed: 0 additions & 14 deletions
This file was deleted.

0 commit comments

Comments
 (0)