slider-captcha-sdk 1.0.7 → 1.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -58
- package/dist/password-validator.min.js +1 -16
- package/dist/slider-captcha.min.js +1 -42
- package/package.json +5 -26
- package/dist/LICENSE +0 -0
- package/dist/README.md +0 -172
package/dist/index.min.js
CHANGED
|
@@ -1,58 +1 @@
|
|
|
1
|
-
(function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports,require("jsencrypt")):"function"==typeof define&&define.amd?define(["exports","jsencrypt"],i):i((t="undefined"!=typeof globalThis?globalThis:t||self).SliderCaptchaSDK={},t.JSEncrypt)})(this,function(t,i){"use strict"
|
|
2
|
-
function e(t){return new PasswordValidator(t)}async function s(t,i={},e={}){const s=new PasswordValidator(i),a=e.userName||""
|
|
3
|
-
return await s.validatePassword(t,a,e)}class PopupSliderCaptcha{static DEFAULTS={width:320,height:155,sliderSize:38,maxRetries:3,timeout:3e4,apiUrl:"/api/captcha",verifyUrl:"/api/captcha/verify",throttleDelay:16,clickMaskClose:!1}
|
|
4
|
-
static CSS_CLASSES={overlay:"slider-captcha-overlay",modal:"slider-captcha-modal",header:"slider-captcha-header",container:"slider-captcha-container",track:"slider-captcha-track",btn:"slider-captcha-btn",hint:"slider-captcha-hint",loading:"slider-captcha-loading",error:"slider-captcha-error"}
|
|
5
|
-
static getStyles(){return":root{--sc-primary:#409eff;--sc-success:#67c23a;--sc-danger:#f56c6c;--sc-border:#e4e7eb;--sc-bg:linear-gradient(90deg, #f7f9fa 0%, #e8f4fd 100%);--sc-text:#333;--sc-text-light:#999;--sc-shadow:0 4px 20px rgba(0,0,0,.3);--sc-radius:8px;--sc-transition:.3s ease}.slider-captcha-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9999;display:none;justify-content:center;align-items:center;opacity:0;transition:opacity var(--sc-transition)}.slider-captcha-overlay.show{opacity:1}.slider-captcha-modal{background:#fff;border-radius:var(--sc-radius);padding:20px;box-shadow:var(--sc-shadow);position:relative;max-width:90vw;max-height:90vh;transform:scale(.8) translateY(-20px);opacity:0;transition:all var(--sc-transition)}.slider-captcha-modal.show{transform:scale(1) translateY(0);opacity:1}.slider-captcha-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid var(--sc-border)}.slider-captcha-container{display:flex;align-items:center;position:relative;border-radius:4px;overflow:hidden;margin-bottom:15px;background:#837a7a;justify-content:center}.slider-captcha-track{width:100%;height:40px;line-height:40px;background:var(--sc-bg);border:1px solid var(--sc-border);border-radius:20px;position:relative;margin-bottom:15px;overflow:hidden}.slider-captcha-btn{width:38px;height:38px;background:#fff;border:1px solid #ccc;border-radius:50%;position:absolute;top:0;left:0;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,.1);transition:all var(--sc-transition);user-select:none;z-index:1}.slider-captcha-loading{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,.6);display:flex;align-items:center;justify-content:center;flex-direction:column;color:#666;font-size:14px;z-index:10;border-radius:4px}.slider-captcha-error{color:var(--sc-danger);font-size:12px;text-align:center;margin-top:10px;display:none}.slider-captcha-title{margin:0;font-size:16px;color:var(--sc-text)}.slider-captcha-close,.slider-captcha-refresh{background:none;border:none;cursor:pointer;color:var(--sc-text-light);padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--sc-transition);position:relative;font-size:0}.slider-captcha-close::before,.slider-captcha-close::after{content:'';position:absolute;width:16px;height:2px;background-color:var(--sc-text-light);border-radius:1px;transition:all var(--sc-transition)}.slider-captcha-close::before{transform:rotate(45deg)}.slider-captcha-close::after{transform:rotate(-45deg)}.slider-captcha-close:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-close:hover::before,.slider-captcha-close:hover::after{background-color:var(--sc-danger)}.slider-captcha-refresh{margin-left:10px}.slider-captcha-refresh svg{width:20px;height:20px;fill:var(--sc-text-light);transition:all var(--sc-transition)}.slider-captcha-refresh:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-refresh:hover svg{fill:var(--sc-primary);transform:rotate(180deg)}.slider-captcha-floating-time{position:absolute;bottom:-40px;left:50%;transform:translateX(-50%);color:#fff;font-size:12px;white-space:nowrap;opacity:0;pointer-events:none;z-index:10;transition:all var(--sc-transition);background:#fff;padding:2px 15px;border-radius:10px}.slider-captcha-floating-time.show{opacity:1;transform:translateX(-50%) translateY(-45px)}.slider-captcha-floating-time.success{color:var(--sc-success)}.slider-captcha-floating-time.fail{color:var(--sc-danger)}.slider-captcha-bg{width:100%;height:100%;object-fit:cover;display:block}.slider-captcha-piece{position:absolute;top:0;left:0;cursor:pointer;transition:none;z-index:2}.slider-captcha-finger{position:absolute;top:50%;left:10px;transform:translateY(-50%);font-size:20px;animation:fingerSlide 2s ease-in-out infinite;pointer-events:none;z-index:1;opacity:.6}.slider-captcha-hint{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:var(--sc-text-light);font-size:14px;pointer-events:none;z-index:1;transition:all var(--sc-transition)}.slider-captcha-header-buttons{display:flex;align-items:center}@keyframes fingerSlide{0%{left:10px;opacity:.6}50%{opacity:1}100%{left:calc(50% - 10px);opacity:.6}}"}constructor(t={}){this.options={...PopupSliderCaptcha.DEFAULTS,...t},this.elements={},this.state=this.createInitialState(),this.captchaData=null,this.times=[],this.startTime=null,this.eventListeners=[],this.timers=new Set,this.rafId=null,this.cachedDimensions=null,this.imageCache=new Map,this.throttledHandleMove=this.throttle(t=>this.handleMove(t),this.options.throttleDelay),this.init()}createInitialState(){return{isVisible:!1,isDragging:!1,currentX:0,startX:0,retryCount:0,isLoading:!1}}init(){this.injectStyles(),this.createElements(),this.bindEvents()}injectStyles(){if(document.querySelector("#slider-captcha-styles"))return
|
|
6
|
-
const t=document.createElement("style")
|
|
7
|
-
t.id="slider-captcha-styles",t.textContent=PopupSliderCaptcha.getStyles(),document.head.appendChild(t)}createElements(){const{elements:t,options:i}=this;[["overlay","div",PopupSliderCaptcha.CSS_CLASSES.overlay],["modal","div",PopupSliderCaptcha.CSS_CLASSES.modal],["header","div",PopupSliderCaptcha.CSS_CLASSES.header],["title","h3","slider-captcha-title","安全验证"],["closeBtn","button","slider-captcha-close"],["refreshBtn","button","slider-captcha-refresh"],["container","div",PopupSliderCaptcha.CSS_CLASSES.container],["backgroundImg","img","slider-captcha-bg"],["sliderImg","img","slider-captcha-piece"],["loadingText","div",PopupSliderCaptcha.CSS_CLASSES.loading,"加载中..."],["floatingTime","div","slider-captcha-floating-time"],["track","div",PopupSliderCaptcha.CSS_CLASSES.track],["fingerAnimation","div","slider-captcha-finger","👉"],["btn","div",PopupSliderCaptcha.CSS_CLASSES.btn],["icon","div","","→"],["hint","div",PopupSliderCaptcha.CSS_CLASSES.hint,"向右滑动完成验证"],["error","div",PopupSliderCaptcha.CSS_CLASSES.error]].forEach(([i,e,s,a])=>{t[i]=this.createElement(e,s,a)}),t.container.style.cssText=`width:${i.width}px;height:${i.height}px`,t.refreshBtn.innerHTML='<svg viewBox="0 0 24 24"><path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z"/></svg>',this.assembleDOM(),this.setInitialState()}createElement(t,i="",e=""){const s=document.createElement(t)
|
|
8
|
-
return i&&(s.className=i),e&&(s.textContent=e),s}assembleDOM(){const{elements:t}=this,i=this.createElement("div","slider-captcha-header-buttons")
|
|
9
|
-
i.append(t.refreshBtn,t.closeBtn),t.header.append(t.title,i),t.container.append(t.backgroundImg,t.sliderImg,t.loadingText,t.floatingTime),t.btn.appendChild(t.icon),t.track.append(t.fingerAnimation,t.btn,t.hint),t.modal.append(t.header,t.container,t.track,t.error),t.overlay.appendChild(t.modal),document.body.appendChild(t.overlay)}setInitialState(){Object.assign(this.elements.container.style,{display:"none"}),Object.assign(this.elements.track.style,{display:"none"})}bindEvents(){const{elements:t}=this
|
|
10
|
-
this.addEventListener(t.closeBtn,"click",()=>this.hide()),this.addEventListener(t.refreshBtn,"click",()=>this.refresh()),this.addEventListener(t.overlay,"click",i=>{i.target===t.overlay&&this.options.clickMaskClose&&this.hide()}),this.addEventListener(document,"keydown",t=>{"Escape"===t.key&&this.state.isVisible&&this.hide()}),this.addEventListener(document,"visibilitychange",()=>this.handleVisibilityChange()),this.bindSliderEvents()}bindSliderEvents(){const{elements:t}=this,i={start:t=>this.handleStart(t),move:this.throttledHandleMove,end:()=>this.handleEnd()}
|
|
11
|
-
this.addEventListener(t.btn,"mousedown",i.start),this.addEventListener(t.btn,"touchstart",i.start),this.addEventListener(t.sliderImg,"mousedown",i.start),this.addEventListener(t.sliderImg,"touchstart",i.start),this.addEventListener(document,"mousemove",i.move,{passive:!1}),this.addEventListener(document,"touchmove",i.move,{passive:!1}),this.addEventListener(document,"mouseup",i.end),this.addEventListener(document,"touchend",i.end)}addEventListener(t,i,e,s={}){t&&"function"==typeof e&&(t.addEventListener(i,e,s),this.eventListeners.push({element:t,event:i,handler:e,options:s}))}removeAllEventListeners(){this.eventListeners.forEach(({element:t,event:i,handler:e,options:s})=>{try{t?.removeEventListener?.(i,e,s)}catch(t){}}),this.eventListeners.length=0}getDimensions(){if(!this.cachedDimensions){const t=this.elements.track.offsetWidth,i=this.elements.btn.offsetWidth
|
|
12
|
-
this.cachedDimensions={trackWidth:t,btnWidth:i,maxX:t-i}}return this.cachedDimensions}getPosition(){const{maxX:t}=this.getDimensions(),i=this.state.currentX/t
|
|
13
|
-
return Math.round(i*(this.options.width-this.options.sliderSize))}handleStart(t){!this.captchaData||this.state.isDragging||this.state.isLoading||(t.preventDefault(),this.state.isDragging=!0,this.state.startX=this.getClientX(t)-this.state.currentX,this.startTime=this.startTime||Date.now(),this.times=[{time:Date.now(),position:this.getPosition()}],this.setTransition(!1),this.updateUIState("dragging"),this.cachedDimensions=null)}handleMove(t){if(!this.state.isDragging)return
|
|
14
|
-
t.preventDefault()
|
|
15
|
-
const i=this.getClientX(t)-this.state.startX,{maxX:e}=this.getDimensions()
|
|
16
|
-
this.state.currentX=Math.max(0,Math.min(i,e)),this.times.push({time:Date.now(),position:this.getPosition()}),this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>this.updateSliderPosition())}handleEnd(){this.state.isDragging&&(this.times.push({time:Date.now(),position:this.getPosition()}),this.state.isDragging=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.verify())}handleVisibilityChange(){const t=document.hidden?"paused":"running"
|
|
17
|
-
this.elements.fingerAnimation&&(this.elements.fingerAnimation.style.animationPlayState=t)}getClientX(t){return t.type.includes("touch")?t.touches[0].clientX:t.clientX}setTransition(t){const i=t?"all 0.3s ease":"none"
|
|
18
|
-
requestAnimationFrame(()=>{this.elements.btn.style.transition=i,this.elements.sliderImg.style.transition=i})}updateUIState(t){const{elements:i}=this,e={dragging:()=>{i.hint.style.opacity="0",i.fingerAnimation.style.display="none"},success:()=>{Object.assign(i.btn.style,{background:"var(--sc-success)"}),Object.assign(i.icon.style,{innerHTML:"✓",color:"white"}),i.icon.innerHTML="✓"},fail:()=>{Object.assign(i.btn.style,{background:"var(--sc-danger)"}),Object.assign(i.icon.style,{innerHTML:"✗",color:"white"}),i.icon.innerHTML="✗"},reset:()=>{Object.assign(i.btn.style,{background:"white"}),Object.assign(i.icon.style,{color:"#666"}),i.icon.innerHTML="→",i.fingerAnimation.style.display="block",this.updateHintText("向右滑动完成验证","var(--sc-text-light)")},loading:()=>{i.hint.style.opacity="0",i.fingerAnimation.style.display="none",Object.assign(i.track.style,{pointerEvents:"none",opacity:"0.6"})}}
|
|
19
|
-
e[t]&&requestAnimationFrame(()=>{e[t](),"loading"!==t&&Object.assign(i.track.style,{pointerEvents:"auto",opacity:"1"})})}updateHintText(t,i){requestAnimationFrame(()=>{Object.assign(this.elements.hint,{textContent:t}),Object.assign(this.elements.hint.style,{color:i,opacity:"1"})})}updateSliderPosition(){const{elements:t,options:i,state:e}=this,{maxX:s}=this.getDimensions(),a=e.currentX/s*(i.width-i.sliderSize),r=e.currentX/s
|
|
20
|
-
requestAnimationFrame(()=>{t.btn.style.transform=`translateX(${e.currentX}px)`,t.sliderImg.style.transform=`translateX(${a}px)`,t.fingerAnimation.style.opacity=.8>r?"0.6":"0"})}show(){this.state.isVisible=!0,this.elements.overlay.style.display="flex",this.elements.overlay.offsetHeight,requestAnimationFrame(()=>{this.elements.overlay.classList.add("show"),this.elements.modal.classList.add("show")}),this.loadCaptcha()}hide(){this.state.isVisible=!1,this.elements.overlay.classList.remove("show"),this.elements.modal.classList.remove("show"),this.safeSetTimeout(()=>{this.elements.overlay.style.display="none",document.body.removeChild(this.elements.overlay),this.reset(),this.options.onClose?.(),this.elements.overlay=null},300)}async loadCaptcha(){try{this.showLoading(),this.startTime=Date.now()
|
|
21
|
-
const t=new AbortController,i=this.safeSetTimeout(()=>t.abort(),this.options.timeout),e=await fetch(this.options.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({place:2,timestamp:Date.now()}),signal:t.signal})
|
|
22
|
-
if(this.safeClearTimeout(i),!e.ok)throw Error("HTTP "+e.status)
|
|
23
|
-
const s=await e.json()
|
|
24
|
-
if(!s.data?.canvasSrc||!s.data?.blockSrc)throw Error("验证码数据格式错误")
|
|
25
|
-
this.captchaData=s.data,this.showCaptcha(),await this.renderCaptcha()}catch(t){const i="AbortError"===t.name?"请求超时,请重试":"加载验证码失败: "+t.message
|
|
26
|
-
this.showError(i)}}async renderCaptcha(){return new Promise((t,i)=>{let e=0
|
|
27
|
-
const s=()=>2===++e&&(this.hideLoading(),t()),a=()=>i(Error("图片加载失败"))
|
|
28
|
-
this.loadImage(this.elements.backgroundImg,this.captchaData.canvasSrc,{width:this.captchaData.canvasWidth,height:this.captchaData.canvasHeight},s,a),this.loadImage(this.elements.sliderImg,this.captchaData.blockSrc,{width:this.captchaData.blockWidth,height:this.captchaData.blockHeight,top:this.captchaData.blockY},s,a)})}loadImage(t,i,e,s,a){if(this.imageCache.has(i)){const a=this.imageCache.get(i)
|
|
29
|
-
return t.src=a.src,this.applyStyles(t,e),void s()}t.onload=()=>{this.imageCache.set(i,t.cloneNode()),s()},t.onerror=a,t.src=i,this.applyStyles(t,e)}applyStyles(t,i){Object.entries(i).forEach(([i,e])=>{t.style[i]="number"==typeof e?e+"px":e})}showLoading(){this.state.isLoading=!0,this.batchUpdateStyles({container:{display:"block"},loadingText:{display:"flex"},error:{display:"none"}}),this.updateUIState("loading")}hideLoading(){this.state.isLoading=!1,this.batchUpdateStyles({loadingText:{display:"none"}}),this.updateUIState("reset")}showCaptcha(){this.batchUpdateStyles({container:{display:"block"},track:{display:"block"},error:{display:"none"}})}showError(t){this.hideLoading(),this.batchUpdateStyles({error:{display:"block",textContent:t}})}batchUpdateStyles(t){requestAnimationFrame(()=>{Object.entries(t).forEach(([t,i])=>{const e=this.elements[t]
|
|
30
|
-
e&&Object.entries(i).forEach(([t,i])=>{"textContent"===t?e.textContent=i:e.style[t]=i})})})}async verify(){if(this.captchaData)try{const t=new AbortController,i=this.safeSetTimeout(()=>t.abort(),this.options.timeout),e=await fetch(this.options.verifyUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({loginVo:{nonceStr:this.captchaData.nonceStr,value:this.getPosition()},dragEventList:[...this.times]}),signal:t.signal})
|
|
31
|
-
if(this.safeClearTimeout(i),!e.ok)throw Error("HTTP "+e.status)
|
|
32
|
-
const s=await e.json()
|
|
33
|
-
"0"===s.code||!0===s.success?this.onVerifySuccess():this.onVerifyFail(s.message||"验证失败,请重试!")}catch(t){const i="AbortError"===t.name?"验证超时,请重试":"网络错误"
|
|
34
|
-
this.onVerifyFail(i)}else this.onVerifyFail("验证码数据丢失")}onVerifySuccess(){const t=Date.now()-this.startTime,i=`验证成功!耗时:${(t/1e3).toFixed(2)}s`
|
|
35
|
-
this.updateUIState("success"),this.showFloatingTime(i,"success"),this.safeSetTimeout(()=>{this.options.onSuccess?.({captchaId:this.captchaData.captchaId,timestamp:Date.now(),duration:t}),this.hide()},2e3)}showFloatingTime(t,i="success"){const{elements:e}=this
|
|
36
|
-
e.floatingTime.textContent=t,e.floatingTime.className="slider-captcha-floating-time "+i,this.safeSetTimeout(()=>e.floatingTime.classList.add("show"),100),this.safeSetTimeout(()=>{e.floatingTime.className="slider-captcha-floating-time"},2500)}onVerifyFail(t){this.state.retryCount++,this.updateUIState("fail"),this.showFloatingTime(t,"fail"),this.safeSetTimeout(()=>{this.state.retryCount<this.options.maxRetries?this.reset():this.refresh()},2500)}reset(){this.clearAllTimers(),Object.assign(this.state,{isDragging:!1,currentX:0,startX:0,isLoading:!1}),this.times=[],this.startTime=null,this.cachedDimensions=null,requestAnimationFrame(()=>{this.setTransition(!0),this.elements.btn.style.transform="translateX(0px)",this.elements.sliderImg.style.transform="translateX(0px)",this.updateUIState("reset"),this.elements.error.style.display="none"})}refresh(){this.reset(),this.state.retryCount=0,this.loadCaptcha()}safeSetTimeout(t,i){const e=setTimeout(()=>{this.timers.delete(e),t()},i)
|
|
37
|
-
return this.timers.add(e),e}safeClearTimeout(t){t&&(clearTimeout(t),this.timers.delete(t))}clearAllTimers(){this.timers.forEach(t=>{clearTimeout(t),clearInterval(t)}),this.timers.clear(),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}cleanupImages(){this.elements.backgroundImg&&(this.elements.backgroundImg.src="",this.elements.backgroundImg.onload=null,this.elements.backgroundImg.onerror=null),this.elements.sliderImg&&(this.elements.sliderImg.src="",this.elements.sliderImg.onload=null,this.elements.sliderImg.onerror=null),this.imageCache.clear()}throttle(t,i){let e=0
|
|
38
|
-
return function(...s){const a=Date.now()
|
|
39
|
-
if(a-e>=i)return e=a,t.apply(this,s)}}debounce(t,i){let e
|
|
40
|
-
return function(...s){clearTimeout(e),e=setTimeout(()=>t.apply(this,s),i)}}destroy(){document.body.style.userSelect="",document.body.style.cursor="",this.clearAllTimers(),this.removeAllEventListeners(),this.cleanupImages(),this.elements.overlay?.parentNode&&this.elements.overlay.parentNode.removeChild(this.elements.overlay)
|
|
41
|
-
const t=document.getElementById("slider-captcha-styles")
|
|
42
|
-
t&&t.remove(),Object.keys(this).forEach(t=>{"constructor"!==t&&(this[t]=null)})}static create(t){return new PopupSliderCaptcha(t)}static show(t){const i=new PopupSliderCaptcha(t)
|
|
43
|
-
return i.show(),i}}"undefined"!=typeof module&&module.exports?(module.exports=PopupSliderCaptcha,module.exports.default=PopupSliderCaptcha):"function"==typeof define&&define.amd?define([],()=>PopupSliderCaptcha):"undefined"!=typeof window&&(window.PopupSliderCaptcha=PopupSliderCaptcha,window.SliderCaptcha=PopupSliderCaptcha)
|
|
44
|
-
class PasswordValidator{constructor(t={}){this.options={publicKeyUrl:t.publicKeyUrl||"/microservice/strongPassword/getPublicKey",validateUrl:t.validateUrl||"/microservice/strongPassword/checkPassword",timeout:t.timeout||1e4,headers:t.headers||{},...t},this.publicKeyCache=null,this.publicKeyExpiry=null}async getPublicKey(){if(this.publicKeyCache&&this.publicKeyExpiry&&Date.now()<this.publicKeyExpiry)return this.publicKeyCache
|
|
45
|
-
try{const t=await this.makeRequest(this.options.publicKeyUrl,{method:"GET"})
|
|
46
|
-
if("0"!==t.code)throw Error("获取公钥失败:"+(t.message||"未知错误"))
|
|
47
|
-
return this.publicKeyCache=t.data,this.publicKeyExpiry=Date.now()+3e5,this.publicKeyCache}catch(t){throw Error("获取公钥失败: "+t.message)}}encryptPassword(t,e){try{if(!i)throw Error("JSEncrypt库未正确加载")
|
|
48
|
-
const s=new i
|
|
49
|
-
s.setPublicKey(e)
|
|
50
|
-
const a=s.encrypt(t)
|
|
51
|
-
if(!a)throw Error("密码加密失败")
|
|
52
|
-
return a}catch(t){throw Error("密码加密失败: "+t.message)}}async validatePassword(t,i,e={}){try{const s=await this.getPublicKey(),a=this.encryptPassword(t,s),r=await this.makeRequest(this.options.validateUrl,{method:"POST",body:JSON.stringify({userName:i,password:a,timestamp:Date.now(),...e})})
|
|
53
|
-
return{success:r.success,message:r.message,data:r.data,code:r.code}}catch(t){return{success:!1,message:t.message,code:"VALIDATION_ERROR"}}}async makeRequest(t,i={}){const e=new AbortController,s=setTimeout(()=>e.abort(),this.options.timeout)
|
|
54
|
-
try{const a=await fetch(t,{...i,headers:{"Content-Type":"application/json",...this.options.headers,...i.headers},signal:e.signal})
|
|
55
|
-
if(clearTimeout(s),!a.ok)throw Error(`HTTP错误: ${a.status} ${a.statusText}`)
|
|
56
|
-
return await a.json()}catch(t){if(clearTimeout(s),"AbortError"===t.name)throw Error("请求超时")
|
|
57
|
-
throw t}}clearCache(){this.publicKeyCache=null,this.publicKeyExpiry=null}updateOptions(t){this.options={...this.options,...t},this.clearCache()}}var a={PopupSliderCaptcha:PopupSliderCaptcha,PasswordValidator:PasswordValidator,createPasswordValidator:e,validatePassword:s}
|
|
58
|
-
"undefined"!=typeof window&&(window.SliderCaptcha=PopupSliderCaptcha,window.PopupSliderCaptcha=PopupSliderCaptcha,window.PasswordValidator=PasswordValidator,window.createPasswordValidator=e,window.validatePassword=s),t.PasswordValidator=PasswordValidator,t.PopupSliderCaptcha=PopupSliderCaptcha,t.createPasswordValidator=e,t.default=a,t.validatePassword=s,Object.defineProperty(t,"t",{value:!0})})
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("jsencrypt")):"function"==typeof define&&define.amd?define(["exports","jsencrypt"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).SliderCaptchaSDK={},t.JSEncrypt)}(this,function(t,e){"use strict";function i(t){return new PasswordValidator(t)}async function s(t,e={},i={}){const s=new PasswordValidator(e),a=i.userName||"";return await s.validatePassword(t,a,i)}class PopupSliderCaptcha{static DEFAULTS={width:320,height:155,sliderSize:38,maxRetries:3,timeout:3e4,apiUrl:"/api/captcha",verifyUrl:"/api/captcha/verify",throttleDelay:16,clickMaskClose:!1};static CSS_CLASSES={overlay:"slider-captcha-overlay",modal:"slider-captcha-modal",header:"slider-captcha-header",container:"slider-captcha-container",track:"slider-captcha-track",btn:"slider-captcha-btn",hint:"slider-captcha-hint",loading:"slider-captcha-loading",error:"slider-captcha-error"};static getStyles(){return":root{--sc-primary:#409eff;--sc-success:#67c23a;--sc-danger:#f56c6c;--sc-border:#e4e7eb;--sc-bg:linear-gradient(90deg, #f7f9fa 0%, #e8f4fd 100%);--sc-text:#333;--sc-text-light:#999;--sc-shadow:0 4px 20px rgba(0,0,0,.3);--sc-radius:8px;--sc-transition:.3s ease}.slider-captcha-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9999;display:none;justify-content:center;align-items:center;opacity:0;transition:opacity var(--sc-transition)}.slider-captcha-overlay.show{opacity:1}.slider-captcha-modal{background:#fff;border-radius:var(--sc-radius);padding:20px;box-shadow:var(--sc-shadow);position:relative;max-width:90vw;max-height:90vh;transform:scale(.8) translateY(-20px);opacity:0;transition:all var(--sc-transition)}.slider-captcha-modal.show{transform:scale(1) translateY(0);opacity:1}.slider-captcha-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid var(--sc-border)}.slider-captcha-container{display:flex;align-items:center;position:relative;border-radius:4px;overflow:hidden;margin-bottom:15px;background:#837a7a;justify-content:center}.slider-captcha-track{width:100%;height:40px;line-height:40px;background:var(--sc-bg);border:1px solid var(--sc-border);border-radius:20px;position:relative;margin-bottom:15px;overflow:hidden}.slider-captcha-btn{width:38px;height:38px;background:#fff;border:1px solid #ccc;border-radius:50%;position:absolute;top:0;left:0;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,.1);transition:all var(--sc-transition);user-select:none;z-index:1}.slider-captcha-loading{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,.6);display:flex;align-items:center;justify-content:center;flex-direction:column;color:#666;font-size:14px;z-index:10;border-radius:4px}.slider-captcha-error{color:var(--sc-danger);font-size:12px;text-align:center;margin-top:10px;display:none}.slider-captcha-title{margin:0;font-size:16px;color:var(--sc-text)}.slider-captcha-close,.slider-captcha-refresh{background:none;border:none;cursor:pointer;color:var(--sc-text-light);padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--sc-transition);position:relative;font-size:0}.slider-captcha-close::before,.slider-captcha-close::after{content:'';position:absolute;width:16px;height:2px;background-color:var(--sc-text-light);border-radius:1px;transition:all var(--sc-transition)}.slider-captcha-close::before{transform:rotate(45deg)}.slider-captcha-close::after{transform:rotate(-45deg)}.slider-captcha-close:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-close:hover::before,.slider-captcha-close:hover::after{background-color:var(--sc-danger)}.slider-captcha-refresh{margin-left:10px}.slider-captcha-refresh svg{width:20px;height:20px;fill:var(--sc-text-light);transition:all var(--sc-transition)}.slider-captcha-refresh:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-refresh:hover svg{fill:var(--sc-primary);transform:rotate(180deg)}.slider-captcha-floating-time{position:absolute;bottom:-40px;left:50%;transform:translateX(-50%);color:#fff;font-size:12px;white-space:nowrap;opacity:0;pointer-events:none;z-index:10;transition:all var(--sc-transition);background:#fff;padding:2px 15px;border-radius:10px}.slider-captcha-floating-time.show{opacity:1;transform:translateX(-50%) translateY(-45px)}.slider-captcha-floating-time.success{color:var(--sc-success)}.slider-captcha-floating-time.fail{color:var(--sc-danger)}.slider-captcha-bg{width:100%;height:100%;object-fit:cover;display:block}.slider-captcha-piece{position:absolute;top:0;left:0;cursor:pointer;transition:none;z-index:2}.slider-captcha-finger{position:absolute;top:50%;left:10px;transform:translateY(-50%);font-size:20px;animation:fingerSlide 2s ease-in-out infinite;pointer-events:none;z-index:1;opacity:.6}.slider-captcha-hint{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:var(--sc-text-light);font-size:14px;pointer-events:none;z-index:1;transition:all var(--sc-transition)}.slider-captcha-header-buttons{display:flex;align-items:center}@keyframes fingerSlide{0%{left:10px;opacity:.6}50%{opacity:1}100%{left:calc(50% - 10px);opacity:.6}}"}constructor(t={}){this.options={...PopupSliderCaptcha.DEFAULTS,...t},this.elements={},this.state=this.createInitialState(),this.captchaData=null,this.times=[],this.startTime=null,this.eventListeners=[],this.timers=new Set,this.rafId=null,this.cachedDimensions=null,this.imageCache=new Map,this.throttledHandleMove=this.throttle(t=>this.handleMove(t),this.options.throttleDelay),this.init()}createInitialState(){return{isVisible:!1,isDragging:!1,currentX:0,startX:0,retryCount:0,isLoading:!1}}init(){this.injectStyles(),this.createElements(),this.bindEvents()}injectStyles(){if(document.querySelector("#slider-captcha-styles"))return;const t=document.createElement("style");t.id="slider-captcha-styles",t.textContent=PopupSliderCaptcha.getStyles(),document.head.appendChild(t)}createElements(){const{elements:t,options:e}=this;[["overlay","div",PopupSliderCaptcha.CSS_CLASSES.overlay],["modal","div",PopupSliderCaptcha.CSS_CLASSES.modal],["header","div",PopupSliderCaptcha.CSS_CLASSES.header],["title","h3","slider-captcha-title","安全验证"],["closeBtn","button","slider-captcha-close"],["refreshBtn","button","slider-captcha-refresh"],["container","div",PopupSliderCaptcha.CSS_CLASSES.container],["backgroundImg","img","slider-captcha-bg"],["sliderImg","img","slider-captcha-piece"],["loadingText","div",PopupSliderCaptcha.CSS_CLASSES.loading,"加载中..."],["floatingTime","div","slider-captcha-floating-time"],["track","div",PopupSliderCaptcha.CSS_CLASSES.track],["fingerAnimation","div","slider-captcha-finger","👉"],["btn","div",PopupSliderCaptcha.CSS_CLASSES.btn],["icon","div","","→"],["hint","div",PopupSliderCaptcha.CSS_CLASSES.hint,"向右滑动完成验证"],["error","div",PopupSliderCaptcha.CSS_CLASSES.error]].forEach(([e,i,s,a])=>{t[e]=this.createElement(i,s,a)}),t.container.style.cssText=`width:${e.width}px;height:${e.height}px`,t.refreshBtn.innerHTML='<svg viewBox="0 0 24 24"><path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z"/></svg>',this.assembleDOM(),this.setInitialState()}createElement(t,e="",i=""){const s=document.createElement(t);return e&&(s.className=e),i&&(s.textContent=i),s}assembleDOM(){const{elements:t}=this,e=this.createElement("div","slider-captcha-header-buttons");e.append(t.refreshBtn,t.closeBtn),t.header.append(t.title,e),t.container.append(t.backgroundImg,t.sliderImg,t.loadingText,t.floatingTime),t.btn.appendChild(t.icon),t.track.append(t.fingerAnimation,t.btn,t.hint),t.modal.append(t.header,t.container,t.track,t.error),t.overlay.appendChild(t.modal),document.body.appendChild(t.overlay)}setInitialState(){Object.assign(this.elements.container.style,{display:"none"}),Object.assign(this.elements.track.style,{display:"none"})}bindEvents(){const{elements:t}=this;this.addEventListener(t.closeBtn,"click",()=>this.hide()),this.addEventListener(t.refreshBtn,"click",()=>this.refresh()),this.addEventListener(t.overlay,"click",e=>{e.target===t.overlay&&this.options.clickMaskClose&&this.hide()}),this.addEventListener(document,"keydown",t=>{"Escape"===t.key&&this.state.isVisible&&this.hide()}),this.addEventListener(document,"visibilitychange",()=>this.handleVisibilityChange()),this.bindSliderEvents()}bindSliderEvents(){const{elements:t}=this,e={start:t=>this.handleStart(t),move:this.throttledHandleMove,end:()=>this.handleEnd()};this.addEventListener(t.btn,"mousedown",e.start),this.addEventListener(t.btn,"touchstart",e.start),this.addEventListener(t.sliderImg,"mousedown",e.start),this.addEventListener(t.sliderImg,"touchstart",e.start),this.addEventListener(document,"mousemove",e.move,{passive:!1}),this.addEventListener(document,"touchmove",e.move,{passive:!1}),this.addEventListener(document,"mouseup",e.end),this.addEventListener(document,"touchend",e.end)}addEventListener(t,e,i,s={}){t&&"function"==typeof i&&(t.addEventListener(e,i,s),this.eventListeners.push({element:t,event:e,handler:i,options:s}))}removeAllEventListeners(){this.eventListeners.forEach(({element:t,event:e,handler:i,options:s})=>{try{t?.removeEventListener?.(e,i,s)}catch(t){}}),this.eventListeners.length=0}getDimensions(){if(!this.cachedDimensions){const t=this.elements.track.offsetWidth,e=this.elements.btn.offsetWidth;this.cachedDimensions={trackWidth:t,btnWidth:e,maxX:t-e}}return this.cachedDimensions}getPosition(){const{maxX:t}=this.getDimensions(),e=this.state.currentX/t;return Math.round(e*(this.options.width-this.options.sliderSize))}handleStart(t){!this.captchaData||this.state.isDragging||this.state.isLoading||(t.preventDefault(),this.state.isDragging=!0,this.state.startX=this.getClientX(t)-this.state.currentX,this.startTime=this.startTime||Date.now(),this.times=[{time:Date.now(),position:this.getPosition()}],this.setTransition(!1),this.updateUIState("dragging"),this.cachedDimensions=null)}handleMove(t){if(!this.state.isDragging)return;t.preventDefault();const e=this.getClientX(t)-this.state.startX,{maxX:i}=this.getDimensions();this.state.currentX=Math.max(0,Math.min(e,i)),this.times.push({time:Date.now(),position:this.getPosition()}),this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>this.updateSliderPosition())}handleEnd(){this.state.isDragging&&(this.times.push({time:Date.now(),position:this.getPosition()}),this.state.isDragging=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.verify())}handleVisibilityChange(){const t=document.hidden?"paused":"running";this.elements.fingerAnimation&&(this.elements.fingerAnimation.style.animationPlayState=t)}getClientX(t){return t.type.includes("touch")?t.touches[0].clientX:t.clientX}setTransition(t){const e=t?"all 0.3s ease":"none";requestAnimationFrame(()=>{this.elements.btn.style.transition=e,this.elements.sliderImg.style.transition=e})}updateUIState(t){const{elements:e}=this,i={dragging:()=>{e.hint.style.opacity="0",e.fingerAnimation.style.display="none"},success:()=>{Object.assign(e.btn.style,{background:"var(--sc-success)"}),Object.assign(e.icon.style,{innerHTML:"✓",color:"white"}),e.icon.innerHTML="✓"},fail:()=>{Object.assign(e.btn.style,{background:"var(--sc-danger)"}),Object.assign(e.icon.style,{innerHTML:"✗",color:"white"}),e.icon.innerHTML="✗"},reset:()=>{Object.assign(e.btn.style,{background:"white"}),Object.assign(e.icon.style,{color:"#666"}),e.icon.innerHTML="→",e.fingerAnimation.style.display="block",this.updateHintText("向右滑动完成验证","var(--sc-text-light)")},loading:()=>{e.hint.style.opacity="0",e.fingerAnimation.style.display="none",Object.assign(e.track.style,{pointerEvents:"none",opacity:"0.6"})}};i[t]&&requestAnimationFrame(()=>{i[t](),"loading"!==t&&Object.assign(e.track.style,{pointerEvents:"auto",opacity:"1"})})}updateHintText(t,e){requestAnimationFrame(()=>{Object.assign(this.elements.hint,{textContent:t}),Object.assign(this.elements.hint.style,{color:e,opacity:"1"})})}updateSliderPosition(){const{elements:t,options:e,state:i}=this,{maxX:s}=this.getDimensions(),a=i.currentX/s*(e.width-e.sliderSize),n=i.currentX/s;requestAnimationFrame(()=>{t.btn.style.transform=`translateX(${i.currentX}px)`,t.sliderImg.style.transform=`translateX(${a}px)`,t.fingerAnimation.style.opacity=.8>n?"0.6":"0"})}show(){this.state.isVisible=!0,this.elements.overlay.style.display="flex",this.elements.overlay.offsetHeight,requestAnimationFrame(()=>{this.elements.overlay.classList.add("show"),this.elements.modal.classList.add("show")}),this.loadCaptcha()}hide(){this.state.isVisible=!1,this.elements.overlay.classList.remove("show"),this.elements.modal.classList.remove("show"),this.safeSetTimeout(()=>{this.elements.overlay.style.display="none",document.body.removeChild(this.elements.overlay),this.reset(),this.options.onClose?.(),this.elements.overlay=null},300)}async loadCaptcha(){try{this.showLoading(),this.startTime=Date.now();const t=new AbortController,e=this.safeSetTimeout(()=>t.abort(),this.options.timeout),i=await fetch(this.options.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({place:2,timestamp:Date.now()}),signal:t.signal});if(this.safeClearTimeout(e),!i.ok)throw Error("HTTP "+i.status);const s=await i.json();if(!s.data?.canvasSrc||!s.data?.blockSrc)throw Error("验证码数据格式错误");this.captchaData=s.data,this.showCaptcha(),await this.renderCaptcha()}catch(t){const e="AbortError"===t.name?"请求超时,请重试":"加载验证码失败: "+t.message;this.showError(e)}}async renderCaptcha(){return new Promise((t,e)=>{let i=0;const s=()=>2===++i&&(this.hideLoading(),t()),a=()=>e(Error("图片加载失败"));this.loadImage(this.elements.backgroundImg,this.captchaData.canvasSrc,{width:this.captchaData.canvasWidth,height:this.captchaData.canvasHeight},s,a),this.loadImage(this.elements.sliderImg,this.captchaData.blockSrc,{width:this.captchaData.blockWidth,height:this.captchaData.blockHeight,top:this.captchaData.blockY},s,a)})}loadImage(t,e,i,s,a){if(this.imageCache.has(e)){const a=this.imageCache.get(e);return t.src=a.src,this.applyStyles(t,i),void s()}t.onload=()=>{this.imageCache.set(e,t.cloneNode()),s()},t.onerror=a,t.src=e,this.applyStyles(t,i)}applyStyles(t,e){Object.entries(e).forEach(([e,i])=>{t.style[e]="number"==typeof i?i+"px":i})}showLoading(){this.state.isLoading=!0,this.batchUpdateStyles({container:{display:"block"},loadingText:{display:"flex"},error:{display:"none"}}),this.updateUIState("loading")}hideLoading(){this.state.isLoading=!1,this.batchUpdateStyles({loadingText:{display:"none"}}),this.updateUIState("reset")}showCaptcha(){this.batchUpdateStyles({container:{display:"block"},track:{display:"block"},error:{display:"none"}})}showError(t){this.hideLoading(),this.batchUpdateStyles({error:{display:"block",textContent:t}})}batchUpdateStyles(t){requestAnimationFrame(()=>{Object.entries(t).forEach(([t,e])=>{const i=this.elements[t];i&&Object.entries(e).forEach(([t,e])=>{"textContent"===t?i.textContent=e:i.style[t]=e})})})}async verify(){if(this.captchaData)try{const t=new AbortController,e=this.safeSetTimeout(()=>t.abort(),this.options.timeout),i=await fetch(this.options.verifyUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({loginVo:{nonceStr:this.captchaData.nonceStr,value:this.getPosition()},dragEventList:[...this.times]}),signal:t.signal});if(this.safeClearTimeout(e),!i.ok)throw Error("HTTP "+i.status);const s=await i.json();"0"===s.code||!0===s.success?this.onVerifySuccess():this.onVerifyFail(s.message||"验证失败,请重试!")}catch(t){const e="AbortError"===t.name?"验证超时,请重试":"网络错误";this.onVerifyFail(e)}else this.onVerifyFail("验证码数据丢失")}onVerifySuccess(){const t=Date.now()-this.startTime,e=`验证成功!耗时:${(t/1e3).toFixed(2)}s`;this.updateUIState("success"),this.showFloatingTime(e,"success"),this.safeSetTimeout(()=>{this.options.onSuccess?.({captchaId:this.captchaData.captchaId,timestamp:Date.now(),duration:t}),this.hide()},2e3)}showFloatingTime(t,e="success"){const{elements:i}=this;i.floatingTime.textContent=t,i.floatingTime.className="slider-captcha-floating-time "+e,this.safeSetTimeout(()=>i.floatingTime.classList.add("show"),100),this.safeSetTimeout(()=>{i.floatingTime.className="slider-captcha-floating-time"},2500)}onVerifyFail(t){this.state.retryCount++,this.updateUIState("fail"),this.showFloatingTime(t,"fail"),this.safeSetTimeout(()=>{this.state.retryCount<this.options.maxRetries?this.reset():this.refresh()},2500)}reset(){this.clearAllTimers(),Object.assign(this.state,{isDragging:!1,currentX:0,startX:0,isLoading:!1}),this.times=[],this.startTime=null,this.cachedDimensions=null,requestAnimationFrame(()=>{this.setTransition(!0),this.elements.btn.style.transform="translateX(0px)",this.elements.sliderImg.style.transform="translateX(0px)",this.updateUIState("reset"),this.elements.error.style.display="none"})}refresh(){this.reset(),this.state.retryCount=0,this.loadCaptcha()}safeSetTimeout(t,e){const i=setTimeout(()=>{this.timers.delete(i),t()},e);return this.timers.add(i),i}safeClearTimeout(t){t&&(clearTimeout(t),this.timers.delete(t))}clearAllTimers(){this.timers.forEach(t=>{clearTimeout(t),clearInterval(t)}),this.timers.clear(),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}cleanupImages(){this.elements.backgroundImg&&(this.elements.backgroundImg.src="",this.elements.backgroundImg.onload=null,this.elements.backgroundImg.onerror=null),this.elements.sliderImg&&(this.elements.sliderImg.src="",this.elements.sliderImg.onload=null,this.elements.sliderImg.onerror=null),this.imageCache.clear()}throttle(t,e){let i=0;return function(...s){const a=Date.now();if(a-i>=e)return i=a,t.apply(this,s)}}debounce(t,e){let i;return function(...s){clearTimeout(i),i=setTimeout(()=>t.apply(this,s),e)}}destroy(){document.body.style.userSelect="",document.body.style.cursor="",this.clearAllTimers(),this.removeAllEventListeners(),this.cleanupImages(),this.elements.overlay?.parentNode&&this.elements.overlay.parentNode.removeChild(this.elements.overlay);const t=document.getElementById("slider-captcha-styles");t&&t.remove(),Object.keys(this).forEach(t=>{"constructor"!==t&&(this[t]=null)})}static create(t){return new PopupSliderCaptcha(t)}static show(t){const e=new PopupSliderCaptcha(t);return e.show(),e}}"undefined"!=typeof module&&module.exports?(module.exports=PopupSliderCaptcha,module.exports.default=PopupSliderCaptcha):"function"==typeof define&&define.amd?define([],()=>PopupSliderCaptcha):"undefined"!=typeof window&&(window.PopupSliderCaptcha=PopupSliderCaptcha,window.SliderCaptcha=PopupSliderCaptcha);class PasswordValidator{constructor(t={}){this.options={publicKeyUrl:t.publicKeyUrl||"/microservice/strongPassword/getPublicKey",validateUrl:t.validateUrl||"/microservice/strongPassword/checkPassword",timeout:t.timeout||1e4,headers:t.headers||{},...t},this.publicKeyCache=null,this.publicKeyExpiry=null}async getPublicKey(){if(this.publicKeyCache&&this.publicKeyExpiry&&Date.now()<this.publicKeyExpiry)return this.publicKeyCache;try{const t=await this.makeRequest(this.options.publicKeyUrl,{method:"GET"});if("0"!==t.code)throw Error("获取公钥失败:"+(t.message||"未知错误"));return this.publicKeyCache=t.data,this.publicKeyExpiry=Date.now()+3e5,this.publicKeyCache}catch(t){throw Error("获取公钥失败: "+t.message)}}encryptPassword(t,i){try{if(!e)throw Error("JSEncrypt库未正确加载");const s=new e;s.setPublicKey(i);const a=s.encrypt(t);if(!a)throw Error("密码加密失败");return a}catch(t){throw Error("密码加密失败: "+t.message)}}async validatePassword(t,e,i={}){try{const s=await this.getPublicKey(),a=this.encryptPassword(t,s),n=await this.makeRequest(this.options.validateUrl,{method:"POST",body:JSON.stringify({userName:e,password:a,timestamp:Date.now(),...i})});return{success:n.success,message:n.message,data:n.data,code:n.code}}catch(t){return{success:!1,message:t.message,code:"VALIDATION_ERROR"}}}async makeRequest(t,e={}){const i=new AbortController,s=setTimeout(()=>i.abort(),this.options.timeout);try{const a=await fetch(t,{...e,headers:{"Content-Type":"application/json",...this.options.headers,...e.headers},signal:i.signal});if(clearTimeout(s),!a.ok)throw Error(`HTTP错误: ${a.status} ${a.statusText}`);return await a.json()}catch(t){if(clearTimeout(s),"AbortError"===t.name)throw Error("请求超时");throw t}}clearCache(){this.publicKeyCache=null,this.publicKeyExpiry=null}updateOptions(t){this.options={...this.options,...t},this.clearCache()}}var a={PopupSliderCaptcha:PopupSliderCaptcha,PasswordValidator:PasswordValidator,createPasswordValidator:i,validatePassword:s};"undefined"!=typeof window&&(window.SliderCaptcha=PopupSliderCaptcha,window.PopupSliderCaptcha=PopupSliderCaptcha,window.PasswordValidator=PasswordValidator,window.createPasswordValidator=i,window.validatePassword=s),t.PasswordValidator=PasswordValidator,t.PopupSliderCaptcha=PopupSliderCaptcha,t.createPasswordValidator=i,t.default=a,t.validatePassword=s,Object.defineProperty(t,"__esModule",{value:!0})});
|
|
@@ -1,16 +1 @@
|
|
|
1
|
-
|
|
2
|
-
class PasswordValidator{constructor(t={}){this.options={publicKeyUrl:t.publicKeyUrl||"/microservice/strongPassword/getPublicKey",validateUrl:t.validateUrl||"/microservice/strongPassword/checkPassword",timeout:t.timeout||1e4,headers:t.headers||{},...t},this.publicKeyCache=null,this.publicKeyExpiry=null}async getPublicKey(){if(this.publicKeyCache&&this.publicKeyExpiry&&Date.now()<this.publicKeyExpiry)return this.publicKeyCache
|
|
3
|
-
try{const t=await this.makeRequest(this.options.publicKeyUrl,{method:"GET"})
|
|
4
|
-
if("0"!==t.code)throw Error("获取公钥失败:"+(t.message||"未知错误"))
|
|
5
|
-
return this.publicKeyCache=t.data,this.publicKeyExpiry=Date.now()+3e5,this.publicKeyCache}catch(t){throw Error("获取公钥失败: "+t.message)}}encryptPassword(t,r){try{if(!e)throw Error("JSEncrypt库未正确加载")
|
|
6
|
-
const s=new e
|
|
7
|
-
s.setPublicKey(r)
|
|
8
|
-
const o=s.encrypt(t)
|
|
9
|
-
if(!o)throw Error("密码加密失败")
|
|
10
|
-
return o}catch(t){throw Error("密码加密失败: "+t.message)}}async validatePassword(t,e,r={}){try{const s=await this.getPublicKey(),o=this.encryptPassword(t,s),i=await this.makeRequest(this.options.validateUrl,{method:"POST",body:JSON.stringify({userName:e,password:o,timestamp:Date.now(),...r})})
|
|
11
|
-
return{success:i.success,message:i.message,data:i.data,code:i.code}}catch(t){return{success:!1,message:t.message,code:"VALIDATION_ERROR"}}}async makeRequest(t,e={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.options.timeout)
|
|
12
|
-
try{const o=await fetch(t,{...e,headers:{"Content-Type":"application/json",...this.options.headers,...e.headers},signal:r.signal})
|
|
13
|
-
if(clearTimeout(s),!o.ok)throw Error(`HTTP错误: ${o.status} ${o.statusText}`)
|
|
14
|
-
return await o.json()}catch(t){if(clearTimeout(s),"AbortError"===t.name)throw Error("请求超时")
|
|
15
|
-
throw t}}clearCache(){this.publicKeyCache=null,this.publicKeyExpiry=null}updateOptions(t){this.options={...this.options,...t},this.clearCache()}}t.createPasswordValidator=function(t){return new PasswordValidator(t)},t.default=PasswordValidator,t.validatePassword=async function(t,e={},r={}){const s=new PasswordValidator(e),o=r.userName||""
|
|
16
|
-
return await s.validatePassword(t,o,r)},Object.defineProperty(t,"t",{value:!0})})
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("jsencrypt")):"function"==typeof define&&define.amd?define(["exports","jsencrypt"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).PasswordValidator={},e.JSEncrypt)}(this,function(e,t){"use strict";class PasswordValidator{constructor(e={}){this.options={publicKeyUrl:e.publicKeyUrl||"/microservice/strongPassword/getPublicKey",validateUrl:e.validateUrl||"/microservice/strongPassword/checkPassword",timeout:e.timeout||1e4,headers:e.headers||{},...e},this.publicKeyCache=null,this.publicKeyExpiry=null}async getPublicKey(){if(this.publicKeyCache&&this.publicKeyExpiry&&Date.now()<this.publicKeyExpiry)return this.publicKeyCache;try{const e=await this.makeRequest(this.options.publicKeyUrl,{method:"GET"});if("0"!==e.code)throw Error("获取公钥失败:"+(e.message||"未知错误"));return this.publicKeyCache=e.data,this.publicKeyExpiry=Date.now()+3e5,this.publicKeyCache}catch(e){throw Error("获取公钥失败: "+e.message)}}encryptPassword(e,s){try{if(!t)throw Error("JSEncrypt库未正确加载");const r=new t;r.setPublicKey(s);const i=r.encrypt(e);if(!i)throw Error("密码加密失败");return i}catch(e){throw Error("密码加密失败: "+e.message)}}async validatePassword(e,t,s={}){try{const r=await this.getPublicKey(),i=this.encryptPassword(e,r),a=await this.makeRequest(this.options.validateUrl,{method:"POST",body:JSON.stringify({userName:t,password:i,timestamp:Date.now(),...s})});return{success:a.success,message:a.message,data:a.data,code:a.code}}catch(e){return{success:!1,message:e.message,code:"VALIDATION_ERROR"}}}async makeRequest(e,t={}){const s=new AbortController,r=setTimeout(()=>s.abort(),this.options.timeout);try{const i=await fetch(e,{...t,headers:{"Content-Type":"application/json",...this.options.headers,...t.headers},signal:s.signal});if(clearTimeout(r),!i.ok)throw Error(`HTTP错误: ${i.status} ${i.statusText}`);return await i.json()}catch(e){if(clearTimeout(r),"AbortError"===e.name)throw Error("请求超时");throw e}}clearCache(){this.publicKeyCache=null,this.publicKeyExpiry=null}updateOptions(e){this.options={...this.options,...e},this.clearCache()}}e.createPasswordValidator=function(e){return new PasswordValidator(e)},e.default=PasswordValidator,e.validatePassword=async function(e,t={},s={}){const r=new PasswordValidator(t),i=s.userName||"";return await r.validatePassword(e,i,s)},Object.defineProperty(e,"__esModule",{value:!0})});
|
|
@@ -1,42 +1 @@
|
|
|
1
|
-
(function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(t="undefined"!=typeof globalThis?globalThis:t||self).SliderCaptcha=i()})(this,function(){"use strict"
|
|
2
|
-
class PopupSliderCaptcha{static DEFAULTS={width:320,height:155,sliderSize:38,maxRetries:3,timeout:3e4,apiUrl:"/api/captcha",verifyUrl:"/api/captcha/verify",throttleDelay:16,clickMaskClose:!1}
|
|
3
|
-
static CSS_CLASSES={overlay:"slider-captcha-overlay",modal:"slider-captcha-modal",header:"slider-captcha-header",container:"slider-captcha-container",track:"slider-captcha-track",btn:"slider-captcha-btn",hint:"slider-captcha-hint",loading:"slider-captcha-loading",error:"slider-captcha-error"}
|
|
4
|
-
static getStyles(){return":root{--sc-primary:#409eff;--sc-success:#67c23a;--sc-danger:#f56c6c;--sc-border:#e4e7eb;--sc-bg:linear-gradient(90deg, #f7f9fa 0%, #e8f4fd 100%);--sc-text:#333;--sc-text-light:#999;--sc-shadow:0 4px 20px rgba(0,0,0,.3);--sc-radius:8px;--sc-transition:.3s ease}.slider-captcha-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9999;display:none;justify-content:center;align-items:center;opacity:0;transition:opacity var(--sc-transition)}.slider-captcha-overlay.show{opacity:1}.slider-captcha-modal{background:#fff;border-radius:var(--sc-radius);padding:20px;box-shadow:var(--sc-shadow);position:relative;max-width:90vw;max-height:90vh;transform:scale(.8) translateY(-20px);opacity:0;transition:all var(--sc-transition)}.slider-captcha-modal.show{transform:scale(1) translateY(0);opacity:1}.slider-captcha-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid var(--sc-border)}.slider-captcha-container{display:flex;align-items:center;position:relative;border-radius:4px;overflow:hidden;margin-bottom:15px;background:#837a7a;justify-content:center}.slider-captcha-track{width:100%;height:40px;line-height:40px;background:var(--sc-bg);border:1px solid var(--sc-border);border-radius:20px;position:relative;margin-bottom:15px;overflow:hidden}.slider-captcha-btn{width:38px;height:38px;background:#fff;border:1px solid #ccc;border-radius:50%;position:absolute;top:0;left:0;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,.1);transition:all var(--sc-transition);user-select:none;z-index:1}.slider-captcha-loading{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,.6);display:flex;align-items:center;justify-content:center;flex-direction:column;color:#666;font-size:14px;z-index:10;border-radius:4px}.slider-captcha-error{color:var(--sc-danger);font-size:12px;text-align:center;margin-top:10px;display:none}.slider-captcha-title{margin:0;font-size:16px;color:var(--sc-text)}.slider-captcha-close,.slider-captcha-refresh{background:none;border:none;cursor:pointer;color:var(--sc-text-light);padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--sc-transition);position:relative;font-size:0}.slider-captcha-close::before,.slider-captcha-close::after{content:'';position:absolute;width:16px;height:2px;background-color:var(--sc-text-light);border-radius:1px;transition:all var(--sc-transition)}.slider-captcha-close::before{transform:rotate(45deg)}.slider-captcha-close::after{transform:rotate(-45deg)}.slider-captcha-close:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-close:hover::before,.slider-captcha-close:hover::after{background-color:var(--sc-danger)}.slider-captcha-refresh{margin-left:10px}.slider-captcha-refresh svg{width:20px;height:20px;fill:var(--sc-text-light);transition:all var(--sc-transition)}.slider-captcha-refresh:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-refresh:hover svg{fill:var(--sc-primary);transform:rotate(180deg)}.slider-captcha-floating-time{position:absolute;bottom:-40px;left:50%;transform:translateX(-50%);color:#fff;font-size:12px;white-space:nowrap;opacity:0;pointer-events:none;z-index:10;transition:all var(--sc-transition);background:#fff;padding:2px 15px;border-radius:10px}.slider-captcha-floating-time.show{opacity:1;transform:translateX(-50%) translateY(-45px)}.slider-captcha-floating-time.success{color:var(--sc-success)}.slider-captcha-floating-time.fail{color:var(--sc-danger)}.slider-captcha-bg{width:100%;height:100%;object-fit:cover;display:block}.slider-captcha-piece{position:absolute;top:0;left:0;cursor:pointer;transition:none;z-index:2}.slider-captcha-finger{position:absolute;top:50%;left:10px;transform:translateY(-50%);font-size:20px;animation:fingerSlide 2s ease-in-out infinite;pointer-events:none;z-index:1;opacity:.6}.slider-captcha-hint{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:var(--sc-text-light);font-size:14px;pointer-events:none;z-index:1;transition:all var(--sc-transition)}.slider-captcha-header-buttons{display:flex;align-items:center}@keyframes fingerSlide{0%{left:10px;opacity:.6}50%{opacity:1}100%{left:calc(50% - 10px);opacity:.6}}"}constructor(t={}){this.options={...PopupSliderCaptcha.DEFAULTS,...t},this.elements={},this.state=this.createInitialState(),this.captchaData=null,this.times=[],this.startTime=null,this.eventListeners=[],this.timers=new Set,this.rafId=null,this.cachedDimensions=null,this.imageCache=new Map,this.throttledHandleMove=this.throttle(t=>this.handleMove(t),this.options.throttleDelay),this.init()}createInitialState(){return{isVisible:!1,isDragging:!1,currentX:0,startX:0,retryCount:0,isLoading:!1}}init(){this.injectStyles(),this.createElements(),this.bindEvents()}injectStyles(){if(document.querySelector("#slider-captcha-styles"))return
|
|
5
|
-
const t=document.createElement("style")
|
|
6
|
-
t.id="slider-captcha-styles",t.textContent=PopupSliderCaptcha.getStyles(),document.head.appendChild(t)}createElements(){const{elements:t,options:i}=this;[["overlay","div",PopupSliderCaptcha.CSS_CLASSES.overlay],["modal","div",PopupSliderCaptcha.CSS_CLASSES.modal],["header","div",PopupSliderCaptcha.CSS_CLASSES.header],["title","h3","slider-captcha-title","安全验证"],["closeBtn","button","slider-captcha-close"],["refreshBtn","button","slider-captcha-refresh"],["container","div",PopupSliderCaptcha.CSS_CLASSES.container],["backgroundImg","img","slider-captcha-bg"],["sliderImg","img","slider-captcha-piece"],["loadingText","div",PopupSliderCaptcha.CSS_CLASSES.loading,"加载中..."],["floatingTime","div","slider-captcha-floating-time"],["track","div",PopupSliderCaptcha.CSS_CLASSES.track],["fingerAnimation","div","slider-captcha-finger","👉"],["btn","div",PopupSliderCaptcha.CSS_CLASSES.btn],["icon","div","","→"],["hint","div",PopupSliderCaptcha.CSS_CLASSES.hint,"向右滑动完成验证"],["error","div",PopupSliderCaptcha.CSS_CLASSES.error]].forEach(([i,e,s,a])=>{t[i]=this.createElement(e,s,a)}),t.container.style.cssText=`width:${i.width}px;height:${i.height}px`,t.refreshBtn.innerHTML='<svg viewBox="0 0 24 24"><path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z"/></svg>',this.assembleDOM(),this.setInitialState()}createElement(t,i="",e=""){const s=document.createElement(t)
|
|
7
|
-
return i&&(s.className=i),e&&(s.textContent=e),s}assembleDOM(){const{elements:t}=this,i=this.createElement("div","slider-captcha-header-buttons")
|
|
8
|
-
i.append(t.refreshBtn,t.closeBtn),t.header.append(t.title,i),t.container.append(t.backgroundImg,t.sliderImg,t.loadingText,t.floatingTime),t.btn.appendChild(t.icon),t.track.append(t.fingerAnimation,t.btn,t.hint),t.modal.append(t.header,t.container,t.track,t.error),t.overlay.appendChild(t.modal),document.body.appendChild(t.overlay)}setInitialState(){Object.assign(this.elements.container.style,{display:"none"}),Object.assign(this.elements.track.style,{display:"none"})}bindEvents(){const{elements:t}=this
|
|
9
|
-
this.addEventListener(t.closeBtn,"click",()=>this.hide()),this.addEventListener(t.refreshBtn,"click",()=>this.refresh()),this.addEventListener(t.overlay,"click",i=>{i.target===t.overlay&&this.options.clickMaskClose&&this.hide()}),this.addEventListener(document,"keydown",t=>{"Escape"===t.key&&this.state.isVisible&&this.hide()}),this.addEventListener(document,"visibilitychange",()=>this.handleVisibilityChange()),this.bindSliderEvents()}bindSliderEvents(){const{elements:t}=this,i={start:t=>this.handleStart(t),move:this.throttledHandleMove,end:()=>this.handleEnd()}
|
|
10
|
-
this.addEventListener(t.btn,"mousedown",i.start),this.addEventListener(t.btn,"touchstart",i.start),this.addEventListener(t.sliderImg,"mousedown",i.start),this.addEventListener(t.sliderImg,"touchstart",i.start),this.addEventListener(document,"mousemove",i.move,{passive:!1}),this.addEventListener(document,"touchmove",i.move,{passive:!1}),this.addEventListener(document,"mouseup",i.end),this.addEventListener(document,"touchend",i.end)}addEventListener(t,i,e,s={}){t&&"function"==typeof e&&(t.addEventListener(i,e,s),this.eventListeners.push({element:t,event:i,handler:e,options:s}))}removeAllEventListeners(){this.eventListeners.forEach(({element:t,event:i,handler:e,options:s})=>{try{t?.removeEventListener?.(i,e,s)}catch(t){}}),this.eventListeners.length=0}getDimensions(){if(!this.cachedDimensions){const t=this.elements.track.offsetWidth,i=this.elements.btn.offsetWidth
|
|
11
|
-
this.cachedDimensions={trackWidth:t,btnWidth:i,maxX:t-i}}return this.cachedDimensions}getPosition(){const{maxX:t}=this.getDimensions(),i=this.state.currentX/t
|
|
12
|
-
return Math.round(i*(this.options.width-this.options.sliderSize))}handleStart(t){!this.captchaData||this.state.isDragging||this.state.isLoading||(t.preventDefault(),this.state.isDragging=!0,this.state.startX=this.getClientX(t)-this.state.currentX,this.startTime=this.startTime||Date.now(),this.times=[{time:Date.now(),position:this.getPosition()}],this.setTransition(!1),this.updateUIState("dragging"),this.cachedDimensions=null)}handleMove(t){if(!this.state.isDragging)return
|
|
13
|
-
t.preventDefault()
|
|
14
|
-
const i=this.getClientX(t)-this.state.startX,{maxX:e}=this.getDimensions()
|
|
15
|
-
this.state.currentX=Math.max(0,Math.min(i,e)),this.times.push({time:Date.now(),position:this.getPosition()}),this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>this.updateSliderPosition())}handleEnd(){this.state.isDragging&&(this.times.push({time:Date.now(),position:this.getPosition()}),this.state.isDragging=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.verify())}handleVisibilityChange(){const t=document.hidden?"paused":"running"
|
|
16
|
-
this.elements.fingerAnimation&&(this.elements.fingerAnimation.style.animationPlayState=t)}getClientX(t){return t.type.includes("touch")?t.touches[0].clientX:t.clientX}setTransition(t){const i=t?"all 0.3s ease":"none"
|
|
17
|
-
requestAnimationFrame(()=>{this.elements.btn.style.transition=i,this.elements.sliderImg.style.transition=i})}updateUIState(t){const{elements:i}=this,e={dragging:()=>{i.hint.style.opacity="0",i.fingerAnimation.style.display="none"},success:()=>{Object.assign(i.btn.style,{background:"var(--sc-success)"}),Object.assign(i.icon.style,{innerHTML:"✓",color:"white"}),i.icon.innerHTML="✓"},fail:()=>{Object.assign(i.btn.style,{background:"var(--sc-danger)"}),Object.assign(i.icon.style,{innerHTML:"✗",color:"white"}),i.icon.innerHTML="✗"},reset:()=>{Object.assign(i.btn.style,{background:"white"}),Object.assign(i.icon.style,{color:"#666"}),i.icon.innerHTML="→",i.fingerAnimation.style.display="block",this.updateHintText("向右滑动完成验证","var(--sc-text-light)")},loading:()=>{i.hint.style.opacity="0",i.fingerAnimation.style.display="none",Object.assign(i.track.style,{pointerEvents:"none",opacity:"0.6"})}}
|
|
18
|
-
e[t]&&requestAnimationFrame(()=>{e[t](),"loading"!==t&&Object.assign(i.track.style,{pointerEvents:"auto",opacity:"1"})})}updateHintText(t,i){requestAnimationFrame(()=>{Object.assign(this.elements.hint,{textContent:t}),Object.assign(this.elements.hint.style,{color:i,opacity:"1"})})}updateSliderPosition(){const{elements:t,options:i,state:e}=this,{maxX:s}=this.getDimensions(),a=e.currentX/s*(i.width-i.sliderSize),n=e.currentX/s
|
|
19
|
-
requestAnimationFrame(()=>{t.btn.style.transform=`translateX(${e.currentX}px)`,t.sliderImg.style.transform=`translateX(${a}px)`,t.fingerAnimation.style.opacity=.8>n?"0.6":"0"})}show(){this.state.isVisible=!0,this.elements.overlay.style.display="flex",this.elements.overlay.offsetHeight,requestAnimationFrame(()=>{this.elements.overlay.classList.add("show"),this.elements.modal.classList.add("show")}),this.loadCaptcha()}hide(){this.state.isVisible=!1,this.elements.overlay.classList.remove("show"),this.elements.modal.classList.remove("show"),this.safeSetTimeout(()=>{this.elements.overlay.style.display="none",document.body.removeChild(this.elements.overlay),this.reset(),this.options.onClose?.(),this.elements.overlay=null},300)}async loadCaptcha(){try{this.showLoading(),this.startTime=Date.now()
|
|
20
|
-
const t=new AbortController,i=this.safeSetTimeout(()=>t.abort(),this.options.timeout),e=await fetch(this.options.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({place:2,timestamp:Date.now()}),signal:t.signal})
|
|
21
|
-
if(this.safeClearTimeout(i),!e.ok)throw Error("HTTP "+e.status)
|
|
22
|
-
const s=await e.json()
|
|
23
|
-
if(!s.data?.canvasSrc||!s.data?.blockSrc)throw Error("验证码数据格式错误")
|
|
24
|
-
this.captchaData=s.data,this.showCaptcha(),await this.renderCaptcha()}catch(t){const i="AbortError"===t.name?"请求超时,请重试":"加载验证码失败: "+t.message
|
|
25
|
-
this.showError(i)}}async renderCaptcha(){return new Promise((t,i)=>{let e=0
|
|
26
|
-
const s=()=>2===++e&&(this.hideLoading(),t()),a=()=>i(Error("图片加载失败"))
|
|
27
|
-
this.loadImage(this.elements.backgroundImg,this.captchaData.canvasSrc,{width:this.captchaData.canvasWidth,height:this.captchaData.canvasHeight},s,a),this.loadImage(this.elements.sliderImg,this.captchaData.blockSrc,{width:this.captchaData.blockWidth,height:this.captchaData.blockHeight,top:this.captchaData.blockY},s,a)})}loadImage(t,i,e,s,a){if(this.imageCache.has(i)){const a=this.imageCache.get(i)
|
|
28
|
-
return t.src=a.src,this.applyStyles(t,e),void s()}t.onload=()=>{this.imageCache.set(i,t.cloneNode()),s()},t.onerror=a,t.src=i,this.applyStyles(t,e)}applyStyles(t,i){Object.entries(i).forEach(([i,e])=>{t.style[i]="number"==typeof e?e+"px":e})}showLoading(){this.state.isLoading=!0,this.batchUpdateStyles({container:{display:"block"},loadingText:{display:"flex"},error:{display:"none"}}),this.updateUIState("loading")}hideLoading(){this.state.isLoading=!1,this.batchUpdateStyles({loadingText:{display:"none"}}),this.updateUIState("reset")}showCaptcha(){this.batchUpdateStyles({container:{display:"block"},track:{display:"block"},error:{display:"none"}})}showError(t){this.hideLoading(),this.batchUpdateStyles({error:{display:"block",textContent:t}})}batchUpdateStyles(t){requestAnimationFrame(()=>{Object.entries(t).forEach(([t,i])=>{const e=this.elements[t]
|
|
29
|
-
e&&Object.entries(i).forEach(([t,i])=>{"textContent"===t?e.textContent=i:e.style[t]=i})})})}async verify(){if(this.captchaData)try{const t=new AbortController,i=this.safeSetTimeout(()=>t.abort(),this.options.timeout),e=await fetch(this.options.verifyUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({loginVo:{nonceStr:this.captchaData.nonceStr,value:this.getPosition()},dragEventList:[...this.times]}),signal:t.signal})
|
|
30
|
-
if(this.safeClearTimeout(i),!e.ok)throw Error("HTTP "+e.status)
|
|
31
|
-
const s=await e.json()
|
|
32
|
-
"0"===s.code||!0===s.success?this.onVerifySuccess():this.onVerifyFail(s.message||"验证失败,请重试!")}catch(t){const i="AbortError"===t.name?"验证超时,请重试":"网络错误"
|
|
33
|
-
this.onVerifyFail(i)}else this.onVerifyFail("验证码数据丢失")}onVerifySuccess(){const t=Date.now()-this.startTime,i=`验证成功!耗时:${(t/1e3).toFixed(2)}s`
|
|
34
|
-
this.updateUIState("success"),this.showFloatingTime(i,"success"),this.safeSetTimeout(()=>{this.options.onSuccess?.({captchaId:this.captchaData.captchaId,timestamp:Date.now(),duration:t}),this.hide()},2e3)}showFloatingTime(t,i="success"){const{elements:e}=this
|
|
35
|
-
e.floatingTime.textContent=t,e.floatingTime.className="slider-captcha-floating-time "+i,this.safeSetTimeout(()=>e.floatingTime.classList.add("show"),100),this.safeSetTimeout(()=>{e.floatingTime.className="slider-captcha-floating-time"},2500)}onVerifyFail(t){this.state.retryCount++,this.updateUIState("fail"),this.showFloatingTime(t,"fail"),this.safeSetTimeout(()=>{this.state.retryCount<this.options.maxRetries?this.reset():this.refresh()},2500)}reset(){this.clearAllTimers(),Object.assign(this.state,{isDragging:!1,currentX:0,startX:0,isLoading:!1}),this.times=[],this.startTime=null,this.cachedDimensions=null,requestAnimationFrame(()=>{this.setTransition(!0),this.elements.btn.style.transform="translateX(0px)",this.elements.sliderImg.style.transform="translateX(0px)",this.updateUIState("reset"),this.elements.error.style.display="none"})}refresh(){this.reset(),this.state.retryCount=0,this.loadCaptcha()}safeSetTimeout(t,i){const e=setTimeout(()=>{this.timers.delete(e),t()},i)
|
|
36
|
-
return this.timers.add(e),e}safeClearTimeout(t){t&&(clearTimeout(t),this.timers.delete(t))}clearAllTimers(){this.timers.forEach(t=>{clearTimeout(t),clearInterval(t)}),this.timers.clear(),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}cleanupImages(){this.elements.backgroundImg&&(this.elements.backgroundImg.src="",this.elements.backgroundImg.onload=null,this.elements.backgroundImg.onerror=null),this.elements.sliderImg&&(this.elements.sliderImg.src="",this.elements.sliderImg.onload=null,this.elements.sliderImg.onerror=null),this.imageCache.clear()}throttle(t,i){let e=0
|
|
37
|
-
return function(...s){const a=Date.now()
|
|
38
|
-
if(a-e>=i)return e=a,t.apply(this,s)}}debounce(t,i){let e
|
|
39
|
-
return function(...s){clearTimeout(e),e=setTimeout(()=>t.apply(this,s),i)}}destroy(){document.body.style.userSelect="",document.body.style.cursor="",this.clearAllTimers(),this.removeAllEventListeners(),this.cleanupImages(),this.elements.overlay?.parentNode&&this.elements.overlay.parentNode.removeChild(this.elements.overlay)
|
|
40
|
-
const t=document.getElementById("slider-captcha-styles")
|
|
41
|
-
t&&t.remove(),Object.keys(this).forEach(t=>{"constructor"!==t&&(this[t]=null)})}static create(t){return new PopupSliderCaptcha(t)}static show(t){const i=new PopupSliderCaptcha(t)
|
|
42
|
-
return i.show(),i}}return"undefined"!=typeof module&&module.exports?(module.exports=PopupSliderCaptcha,module.exports.default=PopupSliderCaptcha):"function"==typeof define&&define.amd?define([],()=>PopupSliderCaptcha):"undefined"!=typeof window&&(window.PopupSliderCaptcha=PopupSliderCaptcha,window.SliderCaptcha=PopupSliderCaptcha),PopupSliderCaptcha})
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SliderCaptcha=e()}(this,function(){"use strict";class PopupSliderCaptcha{static DEFAULTS={width:320,height:155,sliderSize:38,maxRetries:3,timeout:3e4,apiUrl:"/api/captcha",verifyUrl:"/api/captcha/verify",throttleDelay:16,clickMaskClose:!1};static CSS_CLASSES={overlay:"slider-captcha-overlay",modal:"slider-captcha-modal",header:"slider-captcha-header",container:"slider-captcha-container",track:"slider-captcha-track",btn:"slider-captcha-btn",hint:"slider-captcha-hint",loading:"slider-captcha-loading",error:"slider-captcha-error"};static getStyles(){return":root{--sc-primary:#409eff;--sc-success:#67c23a;--sc-danger:#f56c6c;--sc-border:#e4e7eb;--sc-bg:linear-gradient(90deg, #f7f9fa 0%, #e8f4fd 100%);--sc-text:#333;--sc-text-light:#999;--sc-shadow:0 4px 20px rgba(0,0,0,.3);--sc-radius:8px;--sc-transition:.3s ease}.slider-captcha-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9999;display:none;justify-content:center;align-items:center;opacity:0;transition:opacity var(--sc-transition)}.slider-captcha-overlay.show{opacity:1}.slider-captcha-modal{background:#fff;border-radius:var(--sc-radius);padding:20px;box-shadow:var(--sc-shadow);position:relative;max-width:90vw;max-height:90vh;transform:scale(.8) translateY(-20px);opacity:0;transition:all var(--sc-transition)}.slider-captcha-modal.show{transform:scale(1) translateY(0);opacity:1}.slider-captcha-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid var(--sc-border)}.slider-captcha-container{display:flex;align-items:center;position:relative;border-radius:4px;overflow:hidden;margin-bottom:15px;background:#837a7a;justify-content:center}.slider-captcha-track{width:100%;height:40px;line-height:40px;background:var(--sc-bg);border:1px solid var(--sc-border);border-radius:20px;position:relative;margin-bottom:15px;overflow:hidden}.slider-captcha-btn{width:38px;height:38px;background:#fff;border:1px solid #ccc;border-radius:50%;position:absolute;top:0;left:0;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,.1);transition:all var(--sc-transition);user-select:none;z-index:1}.slider-captcha-loading{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,.6);display:flex;align-items:center;justify-content:center;flex-direction:column;color:#666;font-size:14px;z-index:10;border-radius:4px}.slider-captcha-error{color:var(--sc-danger);font-size:12px;text-align:center;margin-top:10px;display:none}.slider-captcha-title{margin:0;font-size:16px;color:var(--sc-text)}.slider-captcha-close,.slider-captcha-refresh{background:none;border:none;cursor:pointer;color:var(--sc-text-light);padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--sc-transition);position:relative;font-size:0}.slider-captcha-close::before,.slider-captcha-close::after{content:'';position:absolute;width:16px;height:2px;background-color:var(--sc-text-light);border-radius:1px;transition:all var(--sc-transition)}.slider-captcha-close::before{transform:rotate(45deg)}.slider-captcha-close::after{transform:rotate(-45deg)}.slider-captcha-close:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-close:hover::before,.slider-captcha-close:hover::after{background-color:var(--sc-danger)}.slider-captcha-refresh{margin-left:10px}.slider-captcha-refresh svg{width:20px;height:20px;fill:var(--sc-text-light);transition:all var(--sc-transition)}.slider-captcha-refresh:hover{background:#f5f5f5;transform:scale(1.1)}.slider-captcha-refresh:hover svg{fill:var(--sc-primary);transform:rotate(180deg)}.slider-captcha-floating-time{position:absolute;bottom:-40px;left:50%;transform:translateX(-50%);color:#fff;font-size:12px;white-space:nowrap;opacity:0;pointer-events:none;z-index:10;transition:all var(--sc-transition);background:#fff;padding:2px 15px;border-radius:10px}.slider-captcha-floating-time.show{opacity:1;transform:translateX(-50%) translateY(-45px)}.slider-captcha-floating-time.success{color:var(--sc-success)}.slider-captcha-floating-time.fail{color:var(--sc-danger)}.slider-captcha-bg{width:100%;height:100%;object-fit:cover;display:block}.slider-captcha-piece{position:absolute;top:0;left:0;cursor:pointer;transition:none;z-index:2}.slider-captcha-finger{position:absolute;top:50%;left:10px;transform:translateY(-50%);font-size:20px;animation:fingerSlide 2s ease-in-out infinite;pointer-events:none;z-index:1;opacity:.6}.slider-captcha-hint{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:var(--sc-text-light);font-size:14px;pointer-events:none;z-index:1;transition:all var(--sc-transition)}.slider-captcha-header-buttons{display:flex;align-items:center}@keyframes fingerSlide{0%{left:10px;opacity:.6}50%{opacity:1}100%{left:calc(50% - 10px);opacity:.6}}"}constructor(t={}){this.options={...PopupSliderCaptcha.DEFAULTS,...t},this.elements={},this.state=this.createInitialState(),this.captchaData=null,this.times=[],this.startTime=null,this.eventListeners=[],this.timers=new Set,this.rafId=null,this.cachedDimensions=null,this.imageCache=new Map,this.throttledHandleMove=this.throttle(t=>this.handleMove(t),this.options.throttleDelay),this.init()}createInitialState(){return{isVisible:!1,isDragging:!1,currentX:0,startX:0,retryCount:0,isLoading:!1}}init(){this.injectStyles(),this.createElements(),this.bindEvents()}injectStyles(){if(document.querySelector("#slider-captcha-styles"))return;const t=document.createElement("style");t.id="slider-captcha-styles",t.textContent=PopupSliderCaptcha.getStyles(),document.head.appendChild(t)}createElements(){const{elements:t,options:e}=this;[["overlay","div",PopupSliderCaptcha.CSS_CLASSES.overlay],["modal","div",PopupSliderCaptcha.CSS_CLASSES.modal],["header","div",PopupSliderCaptcha.CSS_CLASSES.header],["title","h3","slider-captcha-title","安全验证"],["closeBtn","button","slider-captcha-close"],["refreshBtn","button","slider-captcha-refresh"],["container","div",PopupSliderCaptcha.CSS_CLASSES.container],["backgroundImg","img","slider-captcha-bg"],["sliderImg","img","slider-captcha-piece"],["loadingText","div",PopupSliderCaptcha.CSS_CLASSES.loading,"加载中..."],["floatingTime","div","slider-captcha-floating-time"],["track","div",PopupSliderCaptcha.CSS_CLASSES.track],["fingerAnimation","div","slider-captcha-finger","👉"],["btn","div",PopupSliderCaptcha.CSS_CLASSES.btn],["icon","div","","→"],["hint","div",PopupSliderCaptcha.CSS_CLASSES.hint,"向右滑动完成验证"],["error","div",PopupSliderCaptcha.CSS_CLASSES.error]].forEach(([e,i,s,a])=>{t[e]=this.createElement(i,s,a)}),t.container.style.cssText=`width:${e.width}px;height:${e.height}px`,t.refreshBtn.innerHTML='<svg viewBox="0 0 24 24"><path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z"/></svg>',this.assembleDOM(),this.setInitialState()}createElement(t,e="",i=""){const s=document.createElement(t);return e&&(s.className=e),i&&(s.textContent=i),s}assembleDOM(){const{elements:t}=this,e=this.createElement("div","slider-captcha-header-buttons");e.append(t.refreshBtn,t.closeBtn),t.header.append(t.title,e),t.container.append(t.backgroundImg,t.sliderImg,t.loadingText,t.floatingTime),t.btn.appendChild(t.icon),t.track.append(t.fingerAnimation,t.btn,t.hint),t.modal.append(t.header,t.container,t.track,t.error),t.overlay.appendChild(t.modal),document.body.appendChild(t.overlay)}setInitialState(){Object.assign(this.elements.container.style,{display:"none"}),Object.assign(this.elements.track.style,{display:"none"})}bindEvents(){const{elements:t}=this;this.addEventListener(t.closeBtn,"click",()=>this.hide()),this.addEventListener(t.refreshBtn,"click",()=>this.refresh()),this.addEventListener(t.overlay,"click",e=>{e.target===t.overlay&&this.options.clickMaskClose&&this.hide()}),this.addEventListener(document,"keydown",t=>{"Escape"===t.key&&this.state.isVisible&&this.hide()}),this.addEventListener(document,"visibilitychange",()=>this.handleVisibilityChange()),this.bindSliderEvents()}bindSliderEvents(){const{elements:t}=this,e={start:t=>this.handleStart(t),move:this.throttledHandleMove,end:()=>this.handleEnd()};this.addEventListener(t.btn,"mousedown",e.start),this.addEventListener(t.btn,"touchstart",e.start),this.addEventListener(t.sliderImg,"mousedown",e.start),this.addEventListener(t.sliderImg,"touchstart",e.start),this.addEventListener(document,"mousemove",e.move,{passive:!1}),this.addEventListener(document,"touchmove",e.move,{passive:!1}),this.addEventListener(document,"mouseup",e.end),this.addEventListener(document,"touchend",e.end)}addEventListener(t,e,i,s={}){t&&"function"==typeof i&&(t.addEventListener(e,i,s),this.eventListeners.push({element:t,event:e,handler:i,options:s}))}removeAllEventListeners(){this.eventListeners.forEach(({element:t,event:e,handler:i,options:s})=>{try{t?.removeEventListener?.(e,i,s)}catch(t){}}),this.eventListeners.length=0}getDimensions(){if(!this.cachedDimensions){const t=this.elements.track.offsetWidth,e=this.elements.btn.offsetWidth;this.cachedDimensions={trackWidth:t,btnWidth:e,maxX:t-e}}return this.cachedDimensions}getPosition(){const{maxX:t}=this.getDimensions(),e=this.state.currentX/t;return Math.round(e*(this.options.width-this.options.sliderSize))}handleStart(t){!this.captchaData||this.state.isDragging||this.state.isLoading||(t.preventDefault(),this.state.isDragging=!0,this.state.startX=this.getClientX(t)-this.state.currentX,this.startTime=this.startTime||Date.now(),this.times=[{time:Date.now(),position:this.getPosition()}],this.setTransition(!1),this.updateUIState("dragging"),this.cachedDimensions=null)}handleMove(t){if(!this.state.isDragging)return;t.preventDefault();const e=this.getClientX(t)-this.state.startX,{maxX:i}=this.getDimensions();this.state.currentX=Math.max(0,Math.min(e,i)),this.times.push({time:Date.now(),position:this.getPosition()}),this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>this.updateSliderPosition())}handleEnd(){this.state.isDragging&&(this.times.push({time:Date.now(),position:this.getPosition()}),this.state.isDragging=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.verify())}handleVisibilityChange(){const t=document.hidden?"paused":"running";this.elements.fingerAnimation&&(this.elements.fingerAnimation.style.animationPlayState=t)}getClientX(t){return t.type.includes("touch")?t.touches[0].clientX:t.clientX}setTransition(t){const e=t?"all 0.3s ease":"none";requestAnimationFrame(()=>{this.elements.btn.style.transition=e,this.elements.sliderImg.style.transition=e})}updateUIState(t){const{elements:e}=this,i={dragging:()=>{e.hint.style.opacity="0",e.fingerAnimation.style.display="none"},success:()=>{Object.assign(e.btn.style,{background:"var(--sc-success)"}),Object.assign(e.icon.style,{innerHTML:"✓",color:"white"}),e.icon.innerHTML="✓"},fail:()=>{Object.assign(e.btn.style,{background:"var(--sc-danger)"}),Object.assign(e.icon.style,{innerHTML:"✗",color:"white"}),e.icon.innerHTML="✗"},reset:()=>{Object.assign(e.btn.style,{background:"white"}),Object.assign(e.icon.style,{color:"#666"}),e.icon.innerHTML="→",e.fingerAnimation.style.display="block",this.updateHintText("向右滑动完成验证","var(--sc-text-light)")},loading:()=>{e.hint.style.opacity="0",e.fingerAnimation.style.display="none",Object.assign(e.track.style,{pointerEvents:"none",opacity:"0.6"})}};i[t]&&requestAnimationFrame(()=>{i[t](),"loading"!==t&&Object.assign(e.track.style,{pointerEvents:"auto",opacity:"1"})})}updateHintText(t,e){requestAnimationFrame(()=>{Object.assign(this.elements.hint,{textContent:t}),Object.assign(this.elements.hint.style,{color:e,opacity:"1"})})}updateSliderPosition(){const{elements:t,options:e,state:i}=this,{maxX:s}=this.getDimensions(),a=i.currentX/s*(e.width-e.sliderSize),n=i.currentX/s;requestAnimationFrame(()=>{t.btn.style.transform=`translateX(${i.currentX}px)`,t.sliderImg.style.transform=`translateX(${a}px)`,t.fingerAnimation.style.opacity=.8>n?"0.6":"0"})}show(){this.state.isVisible=!0,this.elements.overlay.style.display="flex",this.elements.overlay.offsetHeight,requestAnimationFrame(()=>{this.elements.overlay.classList.add("show"),this.elements.modal.classList.add("show")}),this.loadCaptcha()}hide(){this.state.isVisible=!1,this.elements.overlay.classList.remove("show"),this.elements.modal.classList.remove("show"),this.safeSetTimeout(()=>{this.elements.overlay.style.display="none",document.body.removeChild(this.elements.overlay),this.reset(),this.options.onClose?.(),this.elements.overlay=null},300)}async loadCaptcha(){try{this.showLoading(),this.startTime=Date.now();const t=new AbortController,e=this.safeSetTimeout(()=>t.abort(),this.options.timeout),i=await fetch(this.options.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({place:2,timestamp:Date.now()}),signal:t.signal});if(this.safeClearTimeout(e),!i.ok)throw Error("HTTP "+i.status);const s=await i.json();if(!s.data?.canvasSrc||!s.data?.blockSrc)throw Error("验证码数据格式错误");this.captchaData=s.data,this.showCaptcha(),await this.renderCaptcha()}catch(t){const e="AbortError"===t.name?"请求超时,请重试":"加载验证码失败: "+t.message;this.showError(e)}}async renderCaptcha(){return new Promise((t,e)=>{let i=0;const s=()=>2===++i&&(this.hideLoading(),t()),a=()=>e(Error("图片加载失败"));this.loadImage(this.elements.backgroundImg,this.captchaData.canvasSrc,{width:this.captchaData.canvasWidth,height:this.captchaData.canvasHeight},s,a),this.loadImage(this.elements.sliderImg,this.captchaData.blockSrc,{width:this.captchaData.blockWidth,height:this.captchaData.blockHeight,top:this.captchaData.blockY},s,a)})}loadImage(t,e,i,s,a){if(this.imageCache.has(e)){const a=this.imageCache.get(e);return t.src=a.src,this.applyStyles(t,i),void s()}t.onload=()=>{this.imageCache.set(e,t.cloneNode()),s()},t.onerror=a,t.src=e,this.applyStyles(t,i)}applyStyles(t,e){Object.entries(e).forEach(([e,i])=>{t.style[e]="number"==typeof i?i+"px":i})}showLoading(){this.state.isLoading=!0,this.batchUpdateStyles({container:{display:"block"},loadingText:{display:"flex"},error:{display:"none"}}),this.updateUIState("loading")}hideLoading(){this.state.isLoading=!1,this.batchUpdateStyles({loadingText:{display:"none"}}),this.updateUIState("reset")}showCaptcha(){this.batchUpdateStyles({container:{display:"block"},track:{display:"block"},error:{display:"none"}})}showError(t){this.hideLoading(),this.batchUpdateStyles({error:{display:"block",textContent:t}})}batchUpdateStyles(t){requestAnimationFrame(()=>{Object.entries(t).forEach(([t,e])=>{const i=this.elements[t];i&&Object.entries(e).forEach(([t,e])=>{"textContent"===t?i.textContent=e:i.style[t]=e})})})}async verify(){if(this.captchaData)try{const t=new AbortController,e=this.safeSetTimeout(()=>t.abort(),this.options.timeout),i=await fetch(this.options.verifyUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({loginVo:{nonceStr:this.captchaData.nonceStr,value:this.getPosition()},dragEventList:[...this.times]}),signal:t.signal});if(this.safeClearTimeout(e),!i.ok)throw Error("HTTP "+i.status);const s=await i.json();"0"===s.code||!0===s.success?this.onVerifySuccess():this.onVerifyFail(s.message||"验证失败,请重试!")}catch(t){const e="AbortError"===t.name?"验证超时,请重试":"网络错误";this.onVerifyFail(e)}else this.onVerifyFail("验证码数据丢失")}onVerifySuccess(){const t=Date.now()-this.startTime,e=`验证成功!耗时:${(t/1e3).toFixed(2)}s`;this.updateUIState("success"),this.showFloatingTime(e,"success"),this.safeSetTimeout(()=>{this.options.onSuccess?.({captchaId:this.captchaData.captchaId,timestamp:Date.now(),duration:t}),this.hide()},2e3)}showFloatingTime(t,e="success"){const{elements:i}=this;i.floatingTime.textContent=t,i.floatingTime.className="slider-captcha-floating-time "+e,this.safeSetTimeout(()=>i.floatingTime.classList.add("show"),100),this.safeSetTimeout(()=>{i.floatingTime.className="slider-captcha-floating-time"},2500)}onVerifyFail(t){this.state.retryCount++,this.updateUIState("fail"),this.showFloatingTime(t,"fail"),this.safeSetTimeout(()=>{this.state.retryCount<this.options.maxRetries?this.reset():this.refresh()},2500)}reset(){this.clearAllTimers(),Object.assign(this.state,{isDragging:!1,currentX:0,startX:0,isLoading:!1}),this.times=[],this.startTime=null,this.cachedDimensions=null,requestAnimationFrame(()=>{this.setTransition(!0),this.elements.btn.style.transform="translateX(0px)",this.elements.sliderImg.style.transform="translateX(0px)",this.updateUIState("reset"),this.elements.error.style.display="none"})}refresh(){this.reset(),this.state.retryCount=0,this.loadCaptcha()}safeSetTimeout(t,e){const i=setTimeout(()=>{this.timers.delete(i),t()},e);return this.timers.add(i),i}safeClearTimeout(t){t&&(clearTimeout(t),this.timers.delete(t))}clearAllTimers(){this.timers.forEach(t=>{clearTimeout(t),clearInterval(t)}),this.timers.clear(),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}cleanupImages(){this.elements.backgroundImg&&(this.elements.backgroundImg.src="",this.elements.backgroundImg.onload=null,this.elements.backgroundImg.onerror=null),this.elements.sliderImg&&(this.elements.sliderImg.src="",this.elements.sliderImg.onload=null,this.elements.sliderImg.onerror=null),this.imageCache.clear()}throttle(t,e){let i=0;return function(...s){const a=Date.now();if(a-i>=e)return i=a,t.apply(this,s)}}debounce(t,e){let i;return function(...s){clearTimeout(i),i=setTimeout(()=>t.apply(this,s),e)}}destroy(){document.body.style.userSelect="",document.body.style.cursor="",this.clearAllTimers(),this.removeAllEventListeners(),this.cleanupImages(),this.elements.overlay?.parentNode&&this.elements.overlay.parentNode.removeChild(this.elements.overlay);const t=document.getElementById("slider-captcha-styles");t&&t.remove(),Object.keys(this).forEach(t=>{"constructor"!==t&&(this[t]=null)})}static create(t){return new PopupSliderCaptcha(t)}static show(t){const e=new PopupSliderCaptcha(t);return e.show(),e}}return"undefined"!=typeof module&&module.exports?(module.exports=PopupSliderCaptcha,module.exports.default=PopupSliderCaptcha):"function"==typeof define&&define.amd?define([],()=>PopupSliderCaptcha):"undefined"!=typeof window&&(window.PopupSliderCaptcha=PopupSliderCaptcha,window.SliderCaptcha=PopupSliderCaptcha),PopupSliderCaptcha});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "slider-captcha-sdk",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.9",
|
|
4
4
|
"description": "纯JavaScript滑块验证码SDK和密码校验工具,无依赖,支持多种模块格式",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.min.js",
|
|
@@ -35,16 +35,11 @@
|
|
|
35
35
|
],
|
|
36
36
|
"scripts": {
|
|
37
37
|
"build": "npm run clean && rollup -c",
|
|
38
|
-
"build:dev": "npm run clean && rollup -c --environment NODE_ENV:development",
|
|
39
38
|
"build:prod": "npm run clean && rollup -c --environment NODE_ENV:production",
|
|
40
|
-
"build:analyze": "npm run build:prod && npm run analyze",
|
|
41
|
-
"dev": "rollup -c -w --environment NODE_ENV:development",
|
|
42
39
|
"prepublishOnly": "npm run build:prod",
|
|
43
|
-
"test": "echo \"Error: no test specified\" && exit 1",
|
|
44
|
-
"lint": "eslint src --ext .js --fix",
|
|
45
40
|
"clean": "rm -rf dist",
|
|
46
|
-
"
|
|
47
|
-
"
|
|
41
|
+
"size": "npm run build:prod && ls -lh dist/*.min.js",
|
|
42
|
+
"pack:check": "npm pack --dry-run"
|
|
48
43
|
},
|
|
49
44
|
"keywords": [
|
|
50
45
|
"captcha",
|
|
@@ -72,12 +67,10 @@
|
|
|
72
67
|
"devDependencies": {
|
|
73
68
|
"@rollup/plugin-node-resolve": "^15.0.0",
|
|
74
69
|
"@rollup/plugin-terser": "^0.4.0",
|
|
75
|
-
"bundlesize": "^0.18.2",
|
|
76
70
|
"eslint": "^8.0.0",
|
|
77
71
|
"eslint-plugin-vue": "^9.0.0",
|
|
78
72
|
"rollup": "^3.0.0",
|
|
79
|
-
"rollup-plugin-copy": "^3.4.0"
|
|
80
|
-
"rollup-plugin-visualizer": "^5.14.0"
|
|
73
|
+
"rollup-plugin-copy": "^3.4.0"
|
|
81
74
|
},
|
|
82
75
|
"dependencies": {
|
|
83
76
|
"jsencrypt": "^3.3.2"
|
|
@@ -88,19 +81,5 @@
|
|
|
88
81
|
},
|
|
89
82
|
"publishConfig": {
|
|
90
83
|
"registry": "https://registry.npmjs.org/"
|
|
91
|
-
}
|
|
92
|
-
"bundlesize": [
|
|
93
|
-
{
|
|
94
|
-
"path": "dist/index.min.js",
|
|
95
|
-
"maxSize": "50 kB"
|
|
96
|
-
},
|
|
97
|
-
{
|
|
98
|
-
"path": "dist/slider-captcha.min.js",
|
|
99
|
-
"maxSize": "30 kB"
|
|
100
|
-
},
|
|
101
|
-
{
|
|
102
|
-
"path": "dist/password-validator.min.js",
|
|
103
|
-
"maxSize": "20 kB"
|
|
104
|
-
}
|
|
105
|
-
]
|
|
84
|
+
}
|
|
106
85
|
}
|
package/dist/LICENSE
DELETED
|
File without changes
|
package/dist/README.md
DELETED
|
@@ -1,172 +0,0 @@
|
|
|
1
|
-
# Slider Captcha SDK
|
|
2
|
-
|
|
3
|
-
[](https://badge.fury.io/js/slider-captcha-sdk)
|
|
4
|
-
[](https://opensource.org/licenses/MIT)
|
|
5
|
-
|
|
6
|
-
纯JavaScript滑块验证码SDK,无外部依赖,支持多种模块格式。
|
|
7
|
-
|
|
8
|
-
## ✨ 特性
|
|
9
|
-
|
|
10
|
-
- 🚀 **零依赖** - 纯JavaScript实现,无外部依赖
|
|
11
|
-
- 📱 **响应式** - 完美支持移动端和桌面端
|
|
12
|
-
- 🎨 **可定制** - 丰富的配置选项和样式定制
|
|
13
|
-
- 📦 **多格式** - 支持UMD、ES Module、CommonJS
|
|
14
|
-
- 💪 **TypeScript** - 完整的TypeScript类型定义
|
|
15
|
-
- 🔧 **易集成** - 简单的API,快速集成
|
|
16
|
-
- 🛡️ **安全可靠** - 防暴力破解,多重验证
|
|
17
|
-
|
|
18
|
-
## 📦 安装
|
|
19
|
-
|
|
20
|
-
```bash
|
|
21
|
-
npm install slider-captcha-sdk
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
或者使用yarn:
|
|
25
|
-
|
|
26
|
-
```bash
|
|
27
|
-
yarn add slider-captcha-sdk
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
## 🚀 快速开始
|
|
31
|
-
|
|
32
|
-
### ES Module
|
|
33
|
-
```javascript
|
|
34
|
-
import { PopupSliderCaptcha} from 'slider-captcha-sdk'
|
|
35
|
-
|
|
36
|
-
const captcha = new PopupSliderCaptcha({
|
|
37
|
-
apiUrl: '/api/captcha',
|
|
38
|
-
verifyUrl: '/api/captcha/verify',
|
|
39
|
-
onSuccess: (data) => {
|
|
40
|
-
console.log('验证成功:', data)
|
|
41
|
-
},
|
|
42
|
-
onFail: (error) => {
|
|
43
|
-
console.log('验证失败:', error)
|
|
44
|
-
}
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
// 显示验证码
|
|
48
|
-
captcha.show()
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
### UMD (浏览器直接引入)
|
|
52
|
-
```html
|
|
53
|
-
<script src="https://unpkg.com/slider-captcha-sdk/dist/slider-captcha.min.js"></script>
|
|
54
|
-
<script>
|
|
55
|
-
const captcha = new SliderCaptcha({
|
|
56
|
-
apiUrl: '/api/captcha',
|
|
57
|
-
verifyUrl: '/api/captcha/verify'
|
|
58
|
-
})
|
|
59
|
-
captcha.show()
|
|
60
|
-
</script>
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
### CommonJS
|
|
64
|
-
```javascript
|
|
65
|
-
const SliderCaptcha = require('slider-captcha-sdk')
|
|
66
|
-
|
|
67
|
-
const captcha = new SliderCaptcha()
|
|
68
|
-
captcha.show()
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
## 📖 API文档
|
|
72
|
-
|
|
73
|
-
### 配置选项
|
|
74
|
-
|
|
75
|
-
| 参数 | 类型 | 默认值 | 描述 |
|
|
76
|
-
|------|------|--------|---------|
|
|
77
|
-
| `width` | `number` | `350` | 验证码宽度 |
|
|
78
|
-
| `height` | `number` | `200` | 验证码高度 |
|
|
79
|
-
| `sliderSize` | `number` | `42` | 滑块大小 |
|
|
80
|
-
| `maxRetries` | `number` | `3` | 最大重试次数 |
|
|
81
|
-
| `timeout` | `number` | `30000` | 超时时间(ms) |
|
|
82
|
-
| `apiUrl` | `string` | `'/api/captcha'` | 获取验证码接口 |
|
|
83
|
-
| `verifyUrl` | `string` | `'/api/captcha/verify'` | 验证接口 |
|
|
84
|
-
| `onSuccess` | `function` | `undefined` | 验证成功回调 |
|
|
85
|
-
| `onFail` | `function` | `undefined` | 验证失败回调 |
|
|
86
|
-
| `onClose` | `function` | `undefined` | 关闭回调 |
|
|
87
|
-
|
|
88
|
-
### 实例方法
|
|
89
|
-
|
|
90
|
-
#### `show(): Promise<any>`
|
|
91
|
-
显示验证码弹窗
|
|
92
|
-
|
|
93
|
-
#### `hide(): void`
|
|
94
|
-
隐藏验证码弹窗
|
|
95
|
-
|
|
96
|
-
#### `refresh(): Promise<void>`
|
|
97
|
-
刷新验证码
|
|
98
|
-
|
|
99
|
-
#### `destroy(): void`
|
|
100
|
-
销毁实例,清理所有事件监听器
|
|
101
|
-
|
|
102
|
-
#### `reset(): void`
|
|
103
|
-
重置验证码状态
|
|
104
|
-
|
|
105
|
-
### 静态方法
|
|
106
|
-
|
|
107
|
-
#### `SliderCaptcha.create(options): PopupSliderCaptcha`
|
|
108
|
-
创建验证码实例
|
|
109
|
-
|
|
110
|
-
#### `SliderCaptcha.show(options): Promise<PopupSliderCaptcha>`
|
|
111
|
-
快速显示验证码
|
|
112
|
-
|
|
113
|
-
## 🔧 服务端接口
|
|
114
|
-
|
|
115
|
-
### 获取验证码 (GET /api/captcha)
|
|
116
|
-
|
|
117
|
-
**响应格式:**
|
|
118
|
-
```json
|
|
119
|
-
{
|
|
120
|
-
"id": "captcha_id",
|
|
121
|
-
"backgroundImage": "data:image/png;base64,...",
|
|
122
|
-
"sliderImage": "data:image/png;base64,...",
|
|
123
|
-
"y": 120
|
|
124
|
-
}
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
### 验证接口 (POST /api/captcha/verify)
|
|
128
|
-
|
|
129
|
-
**请求格式:**
|
|
130
|
-
```json
|
|
131
|
-
{
|
|
132
|
-
"id": "captcha_id",
|
|
133
|
-
"x": 200,
|
|
134
|
-
"times": [100, 200, 300]
|
|
135
|
-
}
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
**响应格式:**
|
|
139
|
-
```json
|
|
140
|
-
{
|
|
141
|
-
"success": true,
|
|
142
|
-
"message": "验证成功",
|
|
143
|
-
"token": "verification_token"
|
|
144
|
-
}
|
|
145
|
-
```
|
|
146
|
-
|
|
147
|
-
## 🎨 自定义样式
|
|
148
|
-
|
|
149
|
-
你可以通过CSS覆盖默认样式:
|
|
150
|
-
|
|
151
|
-
```css
|
|
152
|
-
.slider-captcha-modal {
|
|
153
|
-
border-radius: 12px;
|
|
154
|
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
.slider-captcha-btn {
|
|
158
|
-
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
|
|
159
|
-
}
|
|
160
|
-
```
|
|
161
|
-
|
|
162
|
-
## 📄 许可证
|
|
163
|
-
|
|
164
|
-
MIT License - 详见 [LICENSE](LICENSE) 文件
|
|
165
|
-
|
|
166
|
-
## 🤝 贡献
|
|
167
|
-
|
|
168
|
-
欢迎提交 Issue 和 Pull Request!
|
|
169
|
-
|
|
170
|
-
## 📞 支持
|
|
171
|
-
|
|
172
|
-
如果你觉得这个项目有用,请给它一个 ⭐️
|