wx-auth-sdk 1.2.37 → 1.2.38

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
@@ -12,9 +12,9 @@ const i = {
12
12
  i.observer && (i.observer.disconnect(), i.observer = null), i.rafId !== null && (cancelAnimationFrame(i.rafId), i.rafId = null), i.isProtected = !0, i.restorePending = !1, i.observer = new MutationObserver((o) => {
13
13
  for (const n of o)
14
14
  if (n.type === "childList")
15
- for (const s of n.removedNodes) {
16
- if (s.nodeType !== Node.ELEMENT_NODE) continue;
17
- const d = s;
15
+ for (const r of n.removedNodes) {
16
+ if (r.nodeType !== Node.ELEMENT_NODE) continue;
17
+ const d = r;
18
18
  if (d.id === e.modalId || d.querySelector?.(`#${e.modalId}`)) {
19
19
  console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), p.safeRestore(e);
20
20
  return;
@@ -79,9 +79,9 @@ const i = {
79
79
  restoreFn(e) {
80
80
  const { modalId: t, getState: o, onRestore: n } = e;
81
81
  if (!o().isOpen) return;
82
- const s = document.getElementById(t);
83
- if (s) {
84
- s.style.display = "flex", s.style.visibility = "visible", s.style.opacity = "1";
82
+ const r = document.getElementById(t);
83
+ if (r) {
84
+ r.style.display = "flex", r.style.visibility = "visible", r.style.opacity = "1";
85
85
  return;
86
86
  }
87
87
  n();
@@ -104,7 +104,7 @@ const i = {
104
104
  silent: !1
105
105
  // 默认不静默
106
106
  };
107
- let r = { ...q }, c = "", a = {
107
+ let s = { ...q }, u = "", v = "", a = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
110
  currentStep: "qr",
@@ -120,7 +120,7 @@ function E(e) {
120
120
  return "";
121
121
  }
122
122
  }
123
- const u = {
123
+ const l = {
124
124
  getRootDomain() {
125
125
  return E(window.location.hostname);
126
126
  },
@@ -130,9 +130,9 @@ const u = {
130
130
  return o.length === 2 && o.pop()?.split(";").shift() || null;
131
131
  },
132
132
  // Cookie 写入底层(domainStr 传空串 = host-only,落在当前 host 本域)
133
- writeCookieRaw(e, t, o, n, s = !1) {
134
- const d = n ? `;domain=${n}` : "", C = window.location.protocol === "https:" ? ";Secure" : "", A = s ? ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : o !== void 0 ? `;expires=${new Date(Date.now() + o).toUTCString()}` : "";
135
- document.cookie = `${e}=${s ? "" : t};path=/${d}${A}${C};SameSite=Strict`;
133
+ writeCookieRaw(e, t, o, n, r = !1) {
134
+ const d = n ? `;domain=${n}` : "", A = window.location.protocol === "https:" ? ";Secure" : "", I = r ? ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : o !== void 0 ? `;expires=${new Date(Date.now() + o).toUTCString()}` : "";
135
+ document.cookie = `${e}=${r ? "" : t};path=/${d}${I}${A};SameSite=Strict`;
136
136
  },
137
137
  // 设置Cookie(2026-09-04:不传 maxAgeMs 时仍是会话 Cookie —— 浏览器关闭即失效;
138
138
  // 传入 maxAgeMs 则写持久 Cookie;自动设置根域名实现跨子域共享)
@@ -177,6 +177,33 @@ const u = {
177
177
  } catch {
178
178
  }
179
179
  },
180
+ // ===== 设备标识(2026-09-12,风控)=====
181
+ // wxauth-device:随机 32 位 hex 持久 Cookie(1 年),localStorage 镜像兜底
182
+ // (Cookie 被清理/写入失败时从镜像恢复,避免设备身份漂移)。
183
+ // 注意:这是设备身份不是凭证——退出登录(clearToken/revoke)不清除它。
184
+ getOrCreateDeviceId() {
185
+ if (v) return v;
186
+ let e = this.getCookie("wxauth-device");
187
+ if (!e)
188
+ try {
189
+ e = window.localStorage.getItem("wxauth-device");
190
+ } catch {
191
+ }
192
+ if (!e || !/^[A-Za-z0-9_-]{1,64}$/.test(e)) {
193
+ const t = new Uint8Array(16);
194
+ if (typeof crypto < "u" && crypto.getRandomValues)
195
+ crypto.getRandomValues(t);
196
+ else
197
+ for (let o = 0; o < 16; o++) t[o] = Math.floor(Math.random() * 256);
198
+ e = Array.from(t).map((o) => o.toString(16).padStart(2, "0")).join("");
199
+ }
200
+ this.setCookie("wxauth-device", e, 365 * 86400 * 1e3);
201
+ try {
202
+ window.localStorage.setItem("wxauth-device", e);
203
+ } catch {
204
+ }
205
+ return v = e, e;
206
+ },
180
207
  // 发送请求
181
208
  // 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
182
209
  // 供调用方区分「明确未认证」与「瞬时失败」——后者不应触发重新验证(2026-08-29)
@@ -209,16 +236,16 @@ const u = {
209
236
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
210
237
  return e += "</div>", e;
211
238
  }
212
- }, b = [1e3, 3e3];
213
- function g(e) {
239
+ }, C = [1e3, 3e3];
240
+ function b(e) {
214
241
  const t = e;
215
242
  return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
216
243
  }
217
244
  function y(e) {
218
245
  return new Promise((t) => setTimeout(t, e));
219
246
  }
220
- const T = 3e3, I = 2e3, M = 3e3;
221
- function v() {
247
+ const T = 3e3, M = 2e3, $ = 3e3;
248
+ function k() {
222
249
  h++;
223
250
  }
224
251
  async function S(e) {
@@ -227,8 +254,8 @@ async function S(e) {
227
254
  const t = a.mpSession;
228
255
  if (!t || Date.now() >= t.expiresAt) break;
229
256
  try {
230
- const o = await u.request(
231
- `${r.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
257
+ const o = await l.request(
258
+ `${s.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
232
259
  );
233
260
  if (e !== h) return;
234
261
  if (o.status === "confirmed" && o.token) {
@@ -241,28 +268,28 @@ async function S(e) {
241
268
  }
242
269
  } catch (o) {
243
270
  if (e !== h) return;
244
- if (!g(o)) break;
245
- await y(M);
271
+ if (!b(o)) break;
272
+ await y($);
246
273
  continue;
247
274
  }
248
- await y(I);
275
+ await y(M);
249
276
  }
250
- e === h && a.isOpen && f === "mp" && l.showMpExpired();
277
+ e === h && a.isOpen && f === "mp" && c.showMpExpired();
251
278
  }
252
279
  }
253
- async function k(e) {
254
- const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `${r.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
280
+ async function g(e) {
281
+ const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${s.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
255
282
  for (let n = 0; ; n++)
256
283
  try {
257
- const s = await u.request(o);
258
- return s.authenticated ? { kind: "ok", result: s } : s.error === "rate_limited" || s.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: s };
259
- } catch (s) {
260
- if (!g(s) || n >= b.length)
284
+ const r = await l.request(o);
285
+ return r.authenticated ? { kind: "ok", result: r } : r.error === "rate_limited" || r.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: r };
286
+ } catch (r) {
287
+ if (!b(r) || n >= C.length)
261
288
  return { kind: "transient" };
262
- await y(b[n]);
289
+ await y(C[n]);
263
290
  }
264
291
  }
265
- const $ = 300 * 1e3;
292
+ const D = 300 * 1e3;
266
293
  let m = null;
267
294
  function L() {
268
295
  return !m || Date.now() >= m.expiresAt ? (m = null, null) : {
@@ -270,26 +297,26 @@ function L() {
270
297
  qrcodeUrl: m.qrcodeUrl
271
298
  };
272
299
  }
273
- async function N() {
274
- const e = c ? `?siteId=${encodeURIComponent(c)}` : "", t = await u.request(
275
- `${r.apiBase}/api/sdk/config${e}`
300
+ async function P() {
301
+ const e = u ? `?siteId=${encodeURIComponent(u)}` : "", t = await l.request(
302
+ `${s.apiBase}/api/sdk/config${e}`
276
303
  ), o = {
277
304
  wechatName: t.wechatName,
278
305
  qrcodeUrl: t.qrcodeUrl
279
306
  };
280
- return m = { ...o, expiresAt: Date.now() + $ }, o;
307
+ return m = { ...o, expiresAt: Date.now() + D }, o;
281
308
  }
282
- function P(e) {
283
- e.wechatName && !r.wechatName && (r.wechatName = e.wechatName), e.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = e.qrcodeUrl);
309
+ function R(e) {
310
+ e.wechatName && !s.wechatName && (s.wechatName = e.wechatName), e.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = e.qrcodeUrl);
284
311
  }
285
- const l = {
312
+ const c = {
286
313
  // 创建弹窗
287
314
  // 形态固定为双 tab(2026-08-30 去掉 mpScanEnabled 门控):形态不依赖 config,
288
315
  // 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab)结构上不存在
289
316
  createModal() {
290
317
  const e = document.createElement("div");
291
- e.id = "wx-auth-modal", e.className = "wx-auth-modal", r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
292
- const t = r.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>', o = `<div class="wx-auth-tabs">
318
+ e.id = "wx-auth-modal", e.className = "wx-auth-modal", s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
319
+ const t = s.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>', o = `<div class="wx-auth-tabs">
293
320
  <button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
294
321
  <button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
295
322
  </div>`, n = `<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
@@ -305,7 +332,7 @@ const l = {
305
332
  <div class="wx-auth-mp-status"></div>
306
333
  </div>`;
307
334
  return e.innerHTML = `
308
- <div class="wx-auth-overlay" ${r.required ? 'onclick="event.preventDefault()"' : ""}></div>
335
+ <div class="wx-auth-overlay" ${s.required ? 'onclick="event.preventDefault()"' : ""}></div>
309
336
  <div class="wx-auth-content">
310
337
  <div class="wx-auth-header">
311
338
  <div class="wx-auth-title">微信登录</div>
@@ -327,7 +354,7 @@ const l = {
327
354
  <!-- 验证码输入区域 -->
328
355
  <div>
329
356
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
330
- ${u.generateCodeInputs()}
357
+ ${l.generateCodeInputs()}
331
358
  </div>
332
359
 
333
360
  <!-- 按钮 -->
@@ -351,17 +378,17 @@ const l = {
351
378
  const e = document.querySelectorAll(".wx-auth-input");
352
379
  e.length && e.forEach((t, o) => {
353
380
  t.addEventListener("input", (n) => {
354
- const s = n.target.value.replace(/\D/g, "");
355
- n.target.value = s, s && o < 5 && e[o + 1].focus(), o === 5 && s && setTimeout(() => w.verifyCode(), 300);
381
+ const r = n.target.value.replace(/\D/g, "");
382
+ n.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => w.verifyCode(), 300);
356
383
  }), t.addEventListener("keydown", (n) => {
357
- const s = n.target;
358
- n.key === "Backspace" && !s.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());
384
+ const r = n.target;
385
+ 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());
359
386
  }), t.addEventListener("paste", (n) => {
360
387
  n.preventDefault();
361
- const s = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
362
- s && (s.split("").forEach((d, x) => {
388
+ const r = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
389
+ r && (r.split("").forEach((d, x) => {
363
390
  e[x] && (e[x].value = d);
364
- }), s.length === 6 && setTimeout(() => w.verifyCode(), 300));
391
+ }), r.length === 6 && setTimeout(() => w.verifyCode(), 300));
365
392
  });
366
393
  });
367
394
  }, 100);
@@ -369,17 +396,17 @@ const l = {
369
396
  // 显示弹窗
370
397
  show() {
371
398
  let e = document.getElementById("wx-auth-modal");
372
- e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.querySelectorAll(".wx-auth-input").forEach((s) => s.value = "");
399
+ e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.querySelectorAll(".wx-auth-input").forEach((r) => r.value = "");
373
400
  const o = e.querySelector(".wx-auth-message");
374
401
  o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
375
402
  const n = e.querySelector(".wx-auth-btn-primary");
376
- n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), v(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, p.enable({
403
+ n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), k(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, p.enable({
377
404
  modalId: "wx-auth-modal",
378
405
  getState: () => a,
379
406
  onRestore: () => {
380
- this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
381
- const s = document.querySelector(".wx-auth-wechat-name");
382
- s && r.wechatName && (s.textContent = `"${r.wechatName}"`), this.bindInputEvents(), f === "mp" && w.switchMode("mp"), setTimeout(() => {
407
+ this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
408
+ const r = document.querySelector(".wx-auth-wechat-name");
409
+ r && s.wechatName && (r.textContent = `"${s.wechatName}"`), this.bindInputEvents(), f === "mp" && w.switchMode("mp"), setTimeout(() => {
383
410
  const d = document.querySelector(".wx-auth-input");
384
411
  d && d.focus();
385
412
  }, 100);
@@ -389,7 +416,7 @@ const l = {
389
416
  // 隐藏弹窗
390
417
  hide() {
391
418
  const e = document.getElementById("wx-auth-modal");
392
- e && (e.style.display = "none", a.isOpen = !1, v(), a.mpSession = null, p.disable());
419
+ e && (e.style.display = "none", a.isOpen = !1, k(), a.mpSession = null, p.disable());
393
420
  },
394
421
  // 设置二维码
395
422
  setQrCode(e) {
@@ -412,8 +439,8 @@ const l = {
412
439
  setMpStatus(e, t) {
413
440
  const o = document.getElementById("wx-auth-modal"), n = o?.querySelector(".wx-auth-mp-status");
414
441
  n && (n.textContent = e, n.style.display = e ? "block" : "none");
415
- const s = o?.querySelector(".wx-auth-mp-loading");
416
- if (s && (s.style.display = t ? "flex" : "none"), t) {
442
+ const r = o?.querySelector(".wx-auth-mp-loading");
443
+ if (r && (r.style.display = t ? "flex" : "none"), t) {
417
444
  const d = o?.querySelector(".wx-auth-mp-qrcode");
418
445
  d && (d.style.display = "none");
419
446
  }
@@ -442,7 +469,7 @@ const l = {
442
469
  }, w = {
443
470
  // 初始化
444
471
  init(e = {}) {
445
- if (r = { ...q, ...e }, m = null, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
472
+ if (s = { ...q, ...e }, m = null, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
446
473
  console.error("[WxAuth] apiBase is required");
447
474
  return;
448
475
  }
@@ -450,12 +477,14 @@ const l = {
450
477
  const t = document.referrer;
451
478
  if (t)
452
479
  try {
453
- c = new URL(t).hostname;
480
+ u = new URL(t).hostname;
454
481
  } catch {
455
482
  }
456
- !c && window.location.hostname && (c = window.location.hostname), c || (c = "default"), console.log("[WxAuth] 自动获取 siteId:", c);
483
+ !u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
484
+ const o = l.getOrCreateDeviceId();
485
+ console.log("[WxAuth] deviceId:", o);
457
486
  }
458
- console.log("[WxAuth] SDK initialized", r), typeof window < "u" && (r.silent ? this.silentCheck() : this.autoCheck());
487
+ console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
459
488
  },
460
489
  /**
461
490
  * 静默验证(silent 模式专用)
@@ -467,18 +496,18 @@ const l = {
467
496
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
468
497
  */
469
498
  async silentCheck() {
470
- const e = u.getToken();
499
+ const e = l.getToken();
471
500
  if (!e) return !1;
472
- const t = await k(e);
473
- return t.kind === "ok" ? (t.result.token && u.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
501
+ const t = await g(e);
502
+ return t.kind === "ok" ? (t.result.token && l.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
474
503
  },
475
504
  // 自动检测凭证并验证(内部使用)
476
505
  async autoCheck() {
477
- const e = u.getToken();
506
+ const e = l.getToken();
478
507
  if (!e)
479
508
  return this.showAuthModal(), !1;
480
- const t = await k(e);
481
- return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && u.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
509
+ const t = await g(e);
510
+ return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && l.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
482
511
  code: "server_error",
483
512
  retryable: !0,
484
513
  message: "登录服务暂时不可用,请稍后重试"
@@ -489,17 +518,17 @@ const l = {
489
518
  // UI.show() 同步渲染 + 默认小程序扫码立即出码,全程只有一种形态,无中间态;
490
519
  // /api/sdk/config(公众号名称/码图)改为后台拉取,不再阻塞渲染。
491
520
  async showAuthModal() {
492
- l.show(), this.switchMode("mp");
521
+ c.show(), this.switchMode("mp");
493
522
  let e = L();
494
523
  if (!e)
495
524
  try {
496
- e = await N();
525
+ e = await P();
497
526
  } catch (o) {
498
527
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", o);
499
528
  }
500
- e && P(e), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
529
+ e && R(e), s.qrcodeUrl && c.setQrCode(s.qrcodeUrl);
501
530
  const t = document.querySelector(".wx-auth-wechat-name");
502
- t && r.wechatName && (t.textContent = `"${r.wechatName}"`), setTimeout(() => {
531
+ t && s.wechatName && (t.textContent = `"${s.wechatName}"`), setTimeout(() => {
503
532
  const o = document.querySelector(".wx-auth-input");
504
533
  o && o.focus();
505
534
  }, 100);
@@ -509,24 +538,24 @@ const l = {
509
538
  f = e;
510
539
  const t = document.getElementById("wx-auth-modal");
511
540
  if (!t) return;
512
- t.querySelectorAll(".wx-auth-tab").forEach((s) => {
513
- s.classList.toggle("wx-auth-tab-active", s.dataset.mode === f);
541
+ t.querySelectorAll(".wx-auth-tab").forEach((r) => {
542
+ r.classList.toggle("wx-auth-tab-active", r.dataset.mode === f);
514
543
  });
515
544
  const o = t.querySelector(".wx-auth-panel-code"), n = t.querySelector(".wx-auth-panel-mp");
516
- o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : v();
545
+ o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : k();
517
546
  },
518
547
  // 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
519
548
  async startMpLogin() {
520
549
  if (!a.isOpen) return;
521
550
  const e = ++h;
522
- if (l.setMpExpiredVisible(!1), l.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
523
- l.setMpQr(a.mpSession.qrDataUrl), S(e);
551
+ if (c.setMpExpiredVisible(!1), c.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
552
+ c.setMpQr(a.mpSession.qrDataUrl), S(e);
524
553
  return;
525
554
  }
526
555
  try {
527
- const t = await u.request(`${r.apiBase}/api/auth/mp-scan/create`, {
556
+ const t = await l.request(`${s.apiBase}/api/auth/mp-scan/create`, {
528
557
  method: "POST",
529
- body: { siteId: c }
558
+ body: { siteId: u }
530
559
  });
531
560
  if (e !== h || !a.isOpen) return;
532
561
  if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
@@ -534,21 +563,21 @@ const l = {
534
563
  ticket: String(t.ticket),
535
564
  qrDataUrl: String(t.qrDataUrl),
536
565
  expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
537
- }, l.setMpQr(a.mpSession.qrDataUrl), S(e);
566
+ }, c.setMpQr(a.mpSession.qrDataUrl), S(e);
538
567
  } catch (t) {
539
568
  if (e !== h || !a.isOpen) return;
540
- console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"), l.showMessage("小程序扫码暂不可用,请使用公众号验证码登录", "error");
569
+ console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"), c.showMessage("小程序扫码暂不可用,请使用公众号验证码登录", "error");
541
570
  }
542
571
  },
543
572
  // 主入口:需要验证时调用
544
573
  // 凭证仅签名 Token(登录 Cookie,会话级,2026-09-05),不再兼容明文 openid
545
574
  // (2026-08-26 服务端已下线 openid 通道)
546
575
  async requireAuth() {
547
- const e = u.getToken();
576
+ const e = l.getToken();
548
577
  if (e) {
549
- const t = await k(e);
578
+ const t = await g(e);
550
579
  if (t.kind === "ok")
551
- return console.log("[WxAuth] 已认证(凭证)"), t.result.token && u.setToken(t.result.token), this.onVerified(t.result.user), !0;
580
+ return console.log("[WxAuth] 已认证(凭证)"), t.result.token && l.setToken(t.result.token), this.onVerified(t.result.user), !0;
552
581
  if (t.kind === "transient")
553
582
  return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
554
583
  code: "server_error",
@@ -565,8 +594,8 @@ const l = {
565
594
  // 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
566
595
  // close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
567
596
  completeLogin(e) {
568
- if (e?.token && u.setToken(e.token), f === "mp")
569
- l.setMpStatus("✅ 登录成功", !1);
597
+ if (e?.token && l.setToken(e.token), f === "mp")
598
+ c.setMpStatus("✅ 登录成功", !1);
570
599
  else {
571
600
  const t = document.querySelector(".wx-auth-btn-primary");
572
601
  t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
@@ -577,9 +606,9 @@ const l = {
577
606
  },
578
607
  // 验证验证码
579
608
  async verifyCode() {
580
- const e = l.getVerifyCode();
609
+ const e = c.getVerifyCode();
581
610
  if (!e || e.length !== 6) {
582
- l.showMessage("请输入6位验证码", "error");
611
+ c.showMessage("请输入6位验证码", "error");
583
612
  return;
584
613
  }
585
614
  const t = document.querySelector(
@@ -587,16 +616,16 @@ const l = {
587
616
  );
588
617
  t && (t.disabled = !0, t.textContent = "登录中...");
589
618
  try {
590
- const o = c ? `&siteId=${encodeURIComponent(c)}` : "", n = await u.request(
591
- `${r.apiBase}/api/auth/check?authToken=${e}${o}`
619
+ const o = u ? `&siteId=${encodeURIComponent(u)}` : "", n = `&deviceId=${encodeURIComponent(l.getOrCreateDeviceId())}`, r = await l.request(
620
+ `${s.apiBase}/api/auth/check?authToken=${e}${o}${n}`
592
621
  );
593
- n.authenticated ? this.completeLogin(n) : (l.showMessage(
594
- n.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
622
+ r.authenticated ? this.completeLogin(r) : (c.showMessage(
623
+ r.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
595
624
  "error"
596
- ), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
625
+ ), c.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
597
626
  } catch (o) {
598
- l.showMessage(
599
- g(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
627
+ c.showMessage(
628
+ b(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
600
629
  "error"
601
630
  ), t && (t.disabled = !1, t.textContent = "登录");
602
631
  }
@@ -605,12 +634,12 @@ const l = {
605
634
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
606
635
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
607
636
  close(e = !1) {
608
- l.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
637
+ c.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
609
638
  },
610
639
  // 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
611
640
  // 用于"退出登录 / 清空认证状态"按钮。
612
641
  clearToken() {
613
- u.clearToken();
642
+ l.clearToken();
614
643
  },
615
644
  // 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
616
645
  // 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
@@ -621,13 +650,14 @@ const l = {
621
650
  // 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
622
651
  // 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
623
652
  async revoke() {
624
- const e = u.getToken();
653
+ const e = l.getToken();
625
654
  if (e)
626
655
  try {
627
- const t = r.apiBase && !/\/$/.test(r.apiBase) ? r.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
656
+ const t = s.apiBase && !/\/$/.test(s.apiBase) ? s.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
628
657
  method: "POST",
629
658
  headers: { "Content-Type": "application/json" },
630
- body: JSON.stringify({ token: e }),
659
+ // deviceId 显式携带(跨站 SameSite 下 Cookie 不可靠);设备身份不因退出而清除
660
+ body: JSON.stringify({ token: e, deviceId: l.getOrCreateDeviceId() }),
631
661
  credentials: "include"
632
662
  });
633
663
  o.ok || console.warn("[WxAuth] revoke 请求失败,降级本地清理", o.status);
@@ -638,11 +668,11 @@ const l = {
638
668
  },
639
669
  // 验证成功回调
640
670
  onVerified(e) {
641
- console.log("[WxAuth] 验证成功", e), typeof r.onVerified == "function" && r.onVerified(e), a.resolveAuth && (a.resolveAuth(!0), a.resolveAuth = null);
671
+ console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), a.resolveAuth && (a.resolveAuth(!0), a.resolveAuth = null);
642
672
  },
643
673
  // 错误回调
644
674
  onError(e) {
645
- console.error("[WxAuth] 错误", e), typeof r.onError == "function" && r.onError(e);
675
+ console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
646
676
  }
647
677
  };
648
678
  typeof window < "u" && (window.WxAuth = Object.freeze(w));
@@ -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 T(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 T(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 d=n?`;domain=${n}`:"",U=window.location.protocol==="https:"?";Secure":"",N=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=/${d}${N}${U};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{}},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 E=3e3,I=2e3,M=3e3;function k(){h++}async function A(e){if(await y(E),!(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(I)}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 D=300*1e3;let x=null;function $(){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()+D},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()}},q={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...q},l="",b="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},p="code",h=0;function T(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 T(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 d=n?`;domain=${n}`:"",R=window.location.protocol==="https:"?";Secure":"",N=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=/${d}${N}${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(b)return b;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 b=e,e},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}},A=[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 E=3e3,M=2e3,D=3e3;function v(){h++}async function I(e){if(await y(E),!(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(D);continue}await y(M)}e===h&&s.isOpen&&p==="mp"&&u.showMpExpired()}}async function C(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>=A.length)return{kind:"transient"};await y(A[n])}}const $=300*1e3;let x=null;function P(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function U(){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">
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,C)=>{e[C]&&(e[C].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=$();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),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 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,S)=>{e[S]&&(e[S].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={...q,...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);const o=c.getOrCreateDeviceId();console.log("[WxAuth] deviceId:",o)}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 C(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 C(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 U()}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():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),I(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),I(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 C(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=`&deviceId=${encodeURIComponent(c.getOrCreateDeviceId())}`,r=await c.request(`${a.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(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,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 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.37",
3
+ "version": "1.2.38",
4
4
  "description": "微信登录 SDK - 小程序扫码 / 公众号验证码双方式,零依赖",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",