」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 從 Google 的 reCAPTCHA 遷移到 Cloudflare Turnstile?

從 Google 的 reCAPTCHA 遷移到 Cloudflare Turnstile?

發佈於2024-07-31
瀏覽:599

Migrating from Google

Google reCAPTCHA 新定價將於 8 月 1 日推出,這意味著您還有幾天時間遷移到更便宜的替代方案或確保您的銀行帳戶資金充足。

1000 次驗證的起價為 1 美元,這將花費很多。在 Mailmeteor,我們廣泛使用 reCAPTCHA 來保護我們的服務免受機器人攻擊。隨著 Google 定價的變化,我們計算出我們每月需要支付數千美元才能繼續使用他們的 reCAPTCHA 服務。

什麼是驗證碼?

驗證碼是網路的重要組成部分。它的目的是將好公民與壞行為者區分開來。本質上,它是一項在前端運行並產生傳輸到後端的令牌的服務。然後後端驗證令牌是否合法,如果是,則執行操作。

Google 在推廣自己的服務方面做得很好,但值得慶幸的是,還有一些替代方案:

  1. h驗證碼。我們一開始也考慮過,但他們的定價與新 Google 的定價非常相似。
  2. Cloudflare 十字轉門。我們是 Cloudflare 的忠實粉絲,並且確實對其進行了研究。就目前而言,這是一項免費服務。

讓我們深入探討一下。

遠離 Google reCAPTCHA...

我們的免費工具之一是人工智慧電子郵件編寫器。它基本上是一個 HTML 頁面,將請求發送到我們的後端,然後發送到第三方 AI 解決方案。

為了防止濫用,Google reCAPTCHA 從第一天起就啟用了。到目前為止,驗證是如何完成的(後端):

// index.js
app.post('/api/email-ai-writer', recaptcha.middleware.verify, aiEmailWriter)

// ai_email_writer.js
async function aiEmailWriter(request, response) {
  try {
    // Recaptcha
    if (!request.recaptcha || request.recaptcha.error || !request.recaptcha.data) {
      console.warn('Recaptcha: verification failed.')
      return response.status(403).send({ error: true, message: 'Recaptcha: verification failed' })
    } else if (request.recaptcha.data.action !== 'aiemailwriter') {
      console.warn('Recaptcha: bad action name')
      return response.status(403).send({ error: true, message: 'Recaptcha: bad action name' })
    } else if (request.recaptcha.data.score 



這非常簡單,也是 Google reCAPTCHA 如此受歡迎的重要組成部分。佔地面積非常有限,而且非常容易實施。對於最好奇的人,我們利用了express-recaptcha包來使其非常容易實現。

....到 Cloudflare Turnstile

遷移到Turnstile時,我們找不到NPM包,所以我們必須寫一個中間件來處理代幣。它是這樣的:

// middlewares/turnstile.js
const turnstile = async (request, response, next) => {
  try {
    // Turnstile injects a token in "cf-turnstile-response".
    const token = request.query['cf-turnstile-response']
    const ip = request.header('CF-Connecting-IP')

    if (!token) {
      throw new Error('Missing CloudFlare Turnstile Token')
    }

    // Validate the token by calling the
    // "/siteverify" API endpoint.
    const formData = new FormData()
    formData.append('secret', process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY)
    formData.append('response', token)
    if (ip) formData.append('remoteip', ip)

    const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
    const result = await fetch(url, {
      body: formData,
      method: 'POST',
    })

    // Process the verification outcome
    const outcome = await result.json()

    if (!outcome.success) {
      throw new Error('CloudFlare Turnstile declined the token')
    }

    request.turnstile = outcome

    // If authentified, go to next middleware
    next()
  } catch (err) {
    console.error(err)
    return response.status(403).send('Forbidden')
  }
}

export { turnstile }

一旦中間件就位,我們就可以將其應用於任何請求:

// index.js
app.post('/api/ai-email-writer', aiRateLimiter, turnstile, aiEmailWriter)

在處理請求的函數內部,它與我們先前的非常相似:

// ai_email_writer.js
async function aiEmailWriter(request, response) {
  try {
    // CloudFlare Turnstile protection
    if (!request.turnstile || request.turnstile.error) {
      console.warn('Recaptcha: verification failed.')
      return response.status(403).json({ error: true, message: 'Recaptcha: verification failed' })
    } else if (request.turnstile.action !== 'aiemailwriter') {
      console.warn('Recaptcha: bad action name')
      return response.status(403).json({ error: true, message: 'Recaptcha: bad action name' })
    }

    ...

結論

從 reCAPTCHA 遷移到 Turnstile 非常簡單,不會超過幾個小時。它的工作原理非常相似,同時肯定會為您節省很多錢。

我沒有在本文中介紹前端,因為我們使用使用者看不到的看不見小工具。但 Turnstile 的文檔廣泛涵蓋如何使用其互動式小部件。

今天就這樣吧!

版本聲明 本文轉載於:https://dev.to/frenchcooc/migrating-from-googles-recaptcha-to-cloudflare-turnstile-17lf?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3