wx-auth-sdk 1.2.19 → 1.2.21

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,61 +1,61 @@
1
- const s = {
1
+ const i = {
2
2
  observer: null,
3
3
  rafId: null,
4
4
  isProtected: !1,
5
5
  restorePending: !1
6
- }, d = {
6
+ }, h = {
7
7
  /**
8
8
  * 启用弹窗保护
9
9
  */
10
10
  enable(e) {
11
- if (s.isProtected || typeof window > "u") return;
12
- s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !0, s.restorePending = !1, s.observer = new MutationObserver((o) => {
11
+ if (i.isProtected || typeof window > "u") return;
12
+ i.observer && (i.observer.disconnect(), i.observer = null), i.rafId !== null && (cancelAnimationFrame(i.rafId), i.rafId = null), i.isProtected = !0, i.restorePending = !1, i.observer = new MutationObserver((o) => {
13
13
  for (const n of o)
14
14
  if (n.type === "childList")
15
- for (const i of n.removedNodes) {
16
- if (i.nodeType !== Node.ELEMENT_NODE) continue;
17
- const h = i;
18
- if (h.id === e.modalId || h.querySelector?.(`#${e.modalId}`)) {
19
- console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), d.safeRestore(e);
15
+ for (const r of n.removedNodes) {
16
+ if (r.nodeType !== Node.ELEMENT_NODE) continue;
17
+ const u = r;
18
+ if (u.id === e.modalId || u.querySelector?.(`#${e.modalId}`)) {
19
+ console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
20
20
  return;
21
21
  }
22
22
  }
23
- }), s.observer.observe(document.body, {
23
+ }), i.observer.observe(document.body, {
24
24
  childList: !0,
25
25
  subtree: !0
26
26
  });
27
27
  const t = () => {
28
- if (!s.isProtected) return;
28
+ if (!i.isProtected) return;
29
29
  const { getState: o } = e;
30
30
  if (!o().isOpen) {
31
- s.rafId = null;
31
+ i.rafId = null;
32
32
  return;
33
33
  }
34
34
  const n = document.getElementById(e.modalId);
35
- (!n || !n.isConnected || d.isHidden(n)) && (console.warn(
35
+ (!n || !n.isConnected || h.isHidden(n)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
- { has: !!n, connected: n?.isConnected, hidden: n ? d.isHidden(n) : null }
38
- ), d.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
37
+ { has: !!n, connected: n?.isConnected, hidden: n ? h.isHidden(n) : null }
38
+ ), h.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
39
39
  };
40
- s.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
40
+ i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
41
41
  },
42
42
  /**
43
43
  * 禁用弹窗保护
44
44
  */
45
45
  disable() {
46
- s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !1, s.restorePending = !1, console.log("[WxAuth] 弹窗保护已禁用");
46
+ i.observer && (i.observer.disconnect(), i.observer = null), i.rafId !== null && (cancelAnimationFrame(i.rafId), i.rafId = null), i.isProtected = !1, i.restorePending = !1, console.log("[WxAuth] 弹窗保护已禁用");
47
47
  },
48
48
  /**
49
49
  * 同一帧内避免重复恢复
50
50
  */
51
51
  safeRestore(e) {
52
- if (!s.restorePending) {
53
- s.restorePending = !0;
52
+ if (!i.restorePending) {
53
+ i.restorePending = !0;
54
54
  try {
55
- d.restoreFn(e);
55
+ h.restoreFn(e);
56
56
  } finally {
57
57
  requestAnimationFrame(() => {
58
- s.restorePending = !1;
58
+ i.restorePending = !1;
59
59
  });
60
60
  }
61
61
  }
@@ -79,9 +79,9 @@ const s = {
79
79
  restoreFn(e) {
80
80
  const { modalId: t, getState: o, onRestore: n } = e;
81
81
  if (!o().isOpen) return;
82
- const i = document.getElementById(t);
83
- if (i) {
84
- i.style.display = "flex", i.style.visibility = "visible", i.style.opacity = "1";
82
+ const r = document.getElementById(t);
83
+ if (r) {
84
+ r.style.display = "flex", r.style.visibility = "visible", r.style.opacity = "1";
85
85
  return;
86
86
  }
87
87
  n();
@@ -104,7 +104,7 @@ const s = {
104
104
  silent: !1
105
105
  // 默认不静默
106
106
  };
107
- let r = { ...w }, c = "", l = {
107
+ let s = { ...w }, c = "", l = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
110
  currentStep: "qr"
@@ -132,13 +132,13 @@ const a = {
132
132
  setCookie(e, t) {
133
133
  const o = /* @__PURE__ */ new Date();
134
134
  o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
135
- const n = this.getRootDomain(), i = n ? `;domain=${n}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
136
- document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${i}${f};SameSite=Strict`;
135
+ const n = this.getRootDomain(), r = n ? `;domain=${n}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
136
+ document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${r}${f};SameSite=Strict`;
137
137
  },
138
138
  // 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
139
139
  deleteCookie(e) {
140
- const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", i = window.location.protocol === "https:" ? ";Secure" : "";
141
- document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${i};SameSite=Strict`;
140
+ const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", r = window.location.protocol === "https:" ? ";Secure" : "";
141
+ document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`;
142
142
  },
143
143
  // ===== 签名 Token 双存储(Cookie 主 + localStorage 备份) =====
144
144
  // 目标:用户清除 Cookie 后,若服务端认证状态仍有效,可凭备份静默恢复。
@@ -201,14 +201,14 @@ const a = {
201
201
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
202
202
  return e += "</div>", e;
203
203
  }
204
- }, u = {
204
+ }, d = {
205
205
  // 创建弹窗
206
206
  createModal() {
207
207
  const e = document.createElement("div");
208
- e.id = "wx-auth-modal", e.className = "wx-auth-modal", r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
209
- const t = r.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
208
+ e.id = "wx-auth-modal", e.className = "wx-auth-modal", s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
209
+ const t = s.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
210
210
  return e.innerHTML = `
211
- <div class="wx-auth-overlay" ${r.required ? 'onclick="event.preventDefault()"' : ""}></div>
211
+ <div class="wx-auth-overlay" ${s.required ? 'onclick="event.preventDefault()"' : ""}></div>
212
212
  <div class="wx-auth-content">
213
213
  <div class="wx-auth-header">
214
214
  <div class="wx-auth-title">微信登录</div>
@@ -247,17 +247,17 @@ const a = {
247
247
  const e = document.querySelectorAll(".wx-auth-input");
248
248
  e.length && e.forEach((t, o) => {
249
249
  t.addEventListener("input", (n) => {
250
- const i = n.target.value.replace(/\D/g, "");
251
- n.target.value = i, i && o < 5 && e[o + 1].focus(), o === 5 && i && setTimeout(() => m.verifyCode(), 300);
250
+ const r = n.target.value.replace(/\D/g, "");
251
+ n.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => m.verifyCode(), 300);
252
252
  }), t.addEventListener("keydown", (n) => {
253
- const i = n.target;
254
- 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());
253
+ const r = n.target;
254
+ n.key === "Backspace" && !r.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());
255
255
  }), t.addEventListener("paste", (n) => {
256
256
  n.preventDefault();
257
- const i = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
258
- i && (i.split("").forEach((h, f) => {
259
- e[f] && (e[f].value = h);
260
- }), i.length === 6 && setTimeout(() => m.verifyCode(), 300));
257
+ const r = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
258
+ r && (r.split("").forEach((u, f) => {
259
+ e[f] && (e[f].value = u);
260
+ }), r.length === 6 && setTimeout(() => m.verifyCode(), 300));
261
261
  });
262
262
  });
263
263
  }, 100);
@@ -265,15 +265,19 @@ const a = {
265
265
  // 显示弹窗
266
266
  show() {
267
267
  let e = document.getElementById("wx-auth-modal");
268
- 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.style.display = "flex", l.isOpen = !0, d.enable({
268
+ e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.querySelectorAll(".wx-auth-input").forEach((r) => r.value = "");
269
+ const o = e.querySelector(".wx-auth-message");
270
+ o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
271
+ const n = e.querySelector(".wx-auth-btn-primary");
272
+ n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), e.style.display = "flex", l.isOpen = !0, h.enable({
269
273
  modalId: "wx-auth-modal",
270
274
  getState: () => l,
271
275
  onRestore: () => {
272
- this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
273
- const t = document.querySelector(".wx-auth-wechat-name");
274
- t && r.wechatName && (t.textContent = `"${r.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
275
- const o = document.querySelector(".wx-auth-input");
276
- o && o.focus();
276
+ this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
277
+ const r = document.querySelector(".wx-auth-wechat-name");
278
+ r && s.wechatName && (r.textContent = `"${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
279
+ const u = document.querySelector(".wx-auth-input");
280
+ u && u.focus();
277
281
  }, 100);
278
282
  }
279
283
  });
@@ -281,7 +285,7 @@ const a = {
281
285
  // 隐藏弹窗
282
286
  hide() {
283
287
  const e = document.getElementById("wx-auth-modal");
284
- e && (e.style.display = "none", l.isOpen = !1, d.disable());
288
+ e && (e.style.display = "none", l.isOpen = !1, h.disable());
285
289
  },
286
290
  // 设置二维码
287
291
  setQrCode(e) {
@@ -309,7 +313,7 @@ const a = {
309
313
  }, m = {
310
314
  // 初始化
311
315
  init(e = {}) {
312
- if (r = { ...w, ...e }, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
316
+ if (s = { ...w, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
313
317
  console.error("[WxAuth] apiBase is required");
314
318
  return;
315
319
  }
@@ -322,7 +326,7 @@ const a = {
322
326
  }
323
327
  !c && window.location.hostname && (c = window.location.hostname), c || (c = "default"), console.log("[WxAuth] 自动获取 siteId:", c);
324
328
  }
325
- console.log("[WxAuth] SDK initialized", r), typeof window < "u" && (r.silent ? this.silentCheck() : this.autoCheck());
329
+ console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
326
330
  },
327
331
  /**
328
332
  * 静默验证(silent 模式专用)
@@ -336,7 +340,7 @@ const a = {
336
340
  const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`;
337
341
  try {
338
342
  const n = await a.request(
339
- `${r.apiBase}/api/auth/check?${o}${t}`
343
+ `${s.apiBase}/api/auth/check?${o}${t}`
340
344
  );
341
345
  return n.authenticated ? (n.token && a.setToken(n.token), this.onVerified(n.user), !0) : (a.clearToken(), !1);
342
346
  } catch (n) {
@@ -351,7 +355,7 @@ const a = {
351
355
  const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`;
352
356
  try {
353
357
  const n = await a.request(
354
- `${r.apiBase}/api/auth/check?${o}${t}`
358
+ `${s.apiBase}/api/auth/check?${o}${t}`
355
359
  );
356
360
  return n.authenticated ? (console.log("[WxAuth] 自动认证成功(凭证)"), n.token && a.setToken(n.token), this.onVerified(n.user), !0) : (a.clearToken(), this.showAuthModal(), !1);
357
361
  } catch (n) {
@@ -360,18 +364,18 @@ const a = {
360
364
  },
361
365
  // 显示认证弹窗(内部使用)
362
366
  async showAuthModal() {
363
- u.show();
367
+ d.show();
364
368
  try {
365
369
  const t = c ? `?siteId=${encodeURIComponent(c)}` : "", o = await a.request(
366
- `${r.apiBase}/api/sdk/config${t}`
370
+ `${s.apiBase}/api/sdk/config${t}`
367
371
  );
368
- o.wechatName && !r.wechatName && (r.wechatName = o.wechatName), o.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = o.qrcodeUrl);
372
+ o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
369
373
  } catch (t) {
370
374
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
371
375
  }
372
- r.qrcodeUrl && u.setQrCode(r.qrcodeUrl);
376
+ s.qrcodeUrl && d.setQrCode(s.qrcodeUrl);
373
377
  const e = document.querySelector(".wx-auth-wechat-name");
374
- e && r.wechatName && (e.textContent = `"${r.wechatName}"`), setTimeout(() => {
378
+ e && s.wechatName && (e.textContent = `"${s.wechatName}"`), setTimeout(() => {
375
379
  const t = document.querySelector(".wx-auth-input");
376
380
  t && t.focus();
377
381
  }, 100);
@@ -383,7 +387,7 @@ const a = {
383
387
  if (e)
384
388
  try {
385
389
  const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`, n = await a.request(
386
- `${r.apiBase}/api/auth/check?${o}${t}`
390
+ `${s.apiBase}/api/auth/check?${o}${t}`
387
391
  );
388
392
  if (n.authenticated)
389
393
  return console.log("[WxAuth] 已认证(凭证)"), n.token && a.setToken(n.token), this.onVerified(n.user), !0;
@@ -397,9 +401,9 @@ const a = {
397
401
  },
398
402
  // 验证验证码
399
403
  async verifyCode() {
400
- const e = u.getVerifyCode();
404
+ const e = d.getVerifyCode();
401
405
  if (!e || e.length !== 6) {
402
- u.showMessage("请输入6位验证码", "error");
406
+ d.showMessage("请输入6位验证码", "error");
403
407
  return;
404
408
  }
405
409
  const t = document.querySelector(
@@ -408,20 +412,20 @@ const a = {
408
412
  t && (t.disabled = !0, t.textContent = "登录中...");
409
413
  try {
410
414
  const o = c ? `&siteId=${encodeURIComponent(c)}` : "", n = await a.request(
411
- `${r.apiBase}/api/auth/check?authToken=${e}${o}`
415
+ `${s.apiBase}/api/auth/check?authToken=${e}${o}`
412
416
  );
413
417
  n.authenticated ? (n.token && a.setToken(n.token), t && (t.textContent = "✅ 已登录", t.style.background = "#07C160"), setTimeout(() => {
414
418
  this.onVerified(n.user), this.close(!0);
415
- }, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
419
+ }, 500)) : (d.showMessage("验证码错误或已过期", "error"), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
416
420
  } catch {
417
- u.showMessage("登录失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "登录");
421
+ d.showMessage("登录失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "登录");
418
422
  }
419
423
  },
420
424
  // 关闭弹窗
421
425
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
422
426
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
423
427
  close(e = !1) {
424
- u.hide(), l.resolveAuth && (l.resolveAuth(!1), l.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
428
+ d.hide(), l.resolveAuth && (l.resolveAuth(!1), l.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
425
429
  },
426
430
  // 清空本地认证凭证(双重删除:Cookie + localStorage)
427
431
  // 用于"退出登录 / 清空认证状态"按钮。
@@ -441,7 +445,7 @@ const a = {
441
445
  const e = a.getToken();
442
446
  if (e)
443
447
  try {
444
- const t = r.apiBase && !/\/$/.test(r.apiBase) ? r.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
448
+ const t = s.apiBase && !/\/$/.test(s.apiBase) ? s.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
445
449
  method: "POST",
446
450
  headers: { "Content-Type": "application/json" },
447
451
  body: JSON.stringify({ token: e }),
@@ -455,11 +459,11 @@ const a = {
455
459
  },
456
460
  // 验证成功回调
457
461
  onVerified(e) {
458
- console.log("[WxAuth] 验证成功", e), typeof r.onVerified == "function" && r.onVerified(e), l.resolveAuth && (l.resolveAuth(!0), l.resolveAuth = null);
462
+ console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), l.resolveAuth && (l.resolveAuth(!0), l.resolveAuth = null);
459
463
  },
460
464
  // 错误回调
461
465
  onError(e) {
462
- console.error("[WxAuth] 错误", e), typeof r.onError == "function" && r.onError(e);
466
+ console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
463
467
  }
464
468
  };
465
469
  typeof window < "u" && (window.WxAuth = Object.freeze(m));
@@ -1,5 +1,5 @@
1
- (function(h,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(h=typeof globalThis<"u"?globalThis:h||self,f(h.WxAuthSDK={}))})(this,(function(h){"use strict";var f=document.createElement("style");f.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-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
2
- /*$vite$:1*/`,document.head.appendChild(f);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},l={enable(e){if(i.isProtected||typeof window>"u")return;i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!0,i.restorePending=!1,i.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const a of n.removedNodes){if(a.nodeType!==Node.ELEMENT_NODE)continue;const p=a;if(p.id===e.modalId||p.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),l.safeRestore(e);return}}}),i.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!i.isProtected)return;const{getState:o}=e;if(!o().isOpen){i.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||l.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?l.isHidden(n):null}),l.safeRestore(e)),i.isProtected&&(i.rafId=requestAnimationFrame(t))};i.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!1,i.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!i.restorePending){i.restorePending=!0;try{l.restoreFn(e)}finally{requestAnimationFrame(()=>{i.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 a=document.getElementById(t);if(a){a.style.display="flex",a.style.visibility="visible",a.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(),a=n?`;domain=${n}`:"",w=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${a}${w};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",a=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${a};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=`
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-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 d=i;if(d.id===e.modalId||d.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}},l={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">
@@ -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 a=n.target.value.replace(/\D/g,"");n.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const a=n.target;n.key==="Backspace"&&!a.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 a=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((p,w)=>{e[w]&&(e[w].value=p)}),a.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.style.display="flex",u.isOpen=!0,l.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),r.qrcodeUrl&&this.setQrCode(r.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&r.wechatName&&(t.textContent=`"${r.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",u.isOpen=!1,l.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)),h.WxAuth=x,Object.defineProperty(h,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((d,w)=>{e[w]&&(e[w].value=d)}),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 d=document.querySelector(".wx-auth-input");d&&d.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(){l.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&&l.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=l.getVerifyCode();if(!e||e.length!==6){l.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)):(l.showMessage("验证码错误或已过期","error"),l.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch{l.showMessage("登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){l.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"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.19",
3
+ "version": "1.2.21",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",