wx-auth-sdk 1.2.33 → 1.2.34

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/README.md CHANGED
@@ -84,7 +84,7 @@ SDK 会自动:
84
84
 
85
85
  ## 登录态与 Cookie 域
86
86
 
87
- 认证成功后,SDK 将签名 Token 写入 Cookie(**按根域存储,会话 Cookie——不设有效期,浏览器关闭即失效**)。Cookie 的 `domain` 由**当前页面域名**推导,而不是后端地址(apiBase):
87
+ 认证成功后,SDK 将签名 Token 写入 Cookie(**按根域存储,持久 Cookie——有效期 3 天,浏览器关闭/重启登录态仍在;3 天未使用才需重新登录**)。Cookie 的 `domain` 由**当前页面域名**推导,而不是后端地址(apiBase):
88
88
 
89
89
  | 页面域名 | Cookie 落点 | 登录态共享范围 |
90
90
  |---------|------------|---------------|
@@ -97,7 +97,7 @@ SDK 会自动:
97
97
  - **同一注册域内一个认证,全域自动登录**:`sub1.mysite.com` 认证后,`sub2.mysite.com`、根域 `mysite.com` 都能静默通过(凭根域 Cookie)。
98
98
  - **跨注册域不共享**:`mysite.com` 与 `other.com` 是相互独立的登录态,需各自认证一次(浏览器安全机制,无法绕过)。
99
99
  - **主站已登录 → 子站有登录态**:`panhub.shenzjd.com` 认证后,访问 `parse.shenzjd.com` 等其他子站同样静默通过。
100
- - **登录态为会话级(2026-08-30)**:Cookie 不设有效期,浏览器关闭后登录态即失效,下次打开需重新扫码登录;同一浏览器会话内刷新、新开标签页均保持登录(web 定位为小程序引流入口的策略,见主仓库 AGENTS.md)。
100
+ - **登录态统一 3 天(2026-09-04)**:Cookie 带 `expires=3 天`,浏览器关闭/重启后登录态仍在(此前 2026-08-30 起为会话级——浏览器关闭即失效);每次认证成功重置 3 天窗口,3 天未使用才需重新扫码;小程序扫码与公众号验证码两种登录方式一致(策略沿革见主仓库 AGENTS.md)。
101
101
  - **⚠️ 多级公共后缀**:若页面域名属于 `.com.cn` / `.co.uk` 等多级后缀(如 `site.mysite.com.cn`),"取最后两段"会推导出 `.com.cn`,浏览器会拒绝写入。此类接入需确认域名后再接入。
102
102
 
103
103
  > **为什么 cookie 不跟 apiBase 走?** 早期版本 SDK 曾按 apiBase 域名写 Cookie,导致部署在第三方域名(`apiBase` 指向微信认证后端、页面域名不同)时 Cookie 落错域、后端起总不到凭证、前端反复弹窗(死循环)。SDK 已改为始终按「页面所在域」写 Cookie,与后端地址无关。
