feat: add CF Turnstile when new address (#200)

This commit is contained in:
Dream Hunter
2024-05-04 23:14:23 +08:00
committed by GitHub
parent 26969bebb8
commit f63c4ebd9c
14 changed files with 154 additions and 17 deletions

View File

@@ -1,7 +1,8 @@
import { Hono } from 'hono'
import {
getDomains, getPasswords, getBooleanValue, getJsonSetting
getDomains, getPasswords, getBooleanValue, getJsonSetting,
checkCfTurnstile
} from './utils';
import { newAddress } from './common'
import { CONSTANTS } from './constants'
@@ -116,14 +117,21 @@ api.get('/open_api/settings', async (c) => {
"enableUserDeleteEmail": getBooleanValue(c.env.ENABLE_USER_DELETE_EMAIL),
"enableAutoReply": getBooleanValue(c.env.ENABLE_AUTO_REPLY),
"copyright": c.env.COPYRIGHT,
"cfTurnstileSiteKey": c.env.CF_TURNSTILE_SITE_KEY,
});
})
api.get('/api/new_address', async (c) => {
api.post('/api/new_address', async (c) => {
if (!getBooleanValue(c.env.ENABLE_USER_CREATE_EMAIL)) {
return c.text("New address is disabled", 403)
}
let { name, domain } = c.req.query();
let { name, domain, cf_token } = await c.req.json();
// check cf turnstile
try {
await checkCfTurnstile(c, cf_token);
} catch (error) {
return c.text("Failed to check cf turnstile", 500)
}
// if no name, generate random name
if (!name) {
name = Math.random().toString(36).substring(2, 15);

View File

@@ -129,3 +129,24 @@ export const sendAdminInternalMail = async (c, toMail, subject, text) => {
return false;
}
};
export const checkCfTurnstile = async (c, token) => {
if (!c.env.CF_TURNSTILE_SITE_KEY) {
return;
}
const reqIp = c.req.raw.headers.get("cf-connecting-ip")
let formData = new FormData();
formData.append('secret', c.env.CF_TURNSTILE_SECRET_KEY);
formData.append('response', token);
formData.append('remoteip', reqIp);
const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
const result = await fetch(url, {
body: formData,
method: 'POST',
});
const captchaRes = await result.json();
if (!captchaRes.success) {
console.log("Captcha failed", captchaRes);
throw new Error("Captcha failed");
}
}

View File

@@ -32,6 +32,9 @@ ENABLE_AUTO_REPLY = false
# COPYRIGHT = "Dream Hunter"
# default send balance, if not set, it will be 0
# DEFAULT_SEND_BALANCE = 1
# Turnstile verification
# CF_TURNSTILE_SITE_KEY = ""
# CF_TURNSTILE_SECRET_KEY = ""
# dkim config
# DKIM_SELECTOR = ""
# DKIM_PRIVATE_KEY = ""