优化了一些问题fix(captcha)

This commit is contained in:
kate522 committed 2026-08-29 17:03:05 +08:00
1 parent 41da33bb13
commit 88eb29c645
10 files changed
+1074 -407

No files matched your search

+409
View File
@@ -5605,6 +5605,415 @@ tbquire.config({
jQuery.cookie=function(e,o,t){if(o===void 0){var i=null;if(document.cookie&&document.cookie!="")for(var r=document.cookie.split(";"),n=0;n<r.length;n++){var c=jQuery.trim(r[n]);if(c.substring(0,e.length+1)==e+"="){i=decodeURIComponent(c.substring(e.length+1));break}}return i}t=t||{},o===null&&(o="",t.expires=-1);var a="";if(t.expires&&(typeof t.expires=="number"||t.expires.toUTCString)){var l2;typeof t.expires=="number"?(l2=new Date,l2.setTime(l2.getTime()+24*t.expires*60*60*1e3)):l2=t.expires,a="; expires="+l2.toUTCString()}var u=t.path?"; path="+t.path:"",s=t.domain?"; domain="+t.domain:"",m=t.secure?"; secure":"";document.cookie=[e,"=",encodeURIComponent(o),a,u,s,m].join("")};var lcs={get:function(e){return window.localStorage?localStorage.getItem(e):jQuery.cookie(e)},set:function(e,o){window.localStorage?localStorage[e]=o:jQuery.cookie(e,o)},remove:function(e){window.localStorage?localStorage.removeItem(e):jQuery.cookie(e,"")}};function aksrt__(key){var map=window._win&&window._win.i18n;return map&&Object.prototype.hasOwnProperty.call(map,key)?map[key]:key}function aksrt_is_fatal_error_response(text){return text&&(text.indexOf("Fatal error")>-1||text.indexOf("致命错误")>-1)}function aksrt_sprintf(key){var args=Array.prototype.slice.call(arguments,1),str=aksrt__(key),autoIndex=0;return str.replace(/%(\d+\$)?s/g,function(match,num){var idx=num?parseInt(num,10)-1:autoIndex++;return args[idx]!==void 0&&args[idx]!==null?args[idx]:match})}(function(window2,factory){var lazySizes=factory(window2,window2.document,Date);window2.lazySizes=lazySizes,typeof module=="object"&&module.exports&&(module.exports=lazySizes)})(typeof window<"u"?window:{},function(window2,document2,Date2){"use strict";var lazysizes,lazySizesCfg;if((function(){var prop,lazySizesDefaults={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",loadafterClass:"lazyloadafter",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};lazySizesCfg=window2.lazySizesConfig||window2.lazysizesConfig||{};for(prop in lazySizesDefaults)prop in lazySizesCfg||(lazySizesCfg[prop]=lazySizesDefaults[prop])})(),!document2||!document2.getElementsByClassName)return{init:function(){},cfg:lazySizesCfg,noSupport:!0};var docElem=document2.documentElement,supportPicture=window2.HTMLPictureElement,_addEventListener="addEventListener",_getAttribute="getAttribute",addEventListener=window2[_addEventListener].bind(window2),setTimeout2=window2.setTimeout,requestAnimationFrame2=window2.requestAnimationFrame||setTimeout2,requestIdleCallback=window2.requestIdleCallback,regPicture=/^picture$/i,loadEvents=["load","error","lazyincluded","_lazyloaded"],regClassCache={},forEach=Array.prototype.forEach,hasClass=function(ele,cls){return regClassCache[cls]||(regClassCache[cls]=new RegExp("(\\s|^)"+cls+"(\\s|$)")),regClassCache[cls].test(ele[_getAttribute]("class")||"")&&regClassCache[cls]},addClass=function(ele,cls){hasClass(ele,cls)||ele.setAttribute("class",(ele[_getAttribute]("class")||"").trim()+" "+cls)},removeClass=function(ele,cls){var reg2;(reg2=hasClass(ele,cls))&&ele.setAttribute("class",(ele[_getAttribute]("class")||"").replace(reg2," "))},addRemoveLoadEvents=function(dom,fn,add){var action=add?_addEventListener:"removeEventListener";add&&addRemoveLoadEvents(dom,fn),loadEvents.forEach(function(evt){dom[action](evt,fn)})},triggerEvent=function(elem,name,detail,noBubbles,noCancelable){var event=document2.createEvent("Event");return detail||(detail={}),detail.instance=lazysizes,event.initEvent(name,!noBubbles,!noCancelable),event.detail=detail,elem.dispatchEvent(event),event},updatePolyfill=function(el,full){var polyfill;!supportPicture&&(polyfill=window2.picturefill||lazySizesCfg.pf)?(full&&full.src&&!el[_getAttribute]("srcset")&&el.setAttribute("srcset",full.src),polyfill({reevaluate:!0,elements:[el]})):full&&full.src&&(el.src=full.src)},getCSS=function(elem,style){return(getComputedStyle(elem,null)||{})[style]},getWidth=function(elem,parent,width){for(width=width||elem.offsetWidth;width<lazySizesCfg.minSize&&parent&&!elem._lazysizesWidth;)width=parent.offsetWidth,parent=parent.parentNode;return width},rAF=(function(){var running,waiting,firstFns=[],secondFns=[],fns=firstFns,run=function(){var runFns=fns;for(fns=firstFns.length?secondFns:firstFns,running=!0,waiting=!1;runFns.length;)runFns.shift()();running=!1},rafBatch=function(fn,queue){running&&!queue?fn.apply(this,arguments):(fns.push(fn),waiting||(waiting=!0,(document2.hidden?setTimeout2:requestAnimationFrame2)(run)))};return rafBatch._lsFlush=run,rafBatch})(),rAFIt=function(fn,simple){return simple?function(){rAF(fn)}:function(){var that=this,args=arguments;rAF(function(){fn.apply(that,args)})}},throttle2=function(fn){var running,lastTime=0,gDelay=lazySizesCfg.throttleDelay,rICTimeout=lazySizesCfLine truncated
;
/* source: assets/js/captcha-front.js */
/**
* AKSRT Captcha front-end runtime — cloud providers only (tencent / aliyun / cloudflare / geetest).
*
* PHP renders passive mounts via [data-aksrt-captcha-config] (JSON config attribute);
* this script scans them, registers AKSRTCaptchaState.scenes[scene], loads the provider
* SDK once per page, and writes verified tokens back into the surrounding form.
* Bundled into assets/js/build/public.js by tools/build-public-assets.mjs.
*/
(function () {
'use strict';
var TOKEN_FIELDS = [
'cf_turnstile_response',
'tencent_ticket', 'tencent_randstr', 'tencent_sid',
'geetest_lot_number', 'geetest_captcha_output', 'geetest_pass_token', 'geetest_gen_time',
'aliyun_captcha_verify_param'
];
var root = (window.AKSRTCaptchaState = window.AKSRTCaptchaState || { loaders: {}, scenes: {} });
root.rescan = scan;
function scan() {
var mounts = document.querySelectorAll('[data-aksrt-captcha-config]');
Array.prototype.forEach.call(mounts, function (el) {
if (el.dataset.aksrtCaptchaBound) {
return;
}
el.dataset.aksrtCaptchaBound = '1';
var config;
try {
config = JSON.parse(el.getAttribute('data-aksrt-captcha-config'));
} catch (e) {
return;
}
if (config && config.scene && config.uid && config.vid) {
initMount(config);
}
});
}
/**
* One mount = one scene instance. Mirrors the scene semantics of the previous
* per-render inline script: the last initialized mount wins scenes[scene].
*/
function initMount(C) {
var root = window.AKSRTCaptchaState;
var box, hField, form = null;
var verified = false;
var pendingAction = null;
var triggerCaptcha = function () { showTip('验证码加载中,请稍候', '#e67e22'); };
function loadScriptOnce(key, src, readyCheck) {
if (typeof readyCheck === 'function' && readyCheck()) { return Promise.resolve(); }
if (root.loaders[key]) { return root.loaders[key]; }
root.loaders[key] = new Promise(function (resolve, reject) {
var existing = document.querySelector('script[data-aksrt-sdk="' + key + '"]');
if (existing) {
if (typeof readyCheck === 'function' && readyCheck()) { resolve(); return; }
existing.addEventListener('load', function () { resolve(); }, { once: true });
existing.addEventListener('error', function () { reject(new Error(key + ' load failed')); }, { once: true });
return;
}
var script = document.createElement('script');
script.src = src;
script.async = true;
script.setAttribute('data-aksrt-sdk', key);
script.onload = function () { resolve(); };
script.onerror = function () { reject(new Error(key + ' load failed')); };
document.head.appendChild(script);
});
return root.loaders[key];
}
function findForm() {
form = box.closest('form');
if (!form && C.scene === 'comment') form = document.getElementById('commentform');
if (!form && (C.scene === 'login' || C.scene === 'register')) {
form = box.closest('[data-auth-form]') || document.querySelector('[data-auth-form]');
}
if (!form && C.scene === 'bind_phone') {
form = document.getElementById('aksrt-bind-phone-form')
|| document.querySelector('[data-aksrt-bind-phone-form]')
|| document.querySelector('.auth-form');
}
return form;
}
function bindSubmit() {
if (!form) return;
form.addEventListener('submit', function (e) {
if (verified || hField.value === '1') return;
e.preventDefault(); e.stopImmediatePropagation();
pendingAction = null; triggerCaptcha();
}, true);
}
function setField(name, value) {
var container = form || box;
var el = container.querySelector('input[name="' + name + '"]');
if (!el) {
el = document.createElement('input');
el.type = 'hidden';
el.name = name;
container.appendChild(el);
}
el.value = value;
}
function resetVerificationState() {
verified = false;
hField.value = '0';
var container = form || box;
TOKEN_FIELDS.forEach(function (n) {
var f = container.querySelector('input[name="' + n + '"]');
if (f) f.remove();
});
if (C.scene === 'download') {
syncDownloadSiblings(false);
}
}
function syncDownloadSiblings(passed) {
var myContainer = box.closest('[data-aksrt-download-captcha]');
if (!myContainer) return;
document.querySelectorAll('[data-aksrt-download-captcha]').forEach(function (target) {
if (target === myContainer) return;
var tgtH = target.querySelector('input[name="captcha_verified"]');
if (tgtH) tgtH.value = passed ? '1' : '0';
TOKEN_FIELDS.forEach(function (name) {
var f = target.querySelector('input[name="' + name + '"]');
if (f) f.remove();
if (passed) {
var srcEl = myContainer.querySelector('input[name="' + name + '"]');
if (srcEl && srcEl.value !== '') {
var tgtEl = document.createElement('input');
tgtEl.type = 'hidden';
tgtEl.name = name;
target.appendChild(tgtEl);
tgtEl.value = srcEl.value;
}
}
});
});
}
function submitNativeForm() {
if (!form) return;
if (form.requestSubmit) { form.requestSubmit(); }
else { HTMLFormElement.prototype.submit.call(form); }
}
function submitForm() {
verified = true; hField.value = '1';
if (C.scene === 'download') syncDownloadSiblings(true);
if (typeof pendingAction === 'function') {
finishPending(true);
return;
}
setTimeout(resetVerificationState, 3000);
submitNativeForm();
}
function showTip(msg, color) {
var t = box.querySelector('.captcha-tip');
if (!t) {
t = document.createElement('div');
t.className = 'captcha-tip';
t.style.cssText = 'font-size:12px;margin-top:4px;text-align:left;';
box.appendChild(t);
}
t.style.color = color || '#e74c3c';
t.textContent = msg;
setTimeout(function () { if (t.parentNode) t.remove(); }, 4000);
}
function showLoading() { box.innerHTML = '<div style="text-align:center;padding:20px;color:#9ca3af;">验证码加载中...</div>'; }
function clearLoading() { box.innerHTML = ''; }
function finishPending(ok) {
var action = pendingAction;
pendingAction = null;
if (typeof action === 'function') { action(!!ok); }
}
function cancelPending(msg) {
if (msg) showTip(msg, '#e67e22');
finishPending(false);
}
root.scenes[C.scene] = {
verify: function (callback) {
if (verified || hField.value === '1') {
if (typeof callback === 'function') callback(true);
return;
}
pendingAction = (typeof callback === 'function') ? function (ok) { callback(ok !== false); } : null;
triggerCaptcha();
},
reset: resetVerificationState
};
// ============ 腾讯云 Captcha 2.0 ============
function loadTencent() {
showLoading();
loadScriptOnce('tencent', 'https://turing.captcha.qcloud.com/TJCaptcha.js', function () {
return typeof TencentCaptcha !== 'undefined';
}).then(function () {
clearLoading();
var capIns = null;
triggerCaptcha = function () {
if (!capIns) {
capIns = new TencentCaptcha(C.tc.app_id, function (res) {
if (res.ret === 2) { cancelPending('已取消验证'); return; }
if (res.ret === 0 && res.ticket) {
if (res.ticket.indexOf('trerror_') === 0) {
showTip('验证码服务异常,请刷新页面重试', '#e67e22');
return;
}
setField('tencent_ticket', res.ticket);
setField('tencent_randstr', res.randstr);
setField('tencent_sid', res.sid || '');
submitForm();
return;
}
if (res.errorCode) {
var errorMap = { 1001: '验证码组件加载失败', 1002: '验证码超时', 1006: '验证码配置拉取失败', 1008: '验证码页面加载异常', 1012: '验证码刷新次数过多', 1013: '验证码网络异常' };
showTip(errorMap[res.errorCode] || ('验证码异常(errorCode:' + res.errorCode + ')'), '#e74c3c');
}
}, { userLanguage: 'zh-cn' });
}
capIns.show();
};
}).catch(function () { clearLoading(); showTip('验证码组件加载失败,请刷新重试', '#e74c3c'); });
}
// ============ Cloudflare Turnstile(弹窗) ============
function loadCloudflare() {
var cfWidgetId = null, cfVerifying = false, cfModal = null;
if (typeof turnstile === 'undefined') {
window['onTurnstileLoad_' + C.uid] = function () {};
loadScriptOnce('cloudflare', 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onTurnstileLoad_' + C.uid + '&render=explicit', function () {
return typeof turnstile !== 'undefined';
});
}
function renderWidget() {
if (cfWidgetId) { try { turnstile.remove(cfWidgetId); } catch (e) {} cfWidgetId = null; }
if (typeof turnstile === 'undefined') { setTimeout(renderWidget, 200); return; }
cfWidgetId = turnstile.render('#modalWidget_' + C.uid, {
sitekey: C.cf.site_key, theme: C.cf.theme, size: C.cf.size, action: 'aksrt-verify', cdata: C.scene,
callback: function (token) {
if (!cfVerifying) return;
cfVerifying = false;
setField('cf_turnstile_response', token);
closeModal();
submitForm();
},
'error-callback': function () { showTip('验证码失败,请重试', '#e74c3c'); cfWidgetId = null; setTimeout(renderWidget, 500); },
'expired-callback': function () { showTip('验证码已过期,请重新验证', '#e67e22'); cfWidgetId = null; setTimeout(renderWidget, 500); }
});
}
function createModal() {
cfModal = document.createElement('div');
cfModal.className = 'aksrt-captcha-modal-overlay';
cfModal.innerHTML = '<div class="aksrt-captcha-modal-backdrop"></div>' +
'<div class="aksrt-captcha-modal-box"><div class="aksrt-captcha-modal-header">' +
'<span class="aksrt-captcha-modal-title">人机验证</span>' +
'<button type="button" class="aksrt-captcha-modal-close">&times;</button></div>' +
'<div class="aksrt-captcha-modal-body"><p class="aksrt-captcha-modal-hint">请完成验证后继续操作</p>' +
'<div id="modalWidget_' + C.uid + '" class="aksrt-captcha-modal-widget"></div></div></div></div>';
document.body.appendChild(cfModal);
var cancelFn = function () { cfVerifying = false; closeModal(); cancelPending('已取消验证'); };
cfModal.querySelector('.aksrt-captcha-modal-backdrop').addEventListener('click', cancelFn);
cfModal.querySelector('.aksrt-captcha-modal-close').addEventListener('click', cancelFn);
renderWidget();
}
function closeModal() {
if (cfWidgetId) { try { turnstile.remove(cfWidgetId); } catch (e) {} cfWidgetId = null; }
if (cfModal && cfModal.parentNode) { cfModal.parentNode.removeChild(cfModal); }
cfModal = null;
}
triggerCaptcha = function () {
if (cfVerifying) { showTip('验证码进行中,请稍候', '#e67e22'); return; }
cfVerifying = true;
createModal();
};
}
// ============ 极验 GeeTest v4 ============
function loadGeetest() {
showLoading();
var captchaId = (C.gt && C.gt.captcha_id) ? String(C.gt.captcha_id).trim() : '';
var product = (C.gt && C.gt.product) ? String(C.gt.product) : 'bind';
if (!captchaId) {
clearLoading();
showTip('极验 Captcha ID 未配置,请到后台「功能&权限 → 人机验证」填写并保存', '#e74c3c');
return;
}
function render() {
clearLoading();
initGeetest4({ captchaId: captchaId, product: product, hideSuccess: true }, function (capIns) {
window['__gt_' + C.uid] = capIns;
function onSuccess() {
var result = capIns.getValidate();
if (!result) return;
setField('geetest_lot_number', result.lot_number);
setField('geetest_captcha_output', result.captcha_output);
setField('geetest_pass_token', result.pass_token);
setField('geetest_gen_time', result.gen_time);
submitForm();
}
if (product === 'bind' || product === 'popup') {
capIns.onReady(function () {}).onSuccess(onSuccess).onClose(function () { cancelPending('已取消验证'); });
} else {
capIns.appendTo('#' + C.uid).onSuccess(onSuccess).onClose(function () { cancelPending('已取消验证'); });
}
});
triggerCaptcha = function () {
var instance = window['__gt_' + C.uid];
if (!instance) { showTip('验证码加载中,请稍候再试', '#e67e22'); return; }
if (product === 'bind' || product === 'popup') { instance.showCaptcha(); return; }
showTip('请先完成人机验证', '#e67e22');
};
}
if (typeof initGeetest4 === 'undefined') {
loadScriptOnce('geetest', 'https://static.geetest.com/v4/gt4.js', function () {
return typeof initGeetest4 !== 'undefined';
}).then(render).catch(function () { clearLoading(); showTip('极验组件加载失败', '#e74c3c'); });
return;
}
render();
}
// ============ 阿里云 CAPTCHA 2.0 V3 ============
function loadAliyun() {
showLoading();
window.AliyunCaptchaConfig = { region: C.al.region || 'cn', prefix: C.al.prefix };
function render() {
clearLoading();
var captchaIns = null;
var btn = box.closest('form') ? box.closest('form').querySelector('button[type="submit"], input[type="submit"]') : null;
window.initAliyunCaptcha({
SceneId: C.al.scene_id, mode: 'popup', element: '#' + C.uid,
button: btn ? '#' + (btn.id || (function () { btn.id = 'aksrt-captcha-btn-' + C.scene; return btn.id; })()) : null,
success: function (captchaVerifyParam) {
setField('aliyun_captcha_verify_param', captchaVerifyParam);
submitForm();
},
fail: function (result) { showTip('验证码失败: ' + (result || '请重试'), '#e74c3c'); captchaIns = null; },
getInstance: function (instance) { captchaIns = instance; },
slideStyle: { width: 360, height: 40 }, language: 'cn'
});
triggerCaptcha = function () {
if (captchaIns && captchaIns.show) { captchaIns.show(); return; }
showTip('验证码组件加载中,请稍候再试', '#e67e22');
};
}
if (typeof window.initAliyunCaptcha === 'undefined') {
loadScriptOnce('aliyun', 'https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js', function () {
return typeof window.initAliyunCaptcha !== 'undefined';
}).then(render).catch(function () { clearLoading(); showTip('验证码组件加载失败,请刷新重试', '#e74c3c'); });
return;
}
render();
}
function loadProvider() {
switch (C.provider) {
case 'tencent': loadTencent(); break;
case 'cloudflare': loadCloudflare(); break;
case 'geetest': loadGeetest(); break;
case 'aliyun': loadAliyun(); break;
}
}
function init() {
box = document.getElementById(C.uid);
hField = document.getElementById(C.vid);
if (!box || !hField) return;
var tries = 0;
(function retryFind() {
findForm();
if (!form && ++tries < 10) { setTimeout(retryFind, 150); }
else {
if (form) bindSubmit();
setTimeout(loadProvider, 0);
}
})();
}
init();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', scan);
} else {
setTimeout(scan, 50);
}
})();
;
/* source: assets/js/instant-page.js */
/**
* AKSRT Instant Page