wx-auth-sdk 1.2.45 → 1.2.47

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
@@ -106,7 +106,7 @@ const s = {
106
106
  silent: !1
107
107
  // 默认不静默
108
108
  };
109
- let a = { ...M }, d = "", k = "", y = null, x = null;
109
+ let a = { ...M }, d = "", g = "", y = null, x = null;
110
110
  const A = "wxauth-anon", I = 10080 * 60 * 1e3;
111
111
  let i = {
112
112
  isOpen: !1,
@@ -125,7 +125,7 @@ function O(e) {
125
125
  return "";
126
126
  }
127
127
  }
128
- const u = {
128
+ const c = {
129
129
  getRootDomain() {
130
130
  return O(window.location.hostname);
131
131
  },
@@ -155,25 +155,26 @@ const u = {
155
155
  const t = this.getRootDomain();
156
156
  this.writeCookieRaw(e, "", void 0, t, !0), t && this.writeCookieRaw(e, "", void 0, "", !0);
157
157
  },
158
- // ===== 签名 Token 存储(会话 Cookie、无滑动续期,2026-09-28)=====
159
- // 登录态策略:setToken 写**会话 Cookie**(不设 expires,浏览器关闭即失效);
158
+ // ===== 签名 Token 存储(24h 持久 Cookie、无滑动续期,2026-10-14)=====
159
+ // 登录态策略:setToken 写 **24 小时持久 Cookie**(写明 expires);
160
160
  // silentCheck / autoCheck 校验成功**不回写 token**(回写 = 滑动续期)——
161
- // 「浏览器一关就重新登录」,开关浏览器次数 = 激励广告曝光次数。
161
+ // 「每天最多登录一次」,过期点跟用户自己的使用节奏走,开关浏览器不产生额外登录。
162
+ // 服务端配套:网页扫码 token 带 w1 种类段,TTL 1 天(见 token.ts)——
163
+ // 前端 Cookie 与服务端 TTL 双闸门对齐,浏览器会话恢复等保留行为也绕不过 24h。
162
164
  // 沿革:2026-08-30 会话级 → 2026-09-04 放宽 3 天 → 2026-09-05 会话级 →
163
- // 2026-09-19 7 天 + 滑动续期 → 2026-09-24 1 天固定不续期 → 2026-09-28 回到
164
- // 会话 Cookie(09-05 原配对)。服务端公众号 token TTL 保持 1 天作兜底闸门
165
- // (长开浏览器不关的用户最多 24h 也会被要求重新扫码)。
166
- // 不引入 localStorage 备份(备份会让登录态越过 Cookie 生命周期存活,与
167
- // 「浏览器关闭即重登」直接冲突);clearToken 保留对旧版本备份 key 的防御性清理。
165
+ // 2026-09-19 7 天 + 滑动续期 → 2026-09-24 1 天固定不续期 → 2026-09-28 会话
166
+ // Cookie(被 Chrome 会话恢复实测绕过,寿命不可控)→ 2026-10-14 改 24h 持久。
167
+ // 不引入 localStorage 备份(备份会让登录态越过 Cookie 生命周期存活);
168
+ // clearToken 保留对旧版本备份 key 的防御性清理。
168
169
  // 存储的是签名 Token(HMAC,不可伪造),而非明文 openid(永久凭证)。
169
170
  // 注意:Cookie 是根域共享;localStorage 按站点隔离,且不再读取。
170
171
  // 读取:wxauth-token Cookie(旧版本 localStorage 备份不再兜底)
171
172
  getToken() {
172
173
  return this.getCookie("wxauth-token");
173
174
  },
174
- // 写入:会话 Cookie(不设 expires;只在真登录路径调用——校验成功不再回写续期)
175
+ // 写入:24h 持久 Cookie(只在真登录路径调用——校验成功不再回写续期)
175
176
  setToken(e) {
176
- this.setCookie("wxauth-token", e);
177
+ this.setCookie("wxauth-token", e, 1440 * 60 * 1e3);
177
178
  },
178
179
  // 删除:清 Cookie + 防御性清理旧版本 localStorage 备份残留
179
180
  // (同时清掉明文 openid Cookie —— 防御性清理,服务端已下线 openid 通道 2026-08-26)
@@ -189,7 +190,7 @@ const u = {
189
190
  // (Cookie 被清理/写入失败时从镜像恢复,避免设备身份漂移)。
190
191
  // 注意:这是设备身份不是凭证——退出登录(clearToken/revoke)不清除它。
191
192
  getOrCreateDeviceId() {
192
- if (k) return k;
193
+ if (g) return g;
193
194
  let e = this.getCookie("wxauth-device");
194
195
  if (!e)
195
196
  try {
@@ -209,7 +210,7 @@ const u = {
209
210
  window.localStorage.setItem("wxauth-device", e);
210
211
  } catch {
211
212
  }
212
- return k = e, e;
213
+ return g = e, e;
213
214
  },
214
215
  // ===== 匿名票据(2026-09-24)=====
215
216
  // 从 localStorage 读存储的票据(结构校验,坏数据视为无票)
@@ -225,7 +226,9 @@ const u = {
225
226
  if (typeof t.ticket != "string" || typeof t.anonId != "string" || typeof t.expMs != "number")
226
227
  return null;
227
228
  const n = t.ticket.split(".");
228
- return n.length !== 7 || n[0] !== "v1" || parseInt(n[5], 10) * 1e3 !== t.expMs ? null : { ticket: t.ticket, anonId: t.anonId, expMs: t.expMs };
229
+ if (n.length !== 7 || n[0] !== "v1") return null;
230
+ const o = parseInt(n[5] ?? "", 10) * 1e3;
231
+ return !Number.isFinite(o) || Math.abs(t.expMs - o) > 5e3 ? null : { ticket: t.ticket, anonId: t.anonId, expMs: t.expMs };
229
232
  } catch {
230
233
  return null;
231
234
  }
@@ -238,15 +241,19 @@ const u = {
238
241
  }
239
242
  },
240
243
  // 调 wx-auth 签发口拿一张新票(aud = 当前页面 hostname,票与站点绑定)。
244
+ // 续签时带上旧票:服务端验签通过会沿用 anonId,换票不再等于换身份(2026-11-30);
245
+ // 旧票过期/被篡改也无妨,服务端静默换新,不报 4xx。
241
246
  // 403(bot UA) / 429(限流) / 网络失败会抛错,由调用方 catch(fail-open)
242
247
  async requestAnonTicket() {
243
248
  const e = (a.apiBase || "").replace(/\/$/, "");
244
249
  if (!e || typeof window > "u") return null;
245
- const t = await u.request(`${e}/api/auth/anon`, {
250
+ const t = c.readStoredAnonTicket(), n = { aud: window.location.hostname };
251
+ t?.ticket && (n.token = t.ticket);
252
+ const o = await c.request(`${e}/api/auth/anon`, {
246
253
  method: "POST",
247
- body: { aud: window.location.hostname }
254
+ body: n
248
255
  });
249
- return !t || typeof t.ticket != "string" || typeof t.anonId != "string" || typeof t.expiresIn != "number" ? null : { ticket: t.ticket, anonId: t.anonId, expMs: Date.now() + t.expiresIn * 1e3 };
256
+ return !o || typeof o.ticket != "string" || typeof o.anonId != "string" || typeof o.expiresIn != "number" ? null : { ticket: o.ticket, anonId: o.anonId, expMs: Date.now() + o.expiresIn * 1e3 };
250
257
  },
251
258
  // 发送请求
252
259
  // 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
@@ -285,7 +292,7 @@ function b(e) {
285
292
  const t = e;
286
293
  return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
287
294
  }
288
- function g(e) {
295
+ function k(e) {
289
296
  return new Promise((t) => setTimeout(t, e));
290
297
  }
291
298
  const $ = 3e3, D = 2e3, P = 3e3;
@@ -293,12 +300,12 @@ function S() {
293
300
  h++;
294
301
  }
295
302
  async function q(e) {
296
- if (await g($), !(e !== h || !i.isOpen)) {
303
+ if (await k($), !(e !== h || !i.isOpen)) {
297
304
  for (; e === h && i.isOpen; ) {
298
305
  const t = i.mpSession;
299
306
  if (!t || Date.now() >= t.expiresAt) break;
300
307
  try {
301
- const n = await u.request(
308
+ const n = await c.request(
302
309
  `${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
303
310
  );
304
311
  if (e !== h) return;
@@ -313,27 +320,27 @@ async function q(e) {
313
320
  } catch (n) {
314
321
  if (e !== h) return;
315
322
  if (!b(n)) break;
316
- await g(P);
323
+ await k(P);
317
324
  continue;
318
325
  }
319
- await g(D);
326
+ await k(D);
320
327
  }
321
- e === h && i.isOpen && f === "mp" && c.showMpExpired();
328
+ e === h && i.isOpen && f === "mp" && u.showMpExpired();
322
329
  }
323
330
  }
324
331
  async function v(e) {
325
332
  const t = d ? `&siteId=${encodeURIComponent(d)}` : "", n = `${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
326
333
  for (let o = 0; ; o++)
327
334
  try {
328
- const r = await u.request(n);
335
+ const r = await c.request(n);
329
336
  return r.authenticated ? { kind: "ok", result: r } : r.error === "rate_limited" || r.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: r };
330
337
  } catch (r) {
331
338
  if (!b(r) || o >= C.length)
332
339
  return { kind: "transient" };
333
- await g(C[o]);
340
+ await k(C[o]);
334
341
  }
335
342
  }
336
- const c = {
343
+ const u = {
337
344
  // 创建弹窗
338
345
  // 形态固定为双 tab(2026-08-30 去掉 mpScanEnabled 门控):形态不依赖 config,
339
346
  // 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab)结构上不存在。
@@ -510,7 +517,7 @@ const c = {
510
517
  } catch {
511
518
  }
512
519
  !d && window.location.hostname && (d = window.location.hostname), d || (d = "default"), console.log("[WxAuth] 自动获取 siteId:", d);
513
- const n = u.getOrCreateDeviceId();
520
+ const n = c.getOrCreateDeviceId();
514
521
  console.log("[WxAuth] deviceId:", n), this.getOrCreateAnonTicket();
515
522
  }
516
523
  console.log("[WxAuth] SDK initialized", a), typeof window < "u" && (a.silent ? this.silentCheck() : this.autoCheck());
@@ -523,7 +530,7 @@ const c = {
523
530
  getAnonTicket() {
524
531
  if (y)
525
532
  return y.expMs - Date.now() > I ? y.ticket : null;
526
- const e = u.readStoredAnonTicket();
533
+ const e = c.readStoredAnonTicket();
527
534
  return !e || e.expMs - Date.now() <= I ? null : (y = e, e.ticket);
528
535
  },
529
536
  /**
@@ -537,7 +544,7 @@ const c = {
537
544
  */
538
545
  async getOrCreateAnonTicket() {
539
546
  const e = this.getAnonTicket();
540
- return e || (x || (x = u.requestAnonTicket().then((t) => t ? (y = t, u.storeAnonTicket(t.ticket, t.anonId, t.expMs), t.ticket) : null).catch(() => null).finally(() => {
547
+ return e || (x || (x = c.requestAnonTicket().then((t) => t ? (y = t, c.storeAnonTicket(t.ticket, t.anonId, t.expMs), t.ticket) : null).catch(() => null).finally(() => {
541
548
  x = null;
542
549
  })), x);
543
550
  },
@@ -551,14 +558,14 @@ const c = {
551
558
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
552
559
  */
553
560
  async silentCheck() {
554
- const e = u.getToken();
561
+ const e = c.getToken();
555
562
  if (!e) return !1;
556
563
  const t = await v(e);
557
564
  return t.kind === "ok" ? (this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
558
565
  },
559
566
  // 自动检测凭证并验证(内部使用)
560
567
  async autoCheck() {
561
- const e = u.getToken();
568
+ const e = c.getToken();
562
569
  if (!e)
563
570
  return this.showAuthModal(), !1;
564
571
  const t = await v(e);
@@ -576,7 +583,7 @@ const c = {
576
583
  // options.required:本次弹窗是否强制(不可关闭),缺省沿用 init 的 config.required。
577
584
  // 典型用法:搜索/获取等「后端 401 拦截」场景传 true,用户主动点登录则不传或传 false。
578
585
  async showAuthModal(e) {
579
- c.show(e?.required), this.switchMode("mp");
586
+ u.show(e?.required), this.switchMode("mp");
580
587
  },
581
588
  // 切换登录方式(默认模式设定)
582
589
  // 2026-09-16:公众号验证码面板临时停用,弹窗只剩小程序面板,
@@ -595,12 +602,12 @@ const c = {
595
602
  async startMpLogin() {
596
603
  if (!i.isOpen) return;
597
604
  const e = ++h;
598
- if (c.setMpExpiredVisible(!1), c.setMpStatus("", !0), i.mpSession && Date.now() < i.mpSession.expiresAt) {
599
- c.setMpQr(i.mpSession.qrDataUrl), q(e);
605
+ if (u.setMpExpiredVisible(!1), u.setMpStatus("", !0), i.mpSession && Date.now() < i.mpSession.expiresAt) {
606
+ u.setMpQr(i.mpSession.qrDataUrl), q(e);
600
607
  return;
601
608
  }
602
609
  try {
603
- const t = await u.request(`${a.apiBase}/api/auth/mp-scan/create`, {
610
+ const t = await c.request(`${a.apiBase}/api/auth/mp-scan/create`, {
604
611
  method: "POST",
605
612
  body: { siteId: d }
606
613
  });
@@ -610,21 +617,21 @@ const c = {
610
617
  ticket: String(t.ticket),
611
618
  qrDataUrl: String(t.qrDataUrl),
612
619
  expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
613
- }, c.setMpQr(i.mpSession.qrDataUrl), q(e);
620
+ }, u.setMpQr(i.mpSession.qrDataUrl), q(e);
614
621
  } catch (t) {
615
622
  if (e !== h || !i.isOpen) return;
616
- console.warn("[WxAuth] 小程序码生成失败", t), c.setMpStatus("", !1), c.showMpExpired("二维码生成失败,请点下方按钮重试"), c.showMessage("小程序扫码暂不可用,请稍后重试", "error");
623
+ console.warn("[WxAuth] 小程序码生成失败", t), u.setMpStatus("", !1), u.showMpExpired("二维码生成失败,请点下方按钮重试"), u.showMessage("小程序扫码暂不可用,请稍后重试", "error");
617
624
  }
618
625
  },
619
626
  // 主入口:需要验证时调用
620
627
  // 凭证仅签名 Token(登录 Cookie,会话级 + 无滑动续期,2026-09-28),不再兼容明文 openid
621
628
  // (2026-08-26 服务端已下线 openid 通道)
622
629
  async requireAuth(e) {
623
- const t = u.getToken();
630
+ const t = c.getToken();
624
631
  if (t) {
625
632
  const n = await v(t);
626
633
  if (n.kind === "ok")
627
- return console.log("[WxAuth] 已认证(凭证)"), n.result.token && u.setToken(n.result.token), this.onVerified(n.result.user), !0;
634
+ return console.log("[WxAuth] 已认证(凭证)"), n.result.token && c.setToken(n.result.token), this.onVerified(n.result.user), !0;
628
635
  if (n.kind === "transient")
629
636
  return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
630
637
  code: "server_error",
@@ -641,8 +648,8 @@ const c = {
641
648
  // 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
642
649
  // close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
643
650
  completeLogin(e) {
644
- if (e?.token && u.setToken(e.token), f === "mp")
645
- c.setMpStatus("✅ 登录成功", !1);
651
+ if (e?.token && c.setToken(e.token), f === "mp")
652
+ u.setMpStatus("✅ 登录成功", !1);
646
653
  else {
647
654
  const t = document.querySelector(".wx-auth-btn-primary");
648
655
  t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
@@ -655,9 +662,9 @@ const c = {
655
662
  // 2026-09-16:公众号登录临时停用 → 弹窗内已无验证码输入框与登录入口,
656
663
  // 此方法保留(老接入方直调 / 恢复时可直接复用),正常链路不会被触发。
657
664
  async verifyCode() {
658
- const e = c.getVerifyCode();
665
+ const e = u.getVerifyCode();
659
666
  if (!e || e.length !== 6) {
660
- c.showMessage("请输入6位验证码", "error");
667
+ u.showMessage("请输入6位验证码", "error");
661
668
  return;
662
669
  }
663
670
  const t = document.querySelector(
@@ -665,15 +672,15 @@ const c = {
665
672
  );
666
673
  t && (t.disabled = !0, t.textContent = "登录中...");
667
674
  try {
668
- const n = d ? `&siteId=${encodeURIComponent(d)}` : "", o = `&deviceId=${encodeURIComponent(u.getOrCreateDeviceId())}`, r = await u.request(
675
+ const n = d ? `&siteId=${encodeURIComponent(d)}` : "", o = `&deviceId=${encodeURIComponent(c.getOrCreateDeviceId())}`, r = await c.request(
669
676
  `${a.apiBase}/api/auth/check?authToken=${e}${n}${o}`
670
677
  );
671
- r.authenticated ? this.completeLogin(r) : (c.showMessage(
678
+ r.authenticated ? this.completeLogin(r) : (u.showMessage(
672
679
  r.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
673
680
  "error"
674
- ), c.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
681
+ ), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
675
682
  } catch (n) {
676
- c.showMessage(
683
+ u.showMessage(
677
684
  b(n) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
678
685
  "error"
679
686
  ), t && (t.disabled = !1, t.textContent = "登录");
@@ -683,12 +690,12 @@ const c = {
683
690
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
684
691
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
685
692
  close(e = !1) {
686
- c.hide(), i.resolveAuth && (i.resolveAuth(!1), i.resolveAuth = null), !e && typeof a.onClose == "function" && a.onClose();
693
+ u.hide(), i.resolveAuth && (i.resolveAuth(!1), i.resolveAuth = null), !e && typeof a.onClose == "function" && a.onClose();
687
694
  },
688
695
  // 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
689
696
  // 用于"退出登录 / 清空认证状态"按钮。
690
697
  clearToken() {
691
- u.clearToken();
698
+ c.clearToken();
692
699
  },
693
700
  // 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
694
701
  // 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
@@ -699,14 +706,14 @@ const c = {
699
706
  // 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
700
707
  // 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
701
708
  async revoke() {
702
- const e = u.getToken();
709
+ const e = c.getToken();
703
710
  if (e)
704
711
  try {
705
712
  const t = a.apiBase && !/\/$/.test(a.apiBase) ? a.apiBase : "https://wx-auth.shenzjd.com", n = await fetch(`${t}/api/auth/logout`, {
706
713
  method: "POST",
707
714
  headers: { "Content-Type": "application/json" },
708
715
  // deviceId 显式携带(跨站 SameSite 下 Cookie 不可靠);设备身份不因退出而清除
709
- body: JSON.stringify({ token: e, deviceId: u.getOrCreateDeviceId() }),
716
+ body: JSON.stringify({ token: e, deviceId: c.getOrCreateDeviceId() }),
710
717
  credentials: "include"
711
718
  });
712
719
  n.ok || console.warn("[WxAuth] revoke 请求失败,降级本地清理", n.status);
@@ -1,5 +1,5 @@
1
1
  (function(w,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(w=typeof globalThis<"u"?globalThis:w||self,m(w.WxAuthSDK={}))})(this,(function(w){"use strict";var m=document.createElement("style");m.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-modal .wx-auth-header{position:relative;background:#07c160;color:#fff;box-sizing:border-box;min-height:56px;padding:0 16px;display:flex;align-items:center;justify-content:space-between}.wx-auth-modal .wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-modal .wx-auth-close{position:absolute;right:10px;top:50%;transform:translateY(-50%);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-tabs{display:flex;gap:8px;margin-bottom:16px}.wx-auth-tab{flex:1;padding:8px 0;font-size:13px;border:1px solid #DCDCDC;background:#f7f7f7;color:#666;border-radius:6px;cursor:pointer;transition:all .2s}.wx-auth-tab:active{transform:scale(.98)}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff;font-weight:600}.wx-auth-mp-loading{height:100%;display:flex;align-items:center;justify-content:center}.wx-auth-spinner{width:28px;height:28px;border:3px solid #e5e5e5;border-top-color:#07c160;border-radius:50%;animation:wxAuthSpin 1s linear infinite}@keyframes wxAuthSpin{to{transform:rotate(360deg)}}.wx-auth-mp-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-mp-container{position:relative}.wx-auth-mp-expired{position:absolute;inset:0;z-index:1;display:none;flex-direction:column;align-items:center;justify-content:center;gap:10px;background:#ffffffeb}.wx-auth-mp-expired-text{font-size:13px;color:#666}.wx-auth-mp-expired .wx-auth-mp-refresh{flex:none;width:auto;margin:0;padding:8px 18px;font-size:13px}.wx-auth-mp-status{font-size:13px;color:#666;margin:4px 0 12px;min-height:18px;line-height:1.4}.wx-auth-mp-hint{margin:12px 0 4px}.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-tab{background:#2a2a2a;border-color:#444;color:#aaa}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff}.wx-auth-spinner{border-color:#444;border-top-color:#07c160}.wx-auth-mp-status{color:#aaa}.wx-auth-mp-expired{background:#1a1a1aeb}.wx-auth-mp-expired-text{color:#aaa}.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(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={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 r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const l=r;if(l.id===e.modalId||l.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),f.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||f.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?f.isHidden(n):null}),f.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{f.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 r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},I={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!1,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let s={...I},d="",v="",g=null,b=null;const q="wxauth-anon",M=10080*60*1e3;let a={isOpen:!1,resolveAuth:null,currentStep:"qr",required:!!s.required,mpSession:null},p="mp",h=0;function D(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 D(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},writeCookieRaw(e,t,o,n,r=!1){const l=n?`;domain=${n}`:"",R=window.location.protocol==="https:"?";Secure":"",L=r?";expires=Thu, 01 Jan 1970 00:00:00 GMT":o!==void 0?`;expires=${new Date(Date.now()+o).toUTCString()}`:"";document.cookie=`${e}=${r?"":t};path=/${l}${L}${R};SameSite=Strict`},setCookie(e,t,o){const n=this.getRootDomain();this.writeCookieRaw(e,t,o,n),n&&!this.getCookie(e)&&this.writeCookieRaw(e,t,o,"")},deleteCookie(e){const t=this.getRootDomain();this.writeCookieRaw(e,"",void 0,t,!0),t&&this.writeCookieRaw(e,"",void 0,"",!0)},getToken(){return this.getCookie("wxauth-token")},setToken(e){this.setCookie("wxauth-token",e)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}catch{}},getOrCreateDeviceId(){if(v)return v;let e=this.getCookie("wxauth-device");if(!e)try{e=window.localStorage.getItem("wxauth-device")}catch{}if(!e||!/^[A-Za-z0-9_-]{1,64}$/.test(e)){const t=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let o=0;o<16;o++)t[o]=Math.floor(Math.random()*256);e=Array.from(t).map(o=>o.toString(16).padStart(2,"0")).join("")}this.setCookie("wxauth-device",e,365*86400*1e3);try{window.localStorage.setItem("wxauth-device",e)}catch{}return v=e,e},readStoredAnonTicket(){let e=null;try{e=window.localStorage.getItem(q)}catch{}if(!e)return null;try{const t=JSON.parse(e);if(typeof t.ticket!="string"||typeof t.anonId!="string"||typeof t.expMs!="number")return null;const o=t.ticket.split(".");return o.length!==7||o[0]!=="v1"||parseInt(o[5],10)*1e3!==t.expMs?null:{ticket:t.ticket,anonId:t.anonId,expMs:t.expMs}}catch{return null}},storeAnonTicket(e,t,o){try{window.localStorage.setItem(q,JSON.stringify({ticket:e,anonId:t,expMs:o}))}catch{}},async requestAnonTicket(){const e=(s.apiBase||"").replace(/\/$/,"");if(!e||typeof window>"u")return null;const t=await c.request(`${e}/api/auth/anon`,{method:"POST",body:{aud:window.location.hostname}});return!t||typeof t.ticket!="string"||typeof t.anonId!="string"||typeof t.expiresIn!="number"?null:{ticket:t.ticket,anonId:t.anonId,expMs:Date.now()+t.expiresIn*1e3}},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){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},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}},T=[1e3,3e3];function S(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function k(e){return new Promise(t=>setTimeout(t,e))}const $=3e3,O=2e3,P=3e3;function A(){h++}async function E(e){if(await k($),!(e!==h||!a.isOpen)){for(;e===h&&a.isOpen;){const t=a.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${s.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==h)return;if(o.status==="confirmed"&&o.token){x.completeLogin(o);return}if(o.status==="expired"){a.mpSession=null;break}}catch(o){if(e!==h)return;if(!S(o))break;await k(P);continue}await k(O)}e===h&&a.isOpen&&p==="mp"&&u.showMpExpired()}}async function C(e){const t=d?`&siteId=${encodeURIComponent(d)}`:"",o=`${s.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await c.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!S(r)||n>=T.length)return{kind:"transient"};await k(T[n])}}const u={createModal(e){const t=document.createElement("div");t.id="wx-auth-modal",t.className="wx-auth-modal",t.classList.add(e?"wx-auth-required":"wx-auth-optional");const o="",n="",r=`<div class="wx-auth-panel wx-auth-panel-mp">
2
+ /*$vite$:1*/`,document.head.appendChild(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={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 r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const l=r;if(l.id===e.modalId||l.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),f.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||f.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?f.isHidden(n):null}),f.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{f.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 r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},I={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!1,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let s={...I},d="",v="",g=null,b=null;const q="wxauth-anon",M=10080*60*1e3;let a={isOpen:!1,resolveAuth:null,currentStep:"qr",required:!!s.required,mpSession:null},h="mp",p=0;function D(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 D(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},writeCookieRaw(e,t,o,n,r=!1){const l=n?`;domain=${n}`:"",R=window.location.protocol==="https:"?";Secure":"",L=r?";expires=Thu, 01 Jan 1970 00:00:00 GMT":o!==void 0?`;expires=${new Date(Date.now()+o).toUTCString()}`:"";document.cookie=`${e}=${r?"":t};path=/${l}${L}${R};SameSite=Strict`},setCookie(e,t,o){const n=this.getRootDomain();this.writeCookieRaw(e,t,o,n),n&&!this.getCookie(e)&&this.writeCookieRaw(e,t,o,"")},deleteCookie(e){const t=this.getRootDomain();this.writeCookieRaw(e,"",void 0,t,!0),t&&this.writeCookieRaw(e,"",void 0,"",!0)},getToken(){return this.getCookie("wxauth-token")},setToken(e){this.setCookie("wxauth-token",e,1440*60*1e3)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}catch{}},getOrCreateDeviceId(){if(v)return v;let e=this.getCookie("wxauth-device");if(!e)try{e=window.localStorage.getItem("wxauth-device")}catch{}if(!e||!/^[A-Za-z0-9_-]{1,64}$/.test(e)){const t=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let o=0;o<16;o++)t[o]=Math.floor(Math.random()*256);e=Array.from(t).map(o=>o.toString(16).padStart(2,"0")).join("")}this.setCookie("wxauth-device",e,365*86400*1e3);try{window.localStorage.setItem("wxauth-device",e)}catch{}return v=e,e},readStoredAnonTicket(){let e=null;try{e=window.localStorage.getItem(q)}catch{}if(!e)return null;try{const t=JSON.parse(e);if(typeof t.ticket!="string"||typeof t.anonId!="string"||typeof t.expMs!="number")return null;const o=t.ticket.split(".");if(o.length!==7||o[0]!=="v1")return null;const n=parseInt(o[5]??"",10)*1e3;return!Number.isFinite(n)||Math.abs(t.expMs-n)>5e3?null:{ticket:t.ticket,anonId:t.anonId,expMs:t.expMs}}catch{return null}},storeAnonTicket(e,t,o){try{window.localStorage.setItem(q,JSON.stringify({ticket:e,anonId:t,expMs:o}))}catch{}},async requestAnonTicket(){const e=(s.apiBase||"").replace(/\/$/,"");if(!e||typeof window>"u")return null;const t=c.readStoredAnonTicket(),o={aud:window.location.hostname};t?.ticket&&(o.token=t.ticket);const n=await c.request(`${e}/api/auth/anon`,{method:"POST",body:o});return!n||typeof n.ticket!="string"||typeof n.anonId!="string"||typeof n.expiresIn!="number"?null:{ticket:n.ticket,anonId:n.anonId,expMs:Date.now()+n.expiresIn*1e3}},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){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},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}},T=[1e3,3e3];function S(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function k(e){return new Promise(t=>setTimeout(t,e))}const $=3e3,O=2e3,P=3e3;function A(){p++}async function E(e){if(await k($),!(e!==p||!a.isOpen)){for(;e===p&&a.isOpen;){const t=a.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${s.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==p)return;if(o.status==="confirmed"&&o.token){x.completeLogin(o);return}if(o.status==="expired"){a.mpSession=null;break}}catch(o){if(e!==p)return;if(!S(o))break;await k(P);continue}await k(O)}e===p&&a.isOpen&&h==="mp"&&u.showMpExpired()}}async function C(e){const t=d?`&siteId=${encodeURIComponent(d)}`:"",o=`${s.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await c.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!S(r)||n>=T.length)return{kind:"transient"};await k(T[n])}}const u={createModal(e){const t=document.createElement("div");t.id="wx-auth-modal",t.className="wx-auth-modal",t.classList.add(e?"wx-auth-required":"wx-auth-optional");const o="",n="",r=`<div class="wx-auth-panel wx-auth-panel-mp">
3
3
  <div class="wx-auth-qrcode-container wx-auth-mp-container">
4
4
  <div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
5
5
  <img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
@@ -29,4 +29,4 @@
29
29
  <div class="wx-auth-message" style="display:none"></div>
30
30
  </div>
31
31
  </div>
32
- `,document.body.appendChild(t),this.syncModalShape(t,e),this.bindInputEvents(),t},syncModalShape(e,t){e.classList.remove("wx-auth-required","wx-auth-optional"),e.classList.add(t?"wx-auth-required":"wx-auth-optional");const o=e.querySelector(".wx-auth-overlay");o&&(o.onclick=t?y=>y.preventDefault():null);const n=e.querySelector(".wx-auth-close");if(t){n?.remove();return}if(n)return;const r=e.querySelector(".wx-auth-header");if(!r)return;const l=document.createElement("button");l.type="button",l.className="wx-auth-close",l.setAttribute("aria-label","关闭"),l.textContent="×",l.addEventListener("click",()=>x.close()),r.appendChild(l)},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;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())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((l,y)=>{e[y]&&(e[y].value=l)}),r.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(e){const t=e??!!s.required;a.required=t;let o=document.getElementById("wx-auth-modal");o?this.syncModalShape(o,t):o=this.createModal(t);const n=o.querySelector(".wx-auth-message");n&&(n.textContent="",n.className="wx-auth-message",n.style.display="none"),A(),a.mpSession=null,o.style.display="flex",a.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>a,onRestore:()=>{this.createModal(a.required),s.qrcodeUrl&&this.setQrCode(s.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&s.wechatName&&(r.textContent=`"${s.wechatName}"`),this.bindInputEvents(),p==="mp"&&x.switchMode("mp"),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",a.isOpen=!1,A(),a.mpSession=null,f.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},setMpQr(e){const t=document.getElementById("wx-auth-modal"),o=t?.querySelector(".wx-auth-mp-qrcode"),n=t?.querySelector(".wx-auth-mp-loading");o&&(o.src=e,o.style.display="block",n&&(n.style.display="none"),this.setMpExpiredVisible(!1),this.setMpStatus("",!1))},setMpExpiredVisible(e){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");o&&(o.style.display=e?"flex":"none")},setMpStatus(e,t){const o=document.getElementById("wx-auth-modal"),n=o?.querySelector(".wx-auth-mp-status");n&&(n.textContent=e,n.style.display=e?"block":"none");const r=o?.querySelector(".wx-auth-mp-loading");if(r&&(r.style.display=t?"flex":"none"),t){const l=o?.querySelector(".wx-auth-mp-qrcode");l&&(l.style.display="none")}},showMpExpired(e="二维码已过期"){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired-text");o&&(o.textContent=e),this.setMpExpiredVisible(!0)},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(s={...I,...e},!s.apiBase&&typeof window<"u"&&(s.apiBase=window.location.origin),!s.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{d=new URL(t).hostname}catch{}!d&&window.location.hostname&&(d=window.location.hostname),d||(d="default"),console.log("[WxAuth] 自动获取 siteId:",d);const o=c.getOrCreateDeviceId();console.log("[WxAuth] deviceId:",o),this.getOrCreateAnonTicket()}console.log("[WxAuth] SDK initialized",s),typeof window<"u"&&(s.silent?this.silentCheck():this.autoCheck())},getAnonTicket(){if(g)return g.expMs-Date.now()>M?g.ticket:null;const e=c.readStoredAnonTicket();return!e||e.expMs-Date.now()<=M?null:(g=e,e.ticket)},async getOrCreateAnonTicket(){const e=this.getAnonTicket();return e||(b||(b=c.requestAnonTicket().then(t=>t?(g=t,c.storeAnonTicket(t.ticket,t.anonId,t.expMs),t.ticket):null).catch(()=>null).finally(()=>{b=null})),b)},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await C(e);return t.kind==="ok"?(this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=await C(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(e){u.show(e?.required),this.switchMode("mp")},switchMode(e){p=e;const t=document.getElementById("wx-auth-modal");if(!t)return;t.querySelectorAll(".wx-auth-tab").forEach(r=>{r.classList.toggle("wx-auth-tab-active",r.dataset.mode===p)});const o=t.querySelector(".wx-auth-panel-code"),n=t.querySelector(".wx-auth-panel-mp");o&&(o.style.display=p==="code"?"":"none"),n&&(n.style.display=p==="mp"?"":"none"),p==="mp"?this.startMpLogin():A()},async startMpLogin(){if(!a.isOpen)return;const e=++h;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),a.mpSession&&Date.now()<a.mpSession.expiresAt){u.setMpQr(a.mpSession.qrDataUrl),E(e);return}try{const t=await c.request(`${s.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:d}});if(e!==h||!a.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");a.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(a.mpSession.qrDataUrl),E(e)}catch(t){if(e!==h||!a.isOpen)return;console.warn("[WxAuth] 小程序码生成失败",t),u.setMpStatus("",!1),u.showMpExpired("二维码生成失败,请点下方按钮重试"),u.showMessage("小程序扫码暂不可用,请稍后重试","error")}},async requireAuth(e){const t=c.getToken();if(t){const o=await C(t);if(o.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),o.result.token&&c.setToken(o.result.token),this.onVerified(o.result.user),!0;if(o.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(e),new Promise(o=>{a.resolveAuth=o})},completeLogin(e){if(e?.token&&c.setToken(e.token),p==="mp")u.setMpStatus("✅ 登录成功",!1);else{const t=document.querySelector(".wx-auth-btn-primary");t&&(t.textContent="✅ 已登录",t.style.background="#07C160")}setTimeout(()=>{this.onVerified(e?.user),this.close(!0)},500)},async verifyCode(){const e=u.getVerifyCode();if(!e||e.length!==6){u.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=d?`&siteId=${encodeURIComponent(d)}`:"",n=`&deviceId=${encodeURIComponent(c.getOrCreateDeviceId())}`,r=await c.request(`${s.apiBase}/api/auth/check?authToken=${e}${o}${n}`);r.authenticated?this.completeLogin(r):(u.showMessage(r.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(S(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),a.resolveAuth&&(a.resolveAuth(!1),a.resolveAuth=null),!e&&typeof s.onClose=="function"&&s.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=s.apiBase&&!/\/$/.test(s.apiBase)?s.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,deviceId:c.getOrCreateDeviceId()}),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 s.onVerified=="function"&&s.onVerified(e),a.resolveAuth&&(a.resolveAuth(!0),a.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof s.onError=="function"&&s.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),w.WxAuth=x,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
32
+ `,document.body.appendChild(t),this.syncModalShape(t,e),this.bindInputEvents(),t},syncModalShape(e,t){e.classList.remove("wx-auth-required","wx-auth-optional"),e.classList.add(t?"wx-auth-required":"wx-auth-optional");const o=e.querySelector(".wx-auth-overlay");o&&(o.onclick=t?y=>y.preventDefault():null);const n=e.querySelector(".wx-auth-close");if(t){n?.remove();return}if(n)return;const r=e.querySelector(".wx-auth-header");if(!r)return;const l=document.createElement("button");l.type="button",l.className="wx-auth-close",l.setAttribute("aria-label","关闭"),l.textContent="×",l.addEventListener("click",()=>x.close()),r.appendChild(l)},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;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())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((l,y)=>{e[y]&&(e[y].value=l)}),r.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(e){const t=e??!!s.required;a.required=t;let o=document.getElementById("wx-auth-modal");o?this.syncModalShape(o,t):o=this.createModal(t);const n=o.querySelector(".wx-auth-message");n&&(n.textContent="",n.className="wx-auth-message",n.style.display="none"),A(),a.mpSession=null,o.style.display="flex",a.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>a,onRestore:()=>{this.createModal(a.required),s.qrcodeUrl&&this.setQrCode(s.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&s.wechatName&&(r.textContent=`"${s.wechatName}"`),this.bindInputEvents(),h==="mp"&&x.switchMode("mp"),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",a.isOpen=!1,A(),a.mpSession=null,f.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},setMpQr(e){const t=document.getElementById("wx-auth-modal"),o=t?.querySelector(".wx-auth-mp-qrcode"),n=t?.querySelector(".wx-auth-mp-loading");o&&(o.src=e,o.style.display="block",n&&(n.style.display="none"),this.setMpExpiredVisible(!1),this.setMpStatus("",!1))},setMpExpiredVisible(e){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");o&&(o.style.display=e?"flex":"none")},setMpStatus(e,t){const o=document.getElementById("wx-auth-modal"),n=o?.querySelector(".wx-auth-mp-status");n&&(n.textContent=e,n.style.display=e?"block":"none");const r=o?.querySelector(".wx-auth-mp-loading");if(r&&(r.style.display=t?"flex":"none"),t){const l=o?.querySelector(".wx-auth-mp-qrcode");l&&(l.style.display="none")}},showMpExpired(e="二维码已过期"){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired-text");o&&(o.textContent=e),this.setMpExpiredVisible(!0)},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(s={...I,...e},!s.apiBase&&typeof window<"u"&&(s.apiBase=window.location.origin),!s.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{d=new URL(t).hostname}catch{}!d&&window.location.hostname&&(d=window.location.hostname),d||(d="default"),console.log("[WxAuth] 自动获取 siteId:",d);const o=c.getOrCreateDeviceId();console.log("[WxAuth] deviceId:",o),this.getOrCreateAnonTicket()}console.log("[WxAuth] SDK initialized",s),typeof window<"u"&&(s.silent?this.silentCheck():this.autoCheck())},getAnonTicket(){if(g)return g.expMs-Date.now()>M?g.ticket:null;const e=c.readStoredAnonTicket();return!e||e.expMs-Date.now()<=M?null:(g=e,e.ticket)},async getOrCreateAnonTicket(){const e=this.getAnonTicket();return e||(b||(b=c.requestAnonTicket().then(t=>t?(g=t,c.storeAnonTicket(t.ticket,t.anonId,t.expMs),t.ticket):null).catch(()=>null).finally(()=>{b=null})),b)},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await C(e);return t.kind==="ok"?(this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=await C(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(e){u.show(e?.required),this.switchMode("mp")},switchMode(e){h=e;const t=document.getElementById("wx-auth-modal");if(!t)return;t.querySelectorAll(".wx-auth-tab").forEach(r=>{r.classList.toggle("wx-auth-tab-active",r.dataset.mode===h)});const o=t.querySelector(".wx-auth-panel-code"),n=t.querySelector(".wx-auth-panel-mp");o&&(o.style.display=h==="code"?"":"none"),n&&(n.style.display=h==="mp"?"":"none"),h==="mp"?this.startMpLogin():A()},async startMpLogin(){if(!a.isOpen)return;const e=++p;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),a.mpSession&&Date.now()<a.mpSession.expiresAt){u.setMpQr(a.mpSession.qrDataUrl),E(e);return}try{const t=await c.request(`${s.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:d}});if(e!==p||!a.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");a.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(a.mpSession.qrDataUrl),E(e)}catch(t){if(e!==p||!a.isOpen)return;console.warn("[WxAuth] 小程序码生成失败",t),u.setMpStatus("",!1),u.showMpExpired("二维码生成失败,请点下方按钮重试"),u.showMessage("小程序扫码暂不可用,请稍后重试","error")}},async requireAuth(e){const t=c.getToken();if(t){const o=await C(t);if(o.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),o.result.token&&c.setToken(o.result.token),this.onVerified(o.result.user),!0;if(o.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(e),new Promise(o=>{a.resolveAuth=o})},completeLogin(e){if(e?.token&&c.setToken(e.token),h==="mp")u.setMpStatus("✅ 登录成功",!1);else{const t=document.querySelector(".wx-auth-btn-primary");t&&(t.textContent="✅ 已登录",t.style.background="#07C160")}setTimeout(()=>{this.onVerified(e?.user),this.close(!0)},500)},async verifyCode(){const e=u.getVerifyCode();if(!e||e.length!==6){u.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=d?`&siteId=${encodeURIComponent(d)}`:"",n=`&deviceId=${encodeURIComponent(c.getOrCreateDeviceId())}`,r=await c.request(`${s.apiBase}/api/auth/check?authToken=${e}${o}${n}`);r.authenticated?this.completeLogin(r):(u.showMessage(r.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(S(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),a.resolveAuth&&(a.resolveAuth(!1),a.resolveAuth=null),!e&&typeof s.onClose=="function"&&s.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=s.apiBase&&!/\/$/.test(s.apiBase)?s.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,deviceId:c.getOrCreateDeviceId()}),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 s.onVerified=="function"&&s.onVerified(e),a.resolveAuth&&(a.resolveAuth(!0),a.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof s.onError=="function"&&s.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),w.WxAuth=x,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.45",
3
+ "version": "1.2.47",
4
4
  "description": "微信登录 SDK - 小程序扫码 / 公众号验证码双方式,零依赖",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",