@@ -149,7 +149,7 @@ WxAuth.init({
149
149
  初始化 WxAuth.init()
150
150
  │
151
151
  ▼
152
- 读取 Cookie(会话级)
152
+ 读取 Cookie(3 天持久)
153
153
  │
154
154
  ├── 有效 ──────────── onVerified() ✅ 静默通过
155
155
  │
@@ -248,11 +248,11 @@ interface AuthUser {
248
248
  | 输入完成自动提交 | ✅ |
249
249
  | 有 Cookie 静默认证 | ✅ |
250
250
  | Cookie 按页面根域写入(跨子域共享) | ✅ |
251
- | 会话 Cookie 登录态(浏览器关闭即失效,下次重新扫码) | ✅ |
251
+ | 持久 Cookie 登录态(3 天有效,浏览器关闭/重启仍在) | ✅ |
252
252
  | 服务抖动/限流重试,不误清凭证、不误弹码框 | ✅ |
253
253
  | F12 删弹窗自动恢复 | ✅ |
254
254
 
255
- > **登录态有效期(2026-08-30)**:登录态只活在当前浏览器进程内(会话 Cookie,不再写 localStorage 备份)。关闭浏览器后需重新扫码登录;同一浏览器会话内刷新、新开标签页均保持登录。
255
+ > **登录态有效期(2026-09-04)**:web 登录态统一 3 天持久(Cookie 带 `expires=3 天`,小程序扫码 / 公众号验证码一致;2026-08-30~09-03 曾为会话级——浏览器关闭即失效)。浏览器关闭/重启后登录态仍在,每次认证成功重置 3 天窗口,3 天未使用才需重新扫码;不写 localStorage 备份。
256
256
 
257
257
  ---
258
258
 
package/dist/wx-auth.js CHANGED
@@ -110,7 +110,7 @@ let r = { ...q }, u = "", a = {
110
110
  currentStep: "qr",
111
111
  mpSession: null
112
112
  }, f = "code", h = 0;
113
- function A(e) {
113
+ function C(e) {
114
114
  try {
115
115
  if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
116
116
  return "";
@@ -120,40 +120,44 @@ function A(e) {
120
120
  return "";
121
121
  }
122
122
  }
123
- const c = {
123
+ const E = 4320 * 60 * 1e3, c = {
124
124
  getRootDomain() {
125
- return A(window.location.hostname);
125
+ return C(window.location.hostname);
126
126
  },
127
127
  // 获取Cookie
128
128
  getCookie(e) {
129
129
  const o = `; ${document.cookie}`.split(`; ${e}=`);
130
130
  return o.length === 2 && o.pop()?.split(";").shift() || null;
131
131
  },
132
- // 设置Cookie(会话 Cookie,2026-08-30:不设 expires —— 浏览器关闭即失效,
133
- // 下次打开需重新扫码登录;自动设置根域名实现跨子域共享)
134
- setCookie(e, t) {
135
- const o = this.getRootDomain(), n = o ? `;domain=${o}` : "", d = window.location.protocol === "https:" ? ";Secure" : "";
136
- document.cookie = `${e}=${t};path=/${n}${d};SameSite=Strict`;
132
+ // 设置Cookie(2026-09-04:不传 maxAgeMs 时仍是会话 Cookie —— 浏览器关闭即失效;
133
+ // 传入 maxAgeMs 则写持久 Cookie;自动设置根域名实现跨子域共享)
134
+ setCookie(e, t, o) {
135
+ const n = this.getRootDomain(), s = n ? `;domain=${n}` : "", y = window.location.protocol === "https:" ? ";Secure" : "", A = o !== void 0 ? `;expires=${new Date(Date.now() + o).toUTCString()}` : "";
136
+ document.cookie = `${e}=${t};path=/${s}${A}${y};SameSite=Strict`;
137
137
  },
138
138
  // 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
139
139
  deleteCookie(e) {
140
140
  const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", s = window.location.protocol === "https:" ? ";Secure" : "";
141
141
  document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${s};SameSite=Strict`;
142
142
  },
143
- // ===== 签名 Token 存储(会话 Cookie,2026-08-30)=====
144
- // 登录态策略:登录态只活在当前浏览器进程内——Cookie 不设 expires,浏览器
145
- // 关闭即失效,下次打开需重新扫码(web 定位为小程序引流入口,见 AGENTS.md)。
146
- // 旧版本的 localStorage 备份已移除:备份会让登录态在浏览器重启后"复活",
147
- // 击穿会话语义;clearToken 保留对旧备份 key 的防御性清理(升级用户的残留)。
143
+ // ===== 签名 Token 存储(持久 Cookie,3 天,2026-09-04)=====
144
+ // 登录态策略:web 登录态统一 3 天(此前为会话级——不设 expires,浏览器进程
145
+ // 关闭即失效)。现 Cookie 带 expires=3 天:浏览器关闭/重启登录态仍在,3 天
146
+ // 未使用才需重新登录;所有登录方式(小程序扫码 / 公众号验证码)一致。
147
+ // 背景(2026-09-04):原会话语义靠「每次浏览器会话强制扫码一次」把 web 当
148
+ // 小程序引流入口;广告/召回职能已由激励解锁(搜索次数触发看视频)独立承担,
149
+ // 每日强制重登只剩打断摩擦,故放宽(见主仓库 AGENTS.md)。
150
+ // 不引入 localStorage 备份:Cookie 已根域共享覆盖主站全部子域,备份无增益且
151
+ // 徒增残留清理面;clearToken 保留对旧版本备份 key 的防御性清理。
148
152
  // 存储的是签名 Token(HMAC,不可伪造),而非明文 openid(永久凭证)。
149
153
  // 注意:Cookie 是根域共享;localStorage 按站点隔离,且不再读取。
150
- // 读取:仅会话 Cookie(旧版本 localStorage 备份不再兜底)
154
+ // 读取:wxauth-token Cookie(旧版本 localStorage 备份不再兜底)
151
155
  getToken() {
152
156
  return this.getCookie("wxauth-token");
153
157
  },
154
- // 写入:仅会话 Cookie
158
+ // 写入:持久 Cookie(3 天)
155
159
  setToken(e) {
156
- this.setCookie("wxauth-token", e);
160
+ this.setCookie("wxauth-token", e, E);
157
161
  },
158
162
  // 删除:清 Cookie + 防御性清理旧版本 localStorage 备份残留
159
163
  // (同时清掉明文 openid Cookie —— 防御性清理,服务端已下线 openid 通道 2026-08-26)
@@ -197,19 +201,19 @@ const c = {
197
201
  return e += "</div>", e;
198
202
  }
199
203
  }, b = [1e3, 3e3];
200
- function v(e) {
204
+ function g(e) {
201
205
  const t = e;
202
206
  return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
203
207
  }
204
- function y(e) {
208
+ function x(e) {
205
209
  return new Promise((t) => setTimeout(t, e));
206
210
  }
207
- const C = 3e3, E = 2e3, I = 3e3;
211
+ const T = 3e3, I = 2e3, M = 3e3;
208
212
  function k() {
209
213
  h++;
210
214
  }
211
215
  async function S(e) {
212
- if (await y(C), !(e !== h || !a.isOpen)) {
216
+ if (await x(T), !(e !== h || !a.isOpen)) {
213
217
  for (; e === h && a.isOpen; ) {
214
218
  const t = a.mpSession;
215
219
  if (!t || Date.now() >= t.expiresAt) break;
@@ -228,45 +232,45 @@ async function S(e) {
228
232
  }
229
233
  } catch (o) {
230
234
  if (e !== h) return;
231
- if (!v(o)) break;
232
- await y(I);
235
+ if (!g(o)) break;
236
+ await x(M);
233
237
  continue;
234
238
  }
235
- await y(E);
239
+ await x(I);
236
240
  }
237
241
  e === h && a.isOpen && f === "mp" && l.showMpExpired();
238
242
  }
239
243
  }
240
- async function x(e) {
244
+ async function v(e) {
241
245
  const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${r.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
242
246
  for (let n = 0; ; n++)
243
247
  try {
244
248
  const s = await c.request(o);
245
249
  return s.authenticated ? { kind: "ok", result: s } : s.error === "rate_limited" || s.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: s };
246
250
  } catch (s) {
247
- if (!v(s) || n >= b.length)
251
+ if (!g(s) || n >= b.length)
248
252
  return { kind: "transient" };
249
- await y(b[n]);
253
+ await x(b[n]);
250
254
  }
251
255
  }
252
- const T = 300 * 1e3;
256
+ const $ = 300 * 1e3;
253
257
  let m = null;
254
- function M() {
258
+ function L() {
255
259
  return !m || Date.now() >= m.expiresAt ? (m = null, null) : {
256
260
  wechatName: m.wechatName,
257
261
  qrcodeUrl: m.qrcodeUrl
258
262
  };
259
263
  }
260
- async function $() {
264
+ async function N() {
261
265
  const e = u ? `?siteId=${encodeURIComponent(u)}` : "", t = await c.request(
262
266
  `${r.apiBase}/api/sdk/config${e}`
263
267
  ), o = {
264
268
  wechatName: t.wechatName,
265
269
  qrcodeUrl: t.qrcodeUrl
266
270
  };
267
- return m = { ...o, expiresAt: Date.now() + T }, o;
271
+ return m = { ...o, expiresAt: Date.now() + $ }, o;
268
272
  }
269
- function L(e) {
273
+ function P(e) {
270
274
  e.wechatName && !r.wechatName && (r.wechatName = e.wechatName), e.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = e.qrcodeUrl);
271
275
  }
272
276
  const l = {
@@ -346,8 +350,8 @@ const l = {
346
350
  }), t.addEventListener("paste", (n) => {
347
351
  n.preventDefault();
348
352
  const s = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
349
- s && (s.split("").forEach((d, g) => {
350
- e[g] && (e[g].value = d);
353
+ s && (s.split("").forEach((d, y) => {
354
+ e[y] && (e[y].value = d);
351
355
  }), s.length === 6 && setTimeout(() => w.verifyCode(), 300));
352
356
  });
353
357
  });
@@ -456,7 +460,7 @@ const l = {
456
460
  async silentCheck() {
457
461
  const e = c.getToken();
458
462
  if (!e) return !1;
459
- const t = await x(e);
463
+ const t = await v(e);
460
464
  return t.kind === "ok" ? (t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
461
465
  },
462
466
  // 自动检测凭证并验证(内部使用)
@@ -464,7 +468,7 @@ const l = {
464
468
  const e = c.getToken();
465
469
  if (!e)
466
470
  return this.showAuthModal(), !1;
467
- const t = await x(e);
471
+ const t = await v(e);
468
472
  return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
469
473
  code: "server_error",
470
474
  retryable: !0,
@@ -477,14 +481,14 @@ const l = {
477
481
  // /api/sdk/config(公众号名称/码图)改为后台拉取,不再阻塞渲染。
478
482
  async showAuthModal() {
479
483
  l.show(), this.switchMode("mp");
480
- let e = M();
484
+ let e = L();
481
485
  if (!e)
482
486
  try {
483
- e = await $();
487
+ e = await N();
484
488
  } catch (o) {
485
489
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", o);
486
490
  }
487
- e && L(e), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
491
+ e && P(e), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
488
492
  const t = document.querySelector(".wx-auth-wechat-name");
489
493
  t && r.wechatName && (t.textContent = `"${r.wechatName}"`), setTimeout(() => {
490
494
  const o = document.querySelector(".wx-auth-input");
@@ -528,11 +532,12 @@ const l = {
528
532
  }
529
533
  },
530
534
  // 主入口:需要验证时调用
531
- // 凭证仅签名 Token(会话 Cookie),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
535
+ // 凭证仅签名 Token(登录 Cookie,3 天持久,2026-09-04),不再兼容明文 openid
536
+ // (2026-08-26 服务端已下线 openid 通道)
532
537
  async requireAuth() {
533
538
  const e = c.getToken();
534
539
  if (e) {
535
- const t = await x(e);
540
+ const t = await v(e);
536
541
  if (t.kind === "ok")
537
542
  return console.log("[WxAuth] 已认证(凭证)"), t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0;
538
543
  if (t.kind === "transient")
@@ -582,7 +587,7 @@ const l = {
582
587
  ), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
583
588
  } catch (o) {
584
589
  l.showMessage(
585
- v(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
590
+ g(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
586
591
  "error"
587
592
  ), t && (t.disabled = !1, t.textContent = "登录");
588
593
  }
@@ -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-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-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 d=r;if(d.id===e.modalId||d.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()}},S={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...S},l="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},p="code",h=0;function E(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 E(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=this.getRootDomain(),n=o?`;domain=${o}`:"",d=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};path=/${n}${d};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",r=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`},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{}},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}},q=[1e3,3e3];function b(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function y(e){return new Promise(t=>setTimeout(t,e))}const I=3e3,T=2e3,M=3e3;function k(){h++}async function C(e){if(await y(I),!(e!==h||!s.isOpen)){for(;e===h&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==h)return;if(o.status==="confirmed"&&o.token){g.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==h)return;if(!b(o))break;await y(M);continue}await y(T)}e===h&&s.isOpen&&p==="mp"&&u.showMpExpired()}}async function v(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.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(!b(r)||n>=q.length)return{kind:"transient"};await y(q[n])}}const $=300*1e3;let x=null;function D(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function P(){const e=l?`?siteId=${encodeURIComponent(l)}`:"",t=await c.request(`${a.apiBase}/api/sdk/config${e}`),o={wechatName:t.wechatName,qrcodeUrl:t.qrcodeUrl};return x={...o,expiresAt:Date.now()+$},o}function L(e){e.wechatName&&!a.wechatName&&(a.wechatName=e.wechatName),e.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=e.qrcodeUrl)}const u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>',o=`<div class="wx-auth-tabs">
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 d=r;if(d.id===e.modalId||d.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()}},C={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...C},l="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},p="code",h=0;function E(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 T=4320*60*1e3,c={getRootDomain(){return E(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t,o){const n=this.getRootDomain(),r=n?`;domain=${n}`:"",b=window.location.protocol==="https:"?";Secure":"",U=o!==void 0?`;expires=${new Date(Date.now()+o).toUTCString()}`:"";document.cookie=`${e}=${t};path=/${r}${U}${b};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",r=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`},getToken(){return this.getCookie("wxauth-token")},setToken(e){this.setCookie("wxauth-token",e,T)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}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){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}},q=[1e3,3e3];function k(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function y(e){return new Promise(t=>setTimeout(t,e))}const I=3e3,M=2e3,$=3e3;function v(){h++}async function A(e){if(await y(I),!(e!==h||!s.isOpen)){for(;e===h&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==h)return;if(o.status==="confirmed"&&o.token){g.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==h)return;if(!k(o))break;await y($);continue}await y(M)}e===h&&s.isOpen&&p==="mp"&&u.showMpExpired()}}async function S(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.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(!k(r)||n>=q.length)return{kind:"transient"};await y(q[n])}}const D=300*1e3;let x=null;function P(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function L(){const e=l?`?siteId=${encodeURIComponent(l)}`:"",t=await c.request(`${a.apiBase}/api/sdk/config${e}`),o={wechatName:t.wechatName,qrcodeUrl:t.qrcodeUrl};return x={...o,expiresAt:Date.now()+D},o}function N(e){e.wechatName&&!a.wechatName&&(a.wechatName=e.wechatName),e.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=e.qrcodeUrl)}const u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>',o=`<div class="wx-auth-tabs">
3
3
  <button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
4
4
  <button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
5
5
  </div>`,n=`<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
@@ -52,4 +52,4 @@
52
52
  <div class="wx-auth-message" style="display:none"></div>
53
53
  </div>
54
54
  </div>
55
- `,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 r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>g.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((d,A)=>{e[A]&&(e[A].value=d)}),r.length===6&&setTimeout(()=>g.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.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="");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=""),k(),s.mpSession=null,e.style.display="flex",s.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&a.wechatName&&(r.textContent=`"${a.wechatName}"`),this.bindInputEvents(),p==="mp"&&g.switchMode("mp"),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",s.isOpen=!1,k(),s.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 d=o?.querySelector(".wx-auth-mp-qrcode");d&&(d.style.display="none")}},showMpExpired(){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()}},g={init(e={}){if(a={...S,...e},x=null,!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{l=new URL(t).hostname}catch{}!l&&window.location.hostname&&(l=window.location.hostname),l||(l="default"),console.log("[WxAuth] 自动获取 siteId:",l)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await v(e);return t.kind==="ok"?(t.result.token&&c.setToken(t.result.token),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 v(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&c.setToken(t.result.token),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(){u.show(),this.switchMode("mp");let e=D();if(!e)try{e=await P()}catch(o){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",o)}e&&L(e),a.qrcodeUrl&&u.setQrCode(a.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&a.wechatName&&(t.textContent=`"${a.wechatName}"`),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)},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():k()},async startMpLogin(){if(!s.isOpen)return;const e=++h;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){u.setMpQr(s.mpSession.qrDataUrl),C(e);return}try{const t=await c.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:l}});if(e!==h||!s.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");s.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(s.mpSession.qrDataUrl),C(e)}catch(t){if(e!==h||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码",t),this.switchMode("code"),u.showMessage("小程序扫码暂不可用,请使用公众号验证码登录","error")}},async requireAuth(){const e=c.getToken();if(e){const t=await v(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{s.resolveAuth=t})},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=l?`&siteId=${encodeURIComponent(l)}`:"",n=await c.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?this.completeLogin(n):(u.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(b(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.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 a.onVerified=="function"&&a.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(g)),w.WxAuth=g,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
55
+ `,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 r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>g.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((d,b)=>{e[b]&&(e[b].value=d)}),r.length===6&&setTimeout(()=>g.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.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="");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=""),v(),s.mpSession=null,e.style.display="flex",s.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&a.wechatName&&(r.textContent=`"${a.wechatName}"`),this.bindInputEvents(),p==="mp"&&g.switchMode("mp"),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",s.isOpen=!1,v(),s.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 d=o?.querySelector(".wx-auth-mp-qrcode");d&&(d.style.display="none")}},showMpExpired(){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()}},g={init(e={}){if(a={...C,...e},x=null,!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{l=new URL(t).hostname}catch{}!l&&window.location.hostname&&(l=window.location.hostname),l||(l="default"),console.log("[WxAuth] 自动获取 siteId:",l)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await S(e);return t.kind==="ok"?(t.result.token&&c.setToken(t.result.token),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 S(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&c.setToken(t.result.token),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(){u.show(),this.switchMode("mp");let e=P();if(!e)try{e=await L()}catch(o){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",o)}e&&N(e),a.qrcodeUrl&&u.setQrCode(a.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&a.wechatName&&(t.textContent=`"${a.wechatName}"`),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)},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():v()},async startMpLogin(){if(!s.isOpen)return;const e=++h;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){u.setMpQr(s.mpSession.qrDataUrl),A(e);return}try{const t=await c.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:l}});if(e!==h||!s.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");s.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(s.mpSession.qrDataUrl),A(e)}catch(t){if(e!==h||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码",t),this.switchMode("code"),u.showMessage("小程序扫码暂不可用,请使用公众号验证码登录","error")}},async requireAuth(){const e=c.getToken();if(e){const t=await S(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{s.resolveAuth=t})},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=l?`&siteId=${encodeURIComponent(l)}`:"",n=await c.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?this.completeLogin(n):(u.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(k(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.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 a.onVerified=="function"&&a.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(g)),w.WxAuth=g,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.33",
3
+ "version": "1.2.34",
4
4
  "description": "微信登录 SDK - 小程序扫码 / 公众号验证码双方式,零依赖",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",