feat(captcha): 打通人机验证 11 个场景的前后端完整链路

- 统一验证入口 aksrt_require_captcha(),返回 true|WP_Error,启用场景配置缺失时 fail-closed 拒绝
- 前端公共 API 重构为 window.AKSRTCaptcha(verify/collect/reset/run),单飞锁防并发重复验证,一次性 proof 绑定浏览器 cookie+场景+服务商+主机名
- challenge/exchange REST 端点:challenge 原子占用防票据放大厂商调用,增加频率限制
- 新增 OAuth bind pass:服务端签发 5 分钟一次性令牌,绑定用户+服务商+浏览器,微信扫码延迟消费
- 覆盖场景:评论、登录、注册、绑定第三方、绑定手机、找回密码、修改密码、更改邮箱、资料下载、签到、前台投稿
- 移除 Service 层重复验证与 _auth_code_verified/_defer_login 等客户端可伪造标志,删除下载共享 pass 死代码
- 修复腾讯 TC3 签名 scope、Cloudflare action/cdata/hostname 严格校验、阿里云验签错误码映射
- 后台 Schema 保存对 secret 字段做掩码/保留合并;导入导出过滤 aksrt_captcha_config
- 重建 public bundle 与 admin SPA;新增 captcha 运行时/安全/业务契约测试与 harness
This commit is contained in:
kate522 committed 2026-09-02 13:03:24 +08:00
1 parent d2e95acd75
commit ff4ec1eb43
45 files changed
+2694 -1435

No files matched your search

