wx-auth-sdk 1.1.1 → 1.1.4

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/wx-auth.js CHANGED
@@ -1,4 +1,4 @@
1
- const n = {
1
+ const r = {
2
2
  observer: null,
3
3
  healthCheckTimer: null,
4
4
  isProtected: !1
@@ -8,12 +8,12 @@ const n = {
8
8
  * @param config 配置选项
9
9
  */
10
10
  enable(e) {
11
- if (n.isProtected || typeof window > "u") return;
11
+ if (r.isProtected || typeof window > "u") return;
12
12
  const { modalId: t, getState: o } = e;
13
- n.observer = new MutationObserver((r) => {
14
- r.forEach((i) => {
15
- if (i.type === "childList")
16
- i.removedNodes.forEach((c) => {
13
+ r.observer = new MutationObserver((i) => {
14
+ i.forEach((n) => {
15
+ if (n.type === "childList")
16
+ n.removedNodes.forEach((c) => {
17
17
  if (c.nodeType === Node.ELEMENT_NODE) {
18
18
  const d = c;
19
19
  (d.id === t || d.querySelector?.(`#${t}`)) && (console.warn(
@@ -21,27 +21,27 @@ const n = {
21
21
  ), this.restore(e));
22
22
  }
23
23
  });
24
- else if (i.type === "attributes") {
25
- const c = i.target;
26
- c.id === t && i.attributeName === "style" && c.style.display === "none" && o().isOpen && (console.warn(
24
+ else if (n.type === "attributes") {
25
+ const c = n.target;
26
+ c.id === t && n.attributeName === "style" && c.style.display === "none" && o().isOpen && (console.warn(
27
27
  "[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."
28
28
  ), c.style.display = "flex");
29
29
  }
30
30
  });
31
- }), n.observer.observe(document.body, {
31
+ }), r.observer.observe(document.body, {
32
32
  childList: !0,
33
33
  subtree: !0,
34
34
  attributes: !0,
35
35
  attributeFilter: ["style"]
36
- }), n.healthCheckTimer = window.setInterval(() => {
36
+ }), r.healthCheckTimer = window.setInterval(() => {
37
37
  this.healthCheck(e);
38
- }, 1e3), n.isProtected = !0, console.log("[WxAuth] 弹窗保护已启用");
38
+ }, 1e3), r.isProtected = !0, console.log("[WxAuth] 弹窗保护已启用");
39
39
  },
40
40
  /**
41
41
  * 禁用弹窗保护
42
42
  */
43
43
  disable() {
44
- n.observer && (n.observer.disconnect(), n.observer = null), n.healthCheckTimer && (clearInterval(n.healthCheckTimer), n.healthCheckTimer = null), n.isProtected = !1, console.log("[WxAuth] 弹窗保护已禁用");
44
+ r.observer && (r.observer.disconnect(), r.observer = null), r.healthCheckTimer && (clearInterval(r.healthCheckTimer), r.healthCheckTimer = null), r.isProtected = !1, console.log("[WxAuth] 弹窗保护已禁用");
45
45
  },
46
46
  /**
47
47
  * 健康检查(定时器调用)
@@ -50,26 +50,26 @@ const n = {
50
50
  healthCheck(e) {
51
51
  const { modalId: t, getState: o } = e;
52
52
  if (!o().isOpen) return;
53
- const r = document.getElementById(t);
54
- if (!r) {
53
+ const i = document.getElementById(t);
54
+ if (!i) {
55
55
  console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."), this.restore(e);
56
56
  return;
57
57
  }
58
- r.style.display === "none" && (console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."), r.style.display = "flex");
58
+ i.style.display === "none" && (console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."), i.style.display = "flex");
59
59
  },
60
60
  /**
61
61
  * 恢复弹窗
62
62
  * @param config 配置选项
63
63
  */
64
64
  restore(e) {
65
- const { modalId: t, getState: o, onRestore: r } = e;
65
+ const { modalId: t, getState: o, onRestore: i } = e;
66
66
  if (!o().isOpen) return;
67
- const i = document.getElementById(t);
68
- if (i) {
69
- i.style.display = "flex";
67
+ const n = document.getElementById(t);
68
+ if (n) {
69
+ n.style.display = "flex";
70
70
  return;
71
71
  }
72
- r();
72
+ i();
73
73
  }
74
74
  }, p = {
75
75
  apiBase: "",
@@ -91,19 +91,37 @@ let s = { ...p }, a = {
91
91
  currentStep: "qr"
92
92
  };
93
93
  const l = {
94
+ // 从 apiBase 自动推导根域名(用于跨子域名共享 Cookie)
95
+ // wx-auth.shenzjd.com → .shenzjd.com
96
+ // parse.shenzjd.com → .shenzjd.com
97
+ // localhost / 127.0.0.1 / IP → 不设置 domain
98
+ getRootDomain() {
99
+ try {
100
+ const e = new URL(s.apiBase || window.location.origin).hostname;
101
+ if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
102
+ return "";
103
+ const t = e.split(".");
104
+ return t.length >= 2 ? "." + t.slice(-2).join(".") : "";
105
+ } catch {
106
+ return "";
107
+ }
108
+ },
94
109
  // 获取Cookie
95
110
  getCookie(e) {
96
111
  const o = `; ${document.cookie}`.split(`; ${e}=`);
97
112
  return o.length === 2 && o.pop()?.split(";").shift() || null;
98
113
  },
99
- // 设置Cookie(30天过期)
114
+ // 设置Cookie(30天过期,自动设置根域名实现跨子域共享)
100
115
  setCookie(e, t) {
101
116
  const o = /* @__PURE__ */ new Date();
102
- o.setTime(o.getTime() + 720 * 60 * 60 * 1e3), document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/`;
117
+ o.setTime(o.getTime() + 720 * 60 * 60 * 1e3);
118
+ const i = this.getRootDomain(), n = i ? `;domain=${i}` : "";
119
+ document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${n}`;
103
120
  },
104
- // 删除Cookie
121
+ // 删除Cookie(匹配相同的 domain)
105
122
  deleteCookie(e) {
106
- document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
123
+ const t = this.getRootDomain(), o = t ? `;domain=${t}` : "";
124
+ document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}`;
107
125
  },
108
126
  // 发送请求
109
127
  async request(e, t = {}) {
@@ -173,18 +191,18 @@ const l = {
173
191
  setTimeout(() => {
174
192
  const e = document.querySelectorAll(".wx-auth-input");
175
193
  e.length && e.forEach((t, o) => {
176
- t.addEventListener("input", (r) => {
177
- const i = r.target.value.replace(/\D/g, "");
178
- r.target.value = i, i && o < 5 && e[o + 1].focus(), o === 5 && i && setTimeout(() => h.verifyCode(), 300);
179
- }), t.addEventListener("keydown", (r) => {
180
- const i = r.target;
181
- r.key === "Backspace" && !i.value && o > 0 ? e[o - 1].focus() : r.key === "ArrowLeft" && o > 0 ? (r.preventDefault(), e[o - 1].focus()) : r.key === "ArrowRight" && o < 5 && (r.preventDefault(), e[o + 1].focus());
182
- }), t.addEventListener("paste", (r) => {
183
- r.preventDefault();
184
- const i = r.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
185
- i && (i.split("").forEach((c, d) => {
194
+ t.addEventListener("input", (i) => {
195
+ const n = i.target.value.replace(/\D/g, "");
196
+ i.target.value = n, n && o < 5 && e[o + 1].focus(), o === 5 && n && setTimeout(() => h.verifyCode(), 300);
197
+ }), t.addEventListener("keydown", (i) => {
198
+ const n = i.target;
199
+ i.key === "Backspace" && !n.value && o > 0 ? e[o - 1].focus() : i.key === "ArrowLeft" && o > 0 ? (i.preventDefault(), e[o - 1].focus()) : i.key === "ArrowRight" && o < 5 && (i.preventDefault(), e[o + 1].focus());
200
+ }), t.addEventListener("paste", (i) => {
201
+ i.preventDefault();
202
+ const n = i.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
203
+ n && (n.split("").forEach((c, d) => {
186
204
  e[d] && (e[d].value = c);
187
- }), i.length === 6 && setTimeout(() => h.verifyCode(), 300));
205
+ }), n.length === 6 && setTimeout(() => h.verifyCode(), 300));
188
206
  });
189
207
  });
190
208
  }, 100);
@@ -304,11 +322,11 @@ const l = {
304
322
  );
305
323
  t && (t.disabled = !0, t.textContent = "验证中...");
306
324
  try {
307
- const o = s.siteId ? `&siteId=${encodeURIComponent(s.siteId)}` : "", r = await l.request(
325
+ const o = s.siteId ? `&siteId=${encodeURIComponent(s.siteId)}` : "", i = await l.request(
308
326
  `${s.apiBase}/api/auth/check?authToken=${e}${o}`
309
327
  );
310
- r.authenticated ? (r.user && r.user.openid && l.setCookie("wxauth-openid", r.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
311
- this.close(), this.onVerified(r.user);
328
+ i.authenticated ? (i.user && i.user.openid && l.setCookie("wxauth-openid", i.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
329
+ this.close(), this.onVerified(i.user);
312
330
  }, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
313
331
  } catch {
314
332
  u.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
@@ -1,5 +1,5 @@
1
1
  (function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l.WxAuthSDK={}))})(this,(function(l){"use strict";var h=document.createElement("style");h.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:1;padding:0;position:absolute;right:10px;top:50%;transform:translateY(-50%);opacity:.8}.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:16px;font-weight:500}.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}}
2
- /*$vite$:1*/`,document.head.appendChild(h);const s={observer:null,healthCheckTimer:null,isProtected:!1},x={enable(e){if(s.isProtected||typeof window>"u")return;const{modalId:t,getState:o}=e;s.observer=new MutationObserver(i=>{i.forEach(a=>{if(a.type==="childList")a.removedNodes.forEach(u=>{if(u.nodeType===Node.ELEMENT_NODE){const p=u;(p.id===t||p.querySelector?.(`#${t}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(e))}});else if(a.type==="attributes"){const u=a.target;u.id===t&&a.attributeName==="style"&&u.style.display==="none"&&o().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),u.style.display="flex")}})}),s.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),s.healthCheckTimer=window.setInterval(()=>{this.healthCheck(e)},1e3),s.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){s.observer&&(s.observer.disconnect(),s.observer=null),s.healthCheckTimer&&(clearInterval(s.healthCheckTimer),s.healthCheckTimer=null),s.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(!i){console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),this.restore(e);return}i.style.display==="none"&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),i.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:i}=e;if(!o().isOpen)return;const a=document.getElementById(t);if(a){a.style.display="flex";return}i()}},w={apiBase:"",siteId:"",onVerified:null,onError:null,wechatName:"公众号",qrcodeUrl:""};let n={...w},r={isOpen:!1,resolveAuth:null,currentStep:"qr"};const d={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()+720*60*60*1e3),document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/`},deleteCookie(e){document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`},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}},c={createModal(){const e=document.createElement("div");return e.id="wx-auth-modal",e.className="wx-auth-modal",e.innerHTML=`
2
+ /*$vite$:1*/`,document.head.appendChild(h);const s={observer:null,healthCheckTimer:null,isProtected:!1},x={enable(e){if(s.isProtected||typeof window>"u")return;const{modalId:t,getState:o}=e;s.observer=new MutationObserver(i=>{i.forEach(a=>{if(a.type==="childList")a.removedNodes.forEach(u=>{if(u.nodeType===Node.ELEMENT_NODE){const p=u;(p.id===t||p.querySelector?.(`#${t}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(e))}});else if(a.type==="attributes"){const u=a.target;u.id===t&&a.attributeName==="style"&&u.style.display==="none"&&o().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),u.style.display="flex")}})}),s.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),s.healthCheckTimer=window.setInterval(()=>{this.healthCheck(e)},1e3),s.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){s.observer&&(s.observer.disconnect(),s.observer=null),s.healthCheckTimer&&(clearInterval(s.healthCheckTimer),s.healthCheckTimer=null),s.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(!i){console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),this.restore(e);return}i.style.display==="none"&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),i.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:i}=e;if(!o().isOpen)return;const a=document.getElementById(t);if(a){a.style.display="flex";return}i()}},w={apiBase:"",siteId:"",onVerified:null,onError:null,wechatName:"公众号",qrcodeUrl:""};let n={...w},r={isOpen:!1,resolveAuth:null,currentStep:"qr"};const d={getRootDomain(){try{const e=new URL(n.apiBase||window.location.origin).hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}},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()+720*60*60*1e3);const i=this.getRootDomain(),a=i?`;domain=${i}`:"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${a}`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}`},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}},c={createModal(){const e=document.createElement("div");return e.id="wx-auth-modal",e.className="wx-auth-modal",e.innerHTML=`
3
3
  <div class="wx-auth-overlay"></div>
4
4
  <div class="wx-auth-content">
5
5
  <div class="wx-auth-header">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.1.1",
3
+ "version": "1.1.4",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",