rembg / frontend /src /lib /turnstile.js
ilhamdev's picture
feat: implement frontend web application with background removal and Turnstile verification support
7c0b48c
Raw History Blame Contribute Delete
1.9 kB
const CLOUDFLARE_SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
export const DEFAULT_TEST_SECRET = '1x0000000000000000000000000000000AA'
export const DEFAULT_TEST_SITE_KEY = '1x00000000000000000000AA'
/**
* Validates Cloudflare Turnstile token with Cloudflare's siteverify endpoint.
*
* @param {Object} options
* @param {string} options.token - Token generated by Turnstile widget on client
* @param {string} [options.remoteIp] - Client IP address (optional)
* @param {string} [options.secretKey] - Cloudflare Secret Key
* @returns {Promise<{ success: boolean, error?: string, details?: any }>}
*/
export async function verifyTurnstileToken({ token, remoteIp, secretKey }) {
const trimmedToken = typeof token === 'string' ? token.trim() : ''
if (!trimmedToken) {
return {
success: false,
error: 'Token Turnstile tidak ditemukan atau tidak valid.',
}
}
const secret = secretKey || process.env.TURNSTILE_SECRET_KEY || DEFAULT_TEST_SECRET
const formData = new URLSearchParams()
formData.append('secret', secret)
formData.append('response', trimmedToken)
if (remoteIp) {
formData.append('remoteip', remoteIp)
}
try {
const res = await fetch(CLOUDFLARE_SITEVERIFY_URL, {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
const data = await res.json()
if (data.success) {
return { success: true, details: data }
}
const errorCodes = data['error-codes']?.join(', ') || 'Verifikasi ditolak'
return {
success: false,
error: `Verifikasi Turnstile gagal (${errorCodes})`,
details: data,
}
} catch (err) {
console.error('[Turnstile Verify Error]', err)
return {
success: false,
error: `Gagal menghubungi server verifikasi Turnstile: ${err.message}`,
}
}
}