From e6cc8e2ffdf65b6cc08800a4a75ed1d137701763 Mon Sep 17 00:00:00 2001 From: Dream Hunter Date: Thu, 12 Mar 2026 00:47:26 +0800 Subject: [PATCH] feat: add Turnstile CAPTCHA for login forms (#767) (#885) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add Turnstile CAPTCHA for login forms (#767) Add optional Turnstile verification for admin login, user login, and address password login via ENABLE_LOGIN_TURNSTILE_CHECK env var. Does not affect existing Turnstile on address creation / registration. Co-Authored-By: Claude Opus 4.6 * docs: add ENABLE_LOGIN_TURNSTILE_CHECK to wrangler.toml.template Co-Authored-By: Claude Opus 4.6 * fix: ensure openSettings loaded before admin login modal Co-Authored-By: Claude Opus 4.6 * feat: add Turnstile to site access password and fix settings field name - Add Turnstile to site access password modal in Header.vue - Add /open_api/site_login endpoint for password + Turnstile verification - Fix settings field name from enableTurnstileLogin to enableLoginTurnstileCheck Co-Authored-By: Claude Opus 4.6 * refactor: move login endpoints to open_api/auth.ts Move /open_api/site_login and /open_api/admin_login from commom_api.ts to a dedicated open_api/auth.ts file for better code organization. Co-Authored-By: Claude Opus 4.6 * fix: change Turnstile check failure status from 500 to 400 Turnstile validation failure is a client error, not a server error. Change all Turnstile check error responses from 500 to 400. Co-Authored-By: Claude Opus 4.6 * fix: use unique IDs for multiple Turnstile instances When multiple modals with Turnstile appear simultaneously (e.g., site access + admin login), the hardcoded id="cf-turnstile" causes conflicts. Generate a unique container ID per Turnstile instance to fix this. Co-Authored-By: Claude Opus 4.6 * fix: review fixes - cfToken separation, register Turnstile, error codes - Separate cfToken refs in Login.vue to avoid token sharing between login and new address creation Turnstile instances - Add Turnstile check to user registration endpoint (not just verify_code) - Show Turnstile on register tab regardless of enableMailVerify - Pass cf_token in register request body - Fix site_login error message to use CustomAuthPasswordMsg - Fix verifyCode Turnstile error status from 500 to 400 - Restore empty line in commom_api.ts Co-Authored-By: Claude Opus 4.6 * fix: separate register Turnstile logic for with/without mail verify - With mail verify: verify_code already checks Turnstile, register skips Turnstile (token is one-time use) - Without mail verify: register checks Turnstile directly - Separate loginCfToken for login tab to avoid token sharing with register tab Turnstile Co-Authored-By: Claude Opus 4.6 * fix: add enableLoginTurnstileCheck to store defaults, simplify changelog Co-Authored-By: Claude Opus 4.6 * fix: add /open_api/credential_login for credential login verification Add credential_login endpoint that verifies both Turnstile token and JWT credential server-side, replacing the generic verify_turnstile endpoint. Credential login now validates the JWT before accepting it. Co-Authored-By: Claude Opus 4.6 * fix: improve login endpoints - hash passwords, expose Turnstile refresh, fix status codes - site_login/admin_login: always called, verify hashed password + optional Turnstile - credential_login: always called, verify JWT + optional Turnstile - Frontend sends hashed passwords instead of plaintext - Turnstile component exposes refresh method via defineExpose - Fix Turnstile error status 500→400 in mails_api and telegram_api Co-Authored-By: Claude Opus 4.6 * refactor: rename to ENABLE_GLOBAL_TURNSTILE_CHECK and add isGlobalTurnstileEnabled helper - Rename ENABLE_LOGIN_TURNSTILE_CHECK -> ENABLE_GLOBAL_TURNSTILE_CHECK - Add isGlobalTurnstileEnabled() in utils.ts: checks env var + Turnstile keys all present - Backend settings returns enableGlobalTurnstileCheck computed from the helper - All backend endpoints use isGlobalTurnstileEnabled(c) instead of raw env check - Update all frontend refs, docs, changelog, and wrangler template Co-Authored-By: Claude Opus 4.6 * refactor: use utils.isGlobalTurnstileEnabled instead of named import Co-Authored-By: Claude Opus 4.6 * test: add E2E tests for turnstile login endpoints - Test all 3 new /open_api/* endpoints when ENABLE_GLOBAL_TURNSTILE_CHECK is disabled - Verify settings returns enableGlobalTurnstileCheck: false - Test admin_login with correct/wrong/empty hashed password - Test site_login returns 401 when no PASSWORDS configured - Test credential_login with valid JWT, invalid JWT, empty credential - Test address_login with empty cf_token works when turnstile disabled - Add ADMIN_PASSWORDS to E2E wrangler config for admin_login tests Co-Authored-By: Claude Opus 4.6 * test: rename test file to login-endpoints.spec.ts Co-Authored-By: Claude Opus 4.6 * fix: validate JWT payload has address field in credential_login Prevents user tokens or challenge tokens from being accepted as address credentials since they share the same JWT_SECRET. Co-Authored-By: Claude Opus 4.6 * fix: refresh Turnstile token on login failure to allow retry After a failed login attempt, the consumed Turnstile token is now refreshed so users can retry without manually refreshing. Also adds ref to signup Turnstile in UserLogin.vue to refresh after verification code is sent (single-use token consumed). Co-Authored-By: Claude Opus 4.6 * fix: separate Turnstile tokens for signup and reset password flows Split shared cfToken into signupCfToken and resetCfToken to prevent single-use Turnstile token conflicts between signup tab and reset password modal. Each flow now has its own token ref and refreshes the correct Turnstile widget after use. Co-Authored-By: Claude Opus 4.6 * fix: update comments from "login turnstile" to "global turnstile" Co-Authored-By: Claude Opus 4.6 --------- Co-authored-by: Claude Opus 4.6 --- CHANGELOG.md | 1 + CHANGELOG_EN.md | 1 + e2e/fixtures/wrangler.toml.e2e | 1 + e2e/tests/api/login-endpoints.spec.ts | 132 ++++++++++++++++++++ frontend/src/api/index.js | 1 + frontend/src/components/Turnstile.vue | 12 +- frontend/src/store/index.js | 1 + frontend/src/views/Admin.vue | 17 ++- frontend/src/views/Header.vue | 15 ++- frontend/src/views/common/Login.vue | 17 ++- frontend/src/views/user/UserLogin.vue | 30 +++-- vitepress-docs/docs/en/guide/worker-vars.md | 5 +- vitepress-docs/docs/zh/guide/worker-vars.md | 5 +- worker/src/commom_api.ts | 3 +- worker/src/mails_api/address_auth.ts | 11 +- worker/src/mails_api/index.ts | 2 +- worker/src/open_api/auth.ts | 69 ++++++++++ worker/src/telegram_api/miniapp.ts | 2 +- worker/src/user_api/user.ts | 25 +++- worker/src/utils.ts | 7 ++ worker/src/worker.ts | 2 + worker/wrangler.toml.template | 2 + 22 files changed, 335 insertions(+), 26 deletions(-) create mode 100644 e2e/tests/api/login-endpoints.spec.ts create mode 100644 worker/src/open_api/auth.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ef48432..d57364db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ ### Features - feat: |自动回复| 发件人过滤支持正则表达式匹配,使用 `/pattern/` 语法(如 `/@example\.com$/`),同时保持前缀匹配的向后兼容 +- feat: |Turnstile| 新增全局登录表单 Turnstile 人机验证,通过 `ENABLE_GLOBAL_TURNSTILE_CHECK` 环境变量控制(#767) ### Bug Fixes diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 00e8e384..f22fdfeb 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -11,6 +11,7 @@ ### Features - feat: |Auto Reply| Add regex matching support for sender filter using `/pattern/` syntax (e.g. `/@example\.com$/`), backward compatible with prefix matching +- feat: |Turnstile| Add global Turnstile CAPTCHA for all login forms via `ENABLE_GLOBAL_TURNSTILE_CHECK` env var (#767) ### Bug Fixes diff --git a/e2e/fixtures/wrangler.toml.e2e b/e2e/fixtures/wrangler.toml.e2e index 8076222f..b0805260 100644 --- a/e2e/fixtures/wrangler.toml.e2e +++ b/e2e/fixtures/wrangler.toml.e2e @@ -16,6 +16,7 @@ ENABLE_AUTO_REPLY = true DEFAULT_SEND_BALANCE = 10 ENABLE_ADDRESS_PASSWORD = true DISABLE_ADMIN_PASSWORD_CHECK = true +ADMIN_PASSWORDS = '["e2e-admin-pass"]' ENABLE_WEBHOOK = true E2E_TEST_MODE = true SMTP_CONFIG = """ diff --git a/e2e/tests/api/login-endpoints.spec.ts b/e2e/tests/api/login-endpoints.spec.ts new file mode 100644 index 00000000..1d4a2450 --- /dev/null +++ b/e2e/tests/api/login-endpoints.spec.ts @@ -0,0 +1,132 @@ +import { test, expect } from '@playwright/test'; +import { WORKER_URL, createTestAddress, deleteAddress } from '../../fixtures/test-helpers'; +import * as crypto from 'crypto'; + +/** + * SHA-256 hash matching frontend hashPassword utility. + */ +function hashPassword(password: string): string { + return crypto.createHash('sha256').update(password).digest('hex'); +} + +test.describe('Turnstile Login Endpoints (ENABLE_GLOBAL_TURNSTILE_CHECK disabled)', () => { + + test('settings returns enableGlobalTurnstileCheck as false', async ({ request }) => { + const res = await request.get(`${WORKER_URL}/open_api/settings`); + expect(res.ok()).toBe(true); + const settings = await res.json(); + expect(settings.enableGlobalTurnstileCheck).toBe(false); + }); + + test.describe('/open_api/site_login', () => { + test('returns 401 when no PASSWORDS configured', async ({ request }) => { + const res = await request.post(`${WORKER_URL}/open_api/site_login`, { + data: { + password: hashPassword('any-pass'), + cf_token: '' + } + }); + expect(res.status()).toBe(401); + }); + }); + + test.describe('/open_api/admin_login', () => { + test('correct hashed password succeeds', async ({ request }) => { + const res = await request.post(`${WORKER_URL}/open_api/admin_login`, { + data: { + password: hashPassword('e2e-admin-pass'), + cf_token: '' + } + }); + expect(res.ok()).toBe(true); + const body = await res.json(); + expect(body.success).toBe(true); + }); + + test('wrong password returns 401', async ({ request }) => { + const res = await request.post(`${WORKER_URL}/open_api/admin_login`, { + data: { + password: hashPassword('wrong-admin'), + cf_token: '' + } + }); + expect(res.status()).toBe(401); + }); + + test('empty password returns 401', async ({ request }) => { + const res = await request.post(`${WORKER_URL}/open_api/admin_login`, { + data: { + password: '', + cf_token: '' + } + }); + expect(res.status()).toBe(401); + }); + }); + + test.describe('/open_api/credential_login', () => { + test('valid JWT credential succeeds', async ({ request }) => { + const { jwt, address } = await createTestAddress(request, 'cred-login'); + try { + const res = await request.post(`${WORKER_URL}/open_api/credential_login`, { + data: { + credential: jwt, + cf_token: '' + } + }); + expect(res.ok()).toBe(true); + const body = await res.json(); + expect(body.success).toBe(true); + } finally { + await deleteAddress(request, jwt); + } + }); + + test('invalid JWT returns 401', async ({ request }) => { + const res = await request.post(`${WORKER_URL}/open_api/credential_login`, { + data: { + credential: 'invalid.jwt.token', + cf_token: '' + } + }); + expect(res.status()).toBe(401); + }); + + test('empty credential returns 401', async ({ request }) => { + const res = await request.post(`${WORKER_URL}/open_api/credential_login`, { + data: { + credential: '', + cf_token: '' + } + }); + expect(res.status()).toBe(401); + }); + }); + + test.describe('/api/address_login with cf_token', () => { + test('address login with empty cf_token works when turnstile disabled', async ({ request }) => { + const { jwt, address } = await createTestAddress(request, 'addr-cf'); + try { + // Set a password + await request.post(`${WORKER_URL}/api/address_change_password`, { + headers: { Authorization: `Bearer ${jwt}` }, + data: { new_password: 'addr-pass-123' }, + }); + + // Login with cf_token field present but empty + const loginRes = await request.post(`${WORKER_URL}/api/address_login`, { + data: { + email: address, + password: 'addr-pass-123', + cf_token: '' + }, + }); + expect(loginRes.ok()).toBe(true); + const body = await loginRes.json(); + expect(body.jwt).toBeTruthy(); + } finally { + await deleteAddress(request, jwt); + } + }); + }); +}); diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js index e1d8e0df..8554237a 100644 --- a/frontend/src/api/index.js +++ b/frontend/src/api/index.js @@ -93,6 +93,7 @@ const getOpenSettings = async (message, notification) => { isS3Enabled: res["isS3Enabled"] || false, enableAddressPassword: res["enableAddressPassword"] || false, statusUrl: res["statusUrl"] || "", + enableGlobalTurnstileCheck: res["enableGlobalTurnstileCheck"] || false, }); if (openSettings.value.needAuth) { showAuth.value = true; diff --git a/frontend/src/components/Turnstile.vue b/frontend/src/components/Turnstile.vue index 89df4936..e22a7cb6 100644 --- a/frontend/src/components/Turnstile.vue +++ b/frontend/src/components/Turnstile.vue @@ -17,17 +17,21 @@ const { locale, t } = useI18n({ } }); +const containerId = `cf-turnstile-${Math.random().toString(36).slice(2, 9)}` const cfTurnstileId = ref("") const turnstileLoading = ref(false) +const refresh = () => checkCfTurnstile(true) +defineExpose({ refresh }) + const checkCfTurnstile = async (remove) => { if (!openSettings.value.cfTurnstileSiteKey) return; turnstileLoading.value = true; try { - let container = document.getElementById("cf-turnstile"); + let container = document.getElementById(containerId); let count = 100; while (!container && count-- > 0) { - container = document.getElementById("cf-turnstile"); + container = document.getElementById(containerId); await new Promise(r => setTimeout(r, 10)); } count = 100; @@ -38,7 +42,7 @@ const checkCfTurnstile = async (remove) => { window.turnstile.remove(cfTurnstileId.value); } cfTurnstileId.value = window.turnstile.render( - "#cf-turnstile", + `#${containerId}`, { sitekey: openSettings.value.cfTurnstileSiteKey, language: locale.value == 'zh' ? 'zh-CN' : 'en-US', @@ -68,7 +72,7 @@ onMounted(() => { -
+
{{ t('refresh') }} diff --git a/frontend/src/store/index.js b/frontend/src/store/index.js index 4d511eab..8d76d63a 100644 --- a/frontend/src/store/index.js +++ b/frontend/src/store/index.js @@ -39,6 +39,7 @@ export const useGlobalState = createGlobalState( disableAdminPasswordCheck: false, enableAddressPassword: false, statusUrl: '', + enableGlobalTurnstileCheck: false, }) const settings = ref({ fetched: false, diff --git a/frontend/src/views/Admin.vue b/frontend/src/views/Admin.vue index f2fdd3eb..f3864f2b 100644 --- a/frontend/src/views/Admin.vue +++ b/frontend/src/views/Admin.vue @@ -5,7 +5,8 @@ import { useRouter } from 'vue-router' import { useGlobalState } from '../store' import { api } from '../api' -import { getRouterPathWithLang } from '../utils' +import { getRouterPathWithLang, hashPassword } from '../utils' +import Turnstile from '../components/Turnstile.vue' import SenderAccess from './admin/SenderAccess.vue' import Statistics from "./admin/Statistics.vue" @@ -44,12 +45,23 @@ const SendMail = defineAsyncComponent(() => { .finally(() => loading.value = false); }); +const cfToken = ref('') +const turnstileRef = ref(null) + const authFunc = async () => { try { + await api.fetch('/open_api/admin_login', { + method: 'POST', + body: JSON.stringify({ + password: await hashPassword(tmpAdminAuth.value), + cf_token: cfToken.value + }) + }); adminAuth.value = tmpAdminAuth.value; location.reload() } catch (error) { message.error(error.message || "error"); + turnstileRef.value?.refresh?.(); } } @@ -169,6 +181,8 @@ const currentLoginMethod = computed(() => { }) onMounted(async () => { + // make sure openSettings is fetched for turnstile check + if (!openSettings.value.fetched) await api.getOpenSettings(message); // make sure user_id is fetched if (!userSettings.value.user_id) await api.getUserSettings(message); }) @@ -180,6 +194,7 @@ onMounted(async () => { preset="dialog" :title="t('accessHeader')">

{{ t('accessTip') }}

+