+21 -4
View File
@@ -29,6 +29,13 @@ class Moderation {
*/
private $forced_approved_map = [];
/**
* Request-local depth for comment submissions already admitted by the REST controller.
*
* @var int
*/
private $captcha_verified_comment_request_depth = 0;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
@@ -50,6 +57,14 @@ class Moderation {
add_action('manage_comments_custom_column', [$this, 'render_comments_custom_column'], 10, 2);
}
public function begin_captcha_verified_comment_request(): void {
$this->captcha_verified_comment_request_depth++;
}
public function end_captcha_verified_comment_request(): void {
$this->captcha_verified_comment_request_depth = max(0, $this->captcha_verified_comment_request_depth - 1);
}
public function get_config(): array {
$defaults = [
'enabled' => false,
@@ -90,17 +105,19 @@ class Moderation {
);
}
// 人机验证:覆盖 REST 与原生 wp-comments-post 两条提交合同(与审核开关无关)
if (function_exists('aksrt_require_captcha')) {
// 人机验证:原生 wp-comments-post 必须验证;REST 已在 Controller 准入时验证一次。
if ($this->captcha_verified_comment_request_depth === 0) {
$payload = is_array($_POST ?? null) ? wp_unslash($_POST) : [];
if (isset($payload['captcha']) && is_array($payload['captcha'])) {
$payload = array_merge($payload, $payload['captcha']);
}
$captcha_result = aksrt_require_captcha('comment', $payload);
if ($captcha_result !== true) {
$msg = is_string($captcha_result) ? $captcha_result : __('人机验证失败', 'aksrt');
$msg = is_wp_error($captcha_result)
? $captcha_result->get_error_message()
: __('人机验证失败', 'aksrt');
wp_die(
esc_html($msg),
esc_html($msg !== '' ? $msg : __('人机验证失败', 'aksrt')),
esc_html__('评论提交失败', 'aksrt'),
['response' => 400, 'back_link' => true]
);
+124 -5
View File
@@ -9,6 +9,9 @@ defined('ABSPATH') || exit;
final class OAuth {
private const BIND_PASS_KIND = 'oauth_bind_pass';
private const BIND_PASS_TTL = 5 * MINUTE_IN_SECONDS;
private static $instance = null;
private OAuthProviderBroker $broker;
@@ -32,6 +35,7 @@ final class OAuth {
}
}, 30);
add_action('template_redirect', [$this, 'handle_routes'], 8);
add_action('rest_api_init', [$this, 'register_rest_routes']);
add_action('wp_ajax_aksrt_oauth_unbind', [$this, 'ajax_unbind']);
}
@@ -47,6 +51,109 @@ final class OAuth {
});
}
public function register_rest_routes(): void {
register_rest_route('aksrt/v1', '/oauth/bind-pass', [
'methods' => 'POST',
'callback' => [$this, 'rest_issue_bind_pass'],
'permission_callback' => static function (): bool {
return is_user_logged_in();
},
]);
}
public function rest_issue_bind_pass(\WP_REST_Request $request): \WP_REST_Response {
$user_id = get_current_user_id();
$nonce = sanitize_text_field((string) $request->get_header('X-WP-Nonce'));
if ($user_id <= 0 || $nonce === '' || !wp_verify_nonce($nonce, 'wp_rest')) {
return new \WP_REST_Response([
'success' => false,
'code' => 'oauth_bind_nonce_invalid',
'message' => __('安全验证失败,请刷新页面重试', 'aksrt'),
], 403);
}
$payload = $request->get_json_params();
$payload = is_array($payload) ? $payload : [];
$provider = sanitize_key((string) ($payload['provider'] ?? ''));
if (!in_array($provider, OAuthProviderCatalog::enabled_login_keys(), true)) {
return new \WP_REST_Response([
'success' => false,
'code' => 'oauth_bind_provider_invalid',
'message' => __('该第三方登录方式不可用', 'aksrt'),
], 400);
}
$url = $this->get_auth_url($provider, 'bind');
if ($url === '') {
return new \WP_REST_Response([
'success' => false,
'code' => 'oauth_bind_provider_invalid',
'message' => __('该第三方登录方式不可用', 'aksrt'),
], 400);
}
$redirect = OAuthUrlPolicy::validated_redirect((string) ($payload['redirect_to'] ?? ''), home_url('/'));
$url = add_query_arg('redirect_to', $redirect, $url);
if (!aksrt_is_captcha_enabled_for('bind')) {
return new \WP_REST_Response([
'success' => true,
'data' => ['url' => $url],
], 200);
}
$result = aksrt_require_captcha('bind', $payload);
if ($result !== true) {
return new \WP_REST_Response([
'success' => false,
'code' => is_wp_error($result) ? $result->get_error_code() : 'aksrt_captcha_failed',
'message' => is_wp_error($result) ? $result->get_error_message() : __('人机验证失败,请重试', 'aksrt'),
], 400);
}
try {
$pass = OAuthTransactionStore::issue(self::BIND_PASS_KIND, [
'user_id' => $user_id,
'provider' => $provider,
], self::BIND_PASS_TTL, true);
} catch (\Throwable $e) {
return new \WP_REST_Response([
'success' => false,
'code' => 'oauth_bind_pass_issue_failed',
'message' => __('无法创建绑定会话,请稍后重试', 'aksrt'),
], 500);
}
$url = add_query_arg('bind_pass', $pass, $url);
return new \WP_REST_Response([
'success' => true,
'data' => ['url' => $url],
], 200);
}
public static function validate_bind_pass(string $token, string $provider, int $user_id, bool $consume = true): bool {
if (!aksrt_is_captcha_enabled_for('bind')) {
return true;
}
if ($token === '' || $user_id <= 0) {
return false;
}
$matches = static function (?array $row) use ($provider, $user_id): bool {
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
return $row !== null
&& (int) ($payload['user_id'] ?? 0) === $user_id
&& hash_equals(sanitize_key($provider), sanitize_key((string) ($payload['provider'] ?? '')));
};
$row = OAuthTransactionStore::peek($token, self::BIND_PASS_KIND, true);
if (!$matches($row)) {
return false;
}
if (!$consume) {
return true;
}
return $matches(OAuthTransactionStore::claim($token, self::BIND_PASS_KIND, true));
}
public function maybe_flush_rewrite_rules(): void {
$version = defined('AKSRT_VERSION') ? AKSRT_VERSION . ':oauth-v2' : 'oauth-v2';
if (get_option('aksrt_oauth_routes_flushed') !== $version) {
@@ -186,6 +293,17 @@ final class OAuth {
if (!OAuthProviderCatalog::master_enabled() || !in_array($provider, OAuthProviderCatalog::enabled_login_keys(), true)) {
$this->redirect_error('provider_disabled', $provider, $action);
}
$user_id = get_current_user_id();
if ($action === 'bind' && $user_id <= 0) {
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
exit;
}
if ($action === 'bind') {
$bind_pass = sanitize_text_field((string) ($_GET['bind_pass'] ?? ''));
if (!self::validate_bind_pass($bind_pass, $provider, $user_id, true)) {
$this->redirect_error('bind_verification_required', $provider, $action);
}
}
if (OAuthProviderCatalog::proxy_mode() === 'client') {
$url = OAuthProxyClient::get_instance()->get_proxy_auth_url($provider, $action);
if ($url === '') {
@@ -194,11 +312,6 @@ final class OAuth {
wp_redirect($url); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit;
}
$user_id = get_current_user_id();
if ($action === 'bind' && $user_id <= 0) {
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
exit;
}
$redirect = isset($_GET['redirect_to']) ? OAuthUrlPolicy::validated_redirect((string) $_GET['redirect_to'], home_url('/')) : home_url('/');
$redirect_uri = home_url('/oauth/callback/');
try {
@@ -264,6 +377,12 @@ final class OAuth {
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
exit;
}
if ($action === 'bind') {
$bind_pass = sanitize_text_field((string) ($_GET['bind_pass'] ?? ''));
if (!self::validate_bind_pass($bind_pass, 'clogin_' . $type, get_current_user_id(), true)) {
$this->redirect_error('bind_verification_required', 'clogin_' . $type, $action);
}
}
$redirect = isset($_GET['redirect_to']) ? OAuthUrlPolicy::validated_redirect((string) $_GET['redirect_to'], home_url('/')) : home_url('/');
try {
$state = OAuthTransactionStore::issue('clogin', [
+1 -8
View File
@@ -117,16 +117,9 @@ final class Service {
return true;
}
public static function login_user(array $post, string $captcha_scene = 'login'): array {
public static function login_user(array $post): array {
$resolved_login = self::resolve_email_to_username((string) ($post['log'] ?? ''));
if (function_exists('aksrt_require_captcha')) {
$captcha_result = aksrt_require_captcha($captcha_scene, $post);
if ($captcha_result !== true) {
return ['success' => false, 'error' => $captcha_result];
}
}
$creds = [
'user_login' => $resolved_login,
'user_password' => (string) ($post['pwd'] ?? ''),
+7 -14
View File
@@ -10,7 +10,7 @@ defined('ABSPATH') || exit;
trait ServicePart1a {
public static function register_user(array $post): array {
public static function register_user(array $post, bool $verification_completed = false, bool $defer_login = false): array {
$user_login = sanitize_user(wp_unslash($post['user_login'] ?? ''), true);
$user_email = sanitize_email(wp_unslash($post['user_email'] ?? ''));
$password = (string) ($post['user_pass'] ?? '');
@@ -19,7 +19,7 @@ trait ServicePart1a {
if (
class_exists('\AKSRT\Settings\Settings')
&& \AKSRT\Settings\Settings::signup_verification_enabled()
&& empty($post['_auth_code_verified'])
&& !$verification_completed
) {
return ['success' => false, 'error' => __('请先完成邮箱或手机验证', 'aksrt')];
}
@@ -83,13 +83,6 @@ trait ServicePart1a {
return ['success' => false, 'error' => $password_check];
}
if (empty($post['_auth_code_verified']) && function_exists('aksrt_require_captcha')) {
$captcha_result = aksrt_require_captcha('register', $post);
if ($captcha_result !== true) {
return ['success' => false, 'error' => $captcha_result];
}
}
$ref_service = class_exists('\AKSRT\Payment\ReferralAttribution')
? \AKSRT\Payment\ReferralAttribution::get_instance()
: null;
@@ -143,15 +136,15 @@ trait ServicePart1a {
return ['success' => false, 'error' => __('注册成功,但读取用户信息失败,请联系管理员', 'aksrt')];
}
if (
empty($post['_defer_login'])
&& !empty($post['_auth_code_verified'])
&& class_exists('\AKSRT\Settings\Settings')
if (
!$defer_login
&& $verification_completed
&& class_exists('\AKSRT\Settings\Settings')
&& \AKSRT\Settings\Settings::signup_verification_enabled()
) {
self::mark_email_verified($user_id);
}
if (empty($post['_defer_login'])) {
if (!$defer_login) {
wp_set_auth_cookie((int) $user_id, true);
do_action('wp_login', $user->user_login, $user);
}
+3 -10
View File
@@ -15,7 +15,7 @@ trait ServicePart1b {
* @param array $post POST 数据 (phone, code, password, ref)
* @return array{success: bool, user_id?: int, error?: string, redirect?: string}
*/
public static function register_by_phone(array $post): array {
public static function register_by_phone(array $post, bool $verification_completed = false, bool $defer_login = false): array {
$phone = sanitize_text_field((string) ($post['phone'] ?? ''));
$pass = (string) ($post['password'] ?? '');
$confirm = (string) ($post['password_confirm'] ?? '');
@@ -24,7 +24,7 @@ trait ServicePart1b {
if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
return ['success' => false, 'error' => __('手机号格式不正确', 'aksrt')];
}
if (empty($post['_auth_code_verified'])) {
if (!$verification_completed) {
return ['success' => false, 'error' => __('请先完成手机验证', 'aksrt')];
}
if ($username === '' || !validate_username($username) || mb_strlen($username) < 3 || mb_strlen($username) > 60) {
@@ -111,7 +111,7 @@ trait ServicePart1b {
// 自动登录
$user = get_userdata($user_id);
if (empty($post['_defer_login'])) {
if (!$defer_login) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id, true);
if ($user instanceof \WP_User) {
@@ -150,13 +150,6 @@ trait ServicePart1b {
return ['success' => false, 'error' => __('手机号格式不正确', 'aksrt')];
}
if (function_exists('aksrt_require_captcha')) {
$captcha_result = aksrt_require_captcha('bind_phone', $post);
if ($captcha_result !== true) {
return ['success' => false, 'error' => $captcha_result];
}
}
// 验证 SMS 验证码
if (class_exists('\AKSRT\Sms\SMS')) {
$verify_result = \AKSRT\Sms\SMS::get_instance()->verify_code($phone, $code);
+38 -11
View File
@@ -102,10 +102,19 @@ final class WeixinGzh {
if (is_wp_error($context)) {
return $this->error_response($context->get_error_message(), 403);
}
$config = self::settings();
if ((string) ($config['gzh_type'] ?? '') === 'subscribe') {
return $this->code_mode_response($config, $context);
}
$config = self::settings();
$mode = (string) ($config['gzh_type'] ?? '');
if ($context['action'] === 'bind') {
$data = $this->request_data($request);
$bind_pass = sanitize_text_field((string) ($data['bind_pass'] ?? ''));
if (!OAuth::validate_bind_pass($bind_pass, 'weixingzh', $context['user_id'], false)) {
return $this->error_response(__('请先完成人机验证后再绑定', 'aksrt'), 403);
}
$context['bind_pass'] = $bind_pass;
}
if ($mode === 'subscribe') {
return $this->code_mode_response($config, $context);
}
$appid = trim((string) ($config['appid'] ?? ''));
$secret = trim((string) ($config['appsecret'] ?? ''));
@@ -118,9 +127,10 @@ final class WeixinGzh {
'openid' => '',
'profile' => [],
'redirect_to' => $context['redirect_to'],
'action' => $context['action'],
'user_id' => $context['user_id'],
], self::SCAN_TTL, true);
'action' => $context['action'],
'user_id' => $context['user_id'],
'bind_pass' => (string) ($context['bind_pass'] ?? ''),
], self::SCAN_TTL, true);
if (!$this->store_scene_mapping($scene, $transaction)) {
throw new \RuntimeException('scene_mapping_failed');
}
@@ -211,11 +221,21 @@ final class WeixinGzh {
if (is_wp_error($context)) {
return $this->error_response($context->get_error_message(), 403);
}
$bind_pass = '';
if ($context['action'] === 'bind') {
$bind_pass = sanitize_text_field((string) ($data['bind_pass'] ?? ''));
if (!OAuth::validate_bind_pass($bind_pass, 'weixingzh', $context['user_id'], false)) {
return $this->error_response(__('请先完成人机验证后再绑定', 'aksrt'), 403);
}
}
$claimed = $this->claim_code_transaction($code, $context);
if (!$claimed) {
return $this->error_response(__('验证码无效、已过期或尝试次数过多', 'aksrt'), 400);
}
$payload = is_array($claimed['payload'] ?? null) ? $claimed['payload'] : [];
if ($context['action'] === 'bind') {
$payload['bind_pass'] = $bind_pass;
}
return $this->complete_browser_identity($payload);
}
@@ -297,9 +317,12 @@ final class WeixinGzh {
$html .= '<form class="aksrt-weixingzh-code-form" data-aksrt-weixingzh-code>';
$html .= '<p class="muted-2-color em09">' . esc_html(sprintf(__('关注公众号后发送「%s」获取验证码', 'aksrt'), $keyword)) . '</p>';
$html .= '<input type="hidden" name="action" value="' . esc_attr($context['action']) . '" />';
$html .= '<input type="hidden" name="user_id" value="' . esc_attr((string) $context['user_id']) . '" />';
$html .= '<input type="hidden" name="redirect_to" value="' . esc_attr($context['redirect_to']) . '" />';
$html .= '<input type="text" name="code" class="form-control" minlength="6" maxlength="12" autocomplete="one-time-code" placeholder="' . esc_attr__('请输入验证码', 'aksrt') . '" required />';
$html .= '<input type="hidden" name="user_id" value="' . esc_attr((string) $context['user_id']) . '" />';
$html .= '<input type="hidden" name="redirect_to" value="' . esc_attr($context['redirect_to']) . '" />';
if (!empty($context['bind_pass'])) {
$html .= '<input type="hidden" name="bind_pass" value="' . esc_attr((string) $context['bind_pass']) . '" />';
}
$html .= '<input type="text" name="code" class="form-control" minlength="6" maxlength="12" autocomplete="one-time-code" placeholder="' . esc_attr__('请输入验证码', 'aksrt') . '" required />';
$html .= '<button type="submit" class="but c-blue btn-block mt10">' . esc_html__('登录', 'aksrt') . '</button>';
$html .= '</form>';
return new \WP_REST_Response([
@@ -374,6 +397,10 @@ final class WeixinGzh {
if (!$this->binding_user_matches($payload)) {
return $this->error_response(__('绑定会话与当前用户不匹配', 'aksrt'), 403);
}
$bind_pass = sanitize_text_field((string) ($payload['bind_pass'] ?? ''));
if (!OAuth::validate_bind_pass($bind_pass, 'weixingzh', get_current_user_id(), true)) {
return $this->error_response(__('绑定验证已过期,请重新完成人机验证', 'aksrt'), 403);
}
$result = OAuthAccountService::bind(get_current_user_id(), 'weixingzh', $identity);
if (is_wp_error($result)) {
return $this->error_response($result->get_error_message(), 409);
@@ -382,7 +409,7 @@ final class WeixinGzh {
$redirect = add_query_arg(['oauth_action' => 'bind', 'oauth_provider' => 'weixingzh'], $redirect);
return new \WP_REST_Response([
'success' => true,
'data' => ['logged_in' => false, 'bound' => true, 'status' => 'bound', 'redirect' => $redirect],
'data' => ['logged_in' => false, 'bound' => true, 'status' => 'bound', 'redirect' => $redirect],
], 200);
}