wx-auth-sdk 1.2.22 → 1.2.23

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.d.ts CHANGED
@@ -3,7 +3,10 @@ export declare const WxAuth: {
3
3
  /**
4
4
  * 静默验证(silent 模式专用)
5
5
  * - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
6
- * - cookie 无效 / 不存在 → deleteCookie,不调 showAuthModal
6
+ * - cookie 无效 / 不存在 → 不清 cookie、不弹窗,仅返回 false
7
+ * (2026-08-28:不再 deleteCookie。失效 cookie 保留,供后端识别"有凭证但
8
+ * 失效"(取关)→ 返回 401 → 前端弹认证弹窗;后端通过有无 cookie 区分
9
+ * "页面用户取关"(401)与"无凭证爬虫"(蜜罐假数据))
7
10
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
8
11
  */
9
12
  silentCheck(): Promise<boolean>;
package/dist/wx-auth.js CHANGED
@@ -104,7 +104,7 @@ const i = {
104
104
  silent: !1
105
105
  // 默认不静默
106
106
  };
107
- let s = { ...w }, c = "", l = {
107
+ let s = { ...w }, a = "", l = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
110
  currentStep: "qr"
@@ -119,7 +119,7 @@ function p(e) {
119
119
  return "";
120
120
  }
121
121
  }
122
- const a = {
122
+ const c = {
123
123
  getRootDomain() {
124
124
  return p(window.location.hostname);
125
125
  },
@@ -227,7 +227,7 @@ const a = {
227
227
  <div>
228
228
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
229
229
  <div class="wx-auth-note">保持关注,即可一直自动登录</div>
230
- ${a.generateCodeInputs()}
230
+ ${c.generateCodeInputs()}
231
231
  </div>
232
232
 
233
233
  <!-- 消息提示 -->
@@ -321,43 +321,46 @@ const a = {
321
321
  const t = document.referrer;
322
322
  if (t)
323
323
  try {
324
- c = new URL(t).hostname;
324
+ a = new URL(t).hostname;
325
325
  } catch {
326
326
  }
327
- !c && window.location.hostname && (c = window.location.hostname), c || (c = "default"), console.log("[WxAuth] 自动获取 siteId:", c);
327
+ !a && window.location.hostname && (a = window.location.hostname), a || (a = "default"), console.log("[WxAuth] 自动获取 siteId:", a);
328
328
  }
329
329
  console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
330
330
  },
331
331
  /**
332
332
  * 静默验证(silent 模式专用)
333
333
  * - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
334
- * - cookie 无效 / 不存在 → deleteCookie,不调 showAuthModal
334
+ * - cookie 无效 / 不存在 → 不清 cookie、不弹窗,仅返回 false
335
+ * (2026-08-28:不再 deleteCookie。失效 cookie 保留,供后端识别"有凭证但
336
+ * 失效"(取关)→ 返回 401 → 前端弹认证弹窗;后端通过有无 cookie 区分
337
+ * "页面用户取关"(401)与"无凭证爬虫"(蜜罐假数据))
335
338
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
336
339
  */
337
340
  async silentCheck() {
338
- const e = a.getToken();
341
+ const e = c.getToken();
339
342
  if (!e) return !1;
340
- const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`;
343
+ const t = a ? `&siteId=${encodeURIComponent(a)}` : "", o = `token=${encodeURIComponent(e)}`;
341
344
  try {
342
- const n = await a.request(
345
+ const n = await c.request(
343
346
  `${s.apiBase}/api/auth/check?${o}${t}`
344
347
  );
345
- return n.authenticated ? (n.token && a.setToken(n.token), this.onVerified(n.user), !0) : (a.clearToken(), !1);
348
+ return n.authenticated ? (n.token && c.setToken(n.token), this.onVerified(n.user), !0) : !1;
346
349
  } catch (n) {
347
350
  return console.error("[WxAuth] silentCheck 请求失败:", n), !1;
348
351
  }
349
352
  },
350
353
  // 自动检测凭证并验证(内部使用)
351
354
  async autoCheck() {
352
- const e = a.getToken();
355
+ const e = c.getToken();
353
356
  if (!e)
354
357
  return this.showAuthModal(), !1;
355
- const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`;
358
+ const t = a ? `&siteId=${encodeURIComponent(a)}` : "", o = `token=${encodeURIComponent(e)}`;
356
359
  try {
357
- const n = await a.request(
360
+ const n = await c.request(
358
361
  `${s.apiBase}/api/auth/check?${o}${t}`
359
362
  );
360
- return n.authenticated ? (console.log("[WxAuth] 自动认证成功(凭证)"), n.token && a.setToken(n.token), this.onVerified(n.user), !0) : (a.clearToken(), this.showAuthModal(), !1);
363
+ return n.authenticated ? (console.log("[WxAuth] 自动认证成功(凭证)"), n.token && c.setToken(n.token), this.onVerified(n.user), !0) : (this.showAuthModal(), !1);
361
364
  } catch (n) {
362
365
  return console.error("[WxAuth] 自动验证失败:", n), this.showAuthModal(), !1;
363
366
  }
@@ -366,7 +369,7 @@ const a = {
366
369
  async showAuthModal() {
367
370
  d.show();
368
371
  try {
369
- const t = c ? `?siteId=${encodeURIComponent(c)}` : "", o = await a.request(
372
+ const t = a ? `?siteId=${encodeURIComponent(a)}` : "", o = await c.request(
370
373
  `${s.apiBase}/api/sdk/config${t}`
371
374
  );
372
375
  o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
@@ -383,15 +386,14 @@ const a = {
383
386
  // 主入口:需要验证时调用
384
387
  // 凭证仅签名 Token(Cookie 优先 + localStorage 兜底),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
385
388
  async requireAuth() {
386
- const e = a.getToken();
389
+ const e = c.getToken();
387
390
  if (e)
388
391
  try {
389
- const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`, n = await a.request(
392
+ const t = a ? `&siteId=${encodeURIComponent(a)}` : "", o = `token=${encodeURIComponent(e)}`, n = await c.request(
390
393
  `${s.apiBase}/api/auth/check?${o}${t}`
391
394
  );
392
395
  if (n.authenticated)
393
- return console.log("[WxAuth] 已认证(凭证)"), n.token && a.setToken(n.token), this.onVerified(n.user), !0;
394
- a.clearToken();
396
+ return console.log("[WxAuth] 已认证(凭证)"), n.token && c.setToken(n.token), this.onVerified(n.user), !0;
395
397
  } catch (t) {
396
398
  console.error("[WxAuth] 凭证检查失败:", t);
397
399
  }
@@ -411,10 +413,10 @@ const a = {
411
413
  );
412
414
  t && (t.disabled = !0, t.textContent = "登录中...");
413
415
  try {
414
- const o = c ? `&siteId=${encodeURIComponent(c)}` : "", n = await a.request(
416
+ const o = a ? `&siteId=${encodeURIComponent(a)}` : "", n = await c.request(
415
417
  `${s.apiBase}/api/auth/check?authToken=${e}${o}`
416
418
  );
417
- n.authenticated ? (n.token && a.setToken(n.token), t && (t.textContent = "✅ 已登录", t.style.background = "#07C160"), setTimeout(() => {
419
+ n.authenticated ? (n.token && c.setToken(n.token), t && (t.textContent = "✅ 已登录", t.style.background = "#07C160"), setTimeout(() => {
418
420
  this.onVerified(n.user), this.close(!0);
419
421
  }, 500)) : (d.showMessage("验证码错误或已过期", "error"), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
420
422
  } catch {
@@ -433,7 +435,7 @@ const a = {
433
435
  // SDK 会凭备份静默恢复(getToken 优先 Cookie、localStorage 兜底),
434
436
  // 造成"清不掉"的假象——所以必须走这里而非只删 Cookie。
435
437
  clearToken() {
436
- a.clearToken();
438
+ c.clearToken();
437
439
  },
438
440
  // 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
439
441
  // 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
@@ -442,7 +444,7 @@ const a = {
442
444
  // 幂等安全:网络失败 /* 后端不可达 */ 时静默降级为仅本地清理(clearToken),
443
445
  // 不阻塞退出流程;token 无效也会返回 success(本地照常清理)。
444
446
  async revoke() {
445
- const e = a.getToken();
447
+ const e = c.getToken();
446
448
  if (e)
447
449
  try {
448
450
  const t = s.apiBase && !/\/$/.test(s.apiBase) ? s.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
@@ -1,5 +1,5 @@
1
1
  (function(f,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(f=typeof globalThis<"u"?globalThis:f||self,p(f.WxAuthSDK={}))})(this,(function(f){"use strict";var p=document.createElement("style");p.textContent=`.wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:30px;padding:0;opacity:.85;flex-shrink:0}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:4px;font-weight:500}.wx-auth-note{font-size:12px;color:#888;margin-bottom:14px;line-height:1.4;white-space:nowrap}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}.wx-auth-note{color:#aaa}.wx-auth-input{background:#2a2a2a;border-color:#444;color:#e5e5e5}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16040}.wx-auth-input:disabled{background:#333;color:#888}.wx-auth-qrcode-container{background:#2a2a2a}.wx-auth-btn-secondary{background:#2a2a2a;color:#e5e5e5}.wx-auth-btn-secondary:hover:not(:disabled){background:#333}.wx-auth-message-info{background:#0d2a1f;color:#7cc4ff;border-color:#1f4a6b}.wx-auth-message-success{background:#0d2a1a;color:#4ade80;border-color:#1f6b3a}.wx-auth-message-error{background:#2a0d0d;color:#f87171;border-color:#6b1f1f}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
2
- /*$vite$:1*/`,document.head.appendChild(p);const a={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(a.isProtected||typeof window>"u")return;a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!0,a.restorePending=!1,a.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const i of n.removedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;const l=i;if(l.id===e.modalId||l.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.safeRestore(e);return}}}),a.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!a.isProtected)return;const{getState:o}=e;if(!o().isOpen){a.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||h.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?h.isHidden(n):null}),h.safeRestore(e)),a.isProtected&&(a.rafId=requestAnimationFrame(t))};a.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!1,a.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!a.restorePending){a.restorePending=!0;try{h.restoreFn(e)}finally{requestAnimationFrame(()=>{a.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(i){i.style.display="flex",i.style.visibility="visible",i.style.opacity="1";return}n()}},m={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let r={...m},c="",u={isOpen:!1,resolveAuth:null,currentStep:"qr"};function g(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const s={getRootDomain(){return g(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+365*24*60*60*1e3);const n=this.getRootDomain(),i=n?`;domain=${n}`:"",w=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${i}${w};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",i=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${i};SameSite=Strict`},get storageKey(){return"wxauth-token"},getToken(){const e=this.getCookie("wxauth-token");if(e)return e;try{return window.localStorage.getItem(this.storageKey)}catch{return null}},setToken(e){this.setCookie("wxauth-token",e);try{window.localStorage.setItem(this.storageKey,e)}catch{}},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem(this.storageKey)}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},d={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=r.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
2
+ /*$vite$:1*/`,document.head.appendChild(p);const a={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(a.isProtected||typeof window>"u")return;a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!0,a.restorePending=!1,a.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const i of n.removedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;const l=i;if(l.id===e.modalId||l.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.safeRestore(e);return}}}),a.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!a.isProtected)return;const{getState:o}=e;if(!o().isOpen){a.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||h.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?h.isHidden(n):null}),h.safeRestore(e)),a.isProtected&&(a.rafId=requestAnimationFrame(t))};a.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!1,a.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!a.restorePending){a.restorePending=!0;try{h.restoreFn(e)}finally{requestAnimationFrame(()=>{a.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(i){i.style.display="flex",i.style.visibility="visible",i.style.opacity="1";return}n()}},m={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let r={...m},s="",u={isOpen:!1,resolveAuth:null,currentStep:"qr"};function g(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const c={getRootDomain(){return g(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+365*24*60*60*1e3);const n=this.getRootDomain(),i=n?`;domain=${n}`:"",w=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${i}${w};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",i=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${i};SameSite=Strict`},get storageKey(){return"wxauth-token"},getToken(){const e=this.getCookie("wxauth-token");if(e)return e;try{return window.localStorage.getItem(this.storageKey)}catch{return null}},setToken(e){this.setCookie("wxauth-token",e);try{window.localStorage.setItem(this.storageKey,e)}catch{}},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem(this.storageKey)}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},d={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=r.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
3
3
  <div class="wx-auth-overlay" ${r.required?'onclick="event.preventDefault()"':""}></div>
4
4
  <div class="wx-auth-content">
5
5
  <div class="wx-auth-header">
@@ -19,7 +19,7 @@
19
19
  <div>
20
20
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
21
21
  <div class="wx-auth-note">保持关注,即可一直自动登录</div>
22
- ${s.generateCodeInputs()}
22
+ ${c.generateCodeInputs()}
23
23
  </div>
24
24
 
25
25
  <!-- 消息提示 -->
@@ -31,4 +31,4 @@
31
31
  </div>
32
32
  </div>
33
33
  </div>
34
- `,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const i=n.target.value.replace(/\D/g,"");n.target.value=i,i&&o<5&&e[o+1].focus(),o===5&&i&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const i=n.target;n.key==="Backspace"&&!i.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const i=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);i&&(i.split("").forEach((l,w)=>{e[w]&&(e[w].value=l)}),i.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(i=>i.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),e.style.display="flex",u.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),r.qrcodeUrl&&this.setQrCode(r.qrcodeUrl);const i=document.querySelector(".wx-auth-wechat-name");i&&r.wechatName&&(i.textContent=`"${r.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const l=document.querySelector(".wx-auth-input");l&&l.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",u.isOpen=!1,h.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},x={init(e={}){if(r={...m,...e},!r.apiBase&&typeof window<"u"&&(r.apiBase=window.location.origin),!r.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{c=new URL(t).hostname}catch{}!c&&window.location.hostname&&(c=window.location.hostname),c||(c="default"),console.log("[WxAuth] 自动获取 siteId:",c)}console.log("[WxAuth] SDK initialized",r),typeof window<"u"&&(r.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=s.getToken();if(!e)return!1;const t=c?`&siteId=${encodeURIComponent(c)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await s.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(n.token&&s.setToken(n.token),this.onVerified(n.user),!0):(s.clearToken(),!1)}catch(n){return console.error("[WxAuth] silentCheck 请求失败:",n),!1}},async autoCheck(){const e=s.getToken();if(!e)return this.showAuthModal(),!1;const t=c?`&siteId=${encodeURIComponent(c)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await s.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(console.log("[WxAuth] 自动认证成功(凭证)"),n.token&&s.setToken(n.token),this.onVerified(n.user),!0):(s.clearToken(),this.showAuthModal(),!1)}catch(n){return console.error("[WxAuth] 自动验证失败:",n),this.showAuthModal(),!1}},async showAuthModal(){d.show();try{const t=c?`?siteId=${encodeURIComponent(c)}`:"",o=await s.request(`${r.apiBase}/api/sdk/config${t}`);o.wechatName&&!r.wechatName&&(r.wechatName=o.wechatName),o.qrcodeUrl&&!r.qrcodeUrl&&(r.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}r.qrcodeUrl&&d.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&r.wechatName&&(e.textContent=`"${r.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=s.getToken();if(e)try{const t=c?`&siteId=${encodeURIComponent(c)}`:"",o=`token=${encodeURIComponent(e)}`,n=await s.request(`${r.apiBase}/api/auth/check?${o}${t}`);if(n.authenticated)return console.log("[WxAuth] 已认证(凭证)"),n.token&&s.setToken(n.token),this.onVerified(n.user),!0;s.clearToken()}catch(t){console.error("[WxAuth] 凭证检查失败:",t)}return await this.showAuthModal(),new Promise(t=>{u.resolveAuth=t})},async verifyCode(){const e=d.getVerifyCode();if(!e||e.length!==6){d.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=c?`&siteId=${encodeURIComponent(c)}`:"",n=await s.request(`${r.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token&&s.setToken(n.token),t&&(t.textContent="✅ 已登录",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(d.showMessage("验证码错误或已过期","error"),d.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch{d.showMessage("登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){d.hide(),u.resolveAuth&&(u.resolveAuth(!1),u.resolveAuth=null),!e&&typeof r.onClose=="function"&&r.onClose()},clearToken(){s.clearToken()},async revoke(){const e=s.getToken();if(e)try{const t=r.apiBase&&!/\/$/.test(r.apiBase)?r.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof r.onVerified=="function"&&r.onVerified(e),u.resolveAuth&&(u.resolveAuth(!0),u.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof r.onError=="function"&&r.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),f.WxAuth=x,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
34
+ `,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const i=n.target.value.replace(/\D/g,"");n.target.value=i,i&&o<5&&e[o+1].focus(),o===5&&i&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const i=n.target;n.key==="Backspace"&&!i.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const i=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);i&&(i.split("").forEach((l,w)=>{e[w]&&(e[w].value=l)}),i.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(i=>i.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),e.style.display="flex",u.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),r.qrcodeUrl&&this.setQrCode(r.qrcodeUrl);const i=document.querySelector(".wx-auth-wechat-name");i&&r.wechatName&&(i.textContent=`"${r.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const l=document.querySelector(".wx-auth-input");l&&l.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",u.isOpen=!1,h.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},x={init(e={}){if(r={...m,...e},!r.apiBase&&typeof window<"u"&&(r.apiBase=window.location.origin),!r.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{s=new URL(t).hostname}catch{}!s&&window.location.hostname&&(s=window.location.hostname),s||(s="default"),console.log("[WxAuth] 自动获取 siteId:",s)}console.log("[WxAuth] SDK initialized",r),typeof window<"u"&&(r.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=s?`&siteId=${encodeURIComponent(s)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await c.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(n.token&&c.setToken(n.token),this.onVerified(n.user),!0):!1}catch(n){return console.error("[WxAuth] silentCheck 请求失败:",n),!1}},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=s?`&siteId=${encodeURIComponent(s)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await c.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(console.log("[WxAuth] 自动认证成功(凭证)"),n.token&&c.setToken(n.token),this.onVerified(n.user),!0):(this.showAuthModal(),!1)}catch(n){return console.error("[WxAuth] 自动验证失败:",n),this.showAuthModal(),!1}},async showAuthModal(){d.show();try{const t=s?`?siteId=${encodeURIComponent(s)}`:"",o=await c.request(`${r.apiBase}/api/sdk/config${t}`);o.wechatName&&!r.wechatName&&(r.wechatName=o.wechatName),o.qrcodeUrl&&!r.qrcodeUrl&&(r.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}r.qrcodeUrl&&d.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&r.wechatName&&(e.textContent=`"${r.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=c.getToken();if(e)try{const t=s?`&siteId=${encodeURIComponent(s)}`:"",o=`token=${encodeURIComponent(e)}`,n=await c.request(`${r.apiBase}/api/auth/check?${o}${t}`);if(n.authenticated)return console.log("[WxAuth] 已认证(凭证)"),n.token&&c.setToken(n.token),this.onVerified(n.user),!0}catch(t){console.error("[WxAuth] 凭证检查失败:",t)}return await this.showAuthModal(),new Promise(t=>{u.resolveAuth=t})},async verifyCode(){const e=d.getVerifyCode();if(!e||e.length!==6){d.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=s?`&siteId=${encodeURIComponent(s)}`:"",n=await c.request(`${r.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token&&c.setToken(n.token),t&&(t.textContent="✅ 已登录",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(d.showMessage("验证码错误或已过期","error"),d.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch{d.showMessage("登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){d.hide(),u.resolveAuth&&(u.resolveAuth(!1),u.resolveAuth=null),!e&&typeof r.onClose=="function"&&r.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=r.apiBase&&!/\/$/.test(r.apiBase)?r.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof r.onVerified=="function"&&r.onVerified(e),u.resolveAuth&&(u.resolveAuth(!0),u.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof r.onError=="function"&&r.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),f.WxAuth=x,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.22",
3
+ "version": "1.2.23",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",