wx-auth-sdk 1.2.23 → 1.2.24

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
@@ -10,12 +10,12 @@ const i = {
10
10
  enable(e) {
11
11
  if (i.isProtected || typeof window > "u") return;
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
- for (const n of o)
14
- if (n.type === "childList")
15
- for (const r of n.removedNodes) {
16
- if (r.nodeType !== Node.ELEMENT_NODE) continue;
17
- const u = r;
18
- if (u.id === e.modalId || u.querySelector?.(`#${e.modalId}`)) {
13
+ for (const r of o)
14
+ if (r.type === "childList")
15
+ for (const n of r.removedNodes) {
16
+ if (n.nodeType !== Node.ELEMENT_NODE) continue;
17
+ const l = n;
18
+ if (l.id === e.modalId || l.querySelector?.(`#${e.modalId}`)) {
19
19
  console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
20
20
  return;
21
21
  }
@@ -31,10 +31,10 @@ const i = {
31
31
  i.rafId = null;
32
32
  return;
33
33
  }
34
- const n = document.getElementById(e.modalId);
35
- (!n || !n.isConnected || h.isHidden(n)) && (console.warn(
34
+ const r = document.getElementById(e.modalId);
35
+ (!r || !r.isConnected || h.isHidden(r)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
- { has: !!n, connected: n?.isConnected, hidden: n ? h.isHidden(n) : null }
37
+ { has: !!r, connected: r?.isConnected, hidden: r ? h.isHidden(r) : null }
38
38
  ), h.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
39
39
  };
40
40
  i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
@@ -77,16 +77,16 @@ const i = {
77
77
  * 恢复弹窗
78
78
  */
79
79
  restoreFn(e) {
80
- const { modalId: t, getState: o, onRestore: n } = e;
80
+ const { modalId: t, getState: o, onRestore: r } = e;
81
81
  if (!o().isOpen) return;
82
- const r = document.getElementById(t);
83
- if (r) {
84
- r.style.display = "flex", r.style.visibility = "visible", r.style.opacity = "1";
82
+ const n = document.getElementById(t);
83
+ if (n) {
84
+ n.style.display = "flex", n.style.visibility = "visible", n.style.opacity = "1";
85
85
  return;
86
86
  }
87
- n();
87
+ r();
88
88
  }
89
- }, w = {
89
+ }, y = {
90
90
  apiBase: "https://wx-auth.shenzjd.com",
91
91
  // 后端API地址(默认值)
92
92
  onVerified: null,
@@ -104,12 +104,12 @@ const i = {
104
104
  silent: !1
105
105
  // 默认不静默
106
106
  };
107
- let s = { ...w }, a = "", l = {
107
+ let s = { ...y }, u = "", c = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
110
  currentStep: "qr"
111
111
  };
112
- function p(e) {
112
+ function k(e) {
113
113
  try {
114
114
  if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
115
115
  return "";
@@ -119,9 +119,9 @@ function p(e) {
119
119
  return "";
120
120
  }
121
121
  }
122
- const c = {
122
+ const a = {
123
123
  getRootDomain() {
124
- return p(window.location.hostname);
124
+ return k(window.location.hostname);
125
125
  },
126
126
  // 获取Cookie
127
127
  getCookie(e) {
@@ -132,13 +132,13 @@ const c = {
132
132
  setCookie(e, t) {
133
133
  const o = /* @__PURE__ */ new Date();
134
134
  o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
135
- const n = this.getRootDomain(), r = n ? `;domain=${n}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
136
- document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${r}${f};SameSite=Strict`;
135
+ const r = this.getRootDomain(), n = r ? `;domain=${r}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
136
+ document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${n}${f};SameSite=Strict`;
137
137
  },
138
138
  // 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
139
139
  deleteCookie(e) {
140
- const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", r = window.location.protocol === "https:" ? ";Secure" : "";
141
- document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`;
140
+ const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", n = window.location.protocol === "https:" ? ";Secure" : "";
141
+ document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${n};SameSite=Strict`;
142
142
  },
143
143
  // ===== 签名 Token 双存储(Cookie 主 + localStorage 备份) =====
144
144
  // 目标:用户清除 Cookie 后,若服务端认证状态仍有效,可凭备份静默恢复。
@@ -176,6 +176,8 @@ const c = {
176
176
  }
177
177
  },
178
178
  // 发送请求
179
+ // 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
180
+ // 供调用方区分「明确未认证」与「瞬时失败」——后者不应触发重新验证(2026-08-29)
179
181
  async request(e, t = {}) {
180
182
  try {
181
183
  const o = await fetch(e, {
@@ -187,11 +189,14 @@ const c = {
187
189
  body: t.body ? JSON.stringify(t.body) : null,
188
190
  credentials: "include"
189
191
  });
190
- if (!o.ok)
191
- throw new Error(`HTTP ${o.status}`);
192
+ if (!o.ok) {
193
+ const r = new Error(`HTTP ${o.status}`);
194
+ throw r.status = o.status, r;
195
+ }
192
196
  return await o.json();
193
197
  } catch (o) {
194
- throw console.error("[WxAuth] Request error:", o), o;
198
+ const r = o;
199
+ throw r.status === void 0 && (r.isNetworkError = !0), console.error("[WxAuth] Request error:", o), r;
195
200
  }
196
201
  },
197
202
  // 生成6位验证码输入框HTML
@@ -201,7 +206,27 @@ const c = {
201
206
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
202
207
  return e += "</div>", e;
203
208
  }
204
- }, d = {
209
+ }, p = [1e3, 3e3];
210
+ function v(e) {
211
+ const t = e;
212
+ return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
213
+ }
214
+ function g(e) {
215
+ return new Promise((t) => setTimeout(t, e));
216
+ }
217
+ async function m(e) {
218
+ const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${s.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
219
+ for (let r = 0; ; r++)
220
+ try {
221
+ const n = await a.request(o);
222
+ return n.authenticated ? { kind: "ok", result: n } : n.error === "rate_limited" || n.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: n };
223
+ } catch (n) {
224
+ if (!v(n) || r >= p.length)
225
+ return { kind: "transient" };
226
+ await g(p[r]);
227
+ }
228
+ }
229
+ const d = {
205
230
  // 创建弹窗
206
231
  createModal() {
207
232
  const e = document.createElement("div");
@@ -227,7 +252,7 @@ const c = {
227
252
  <div>
228
253
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
229
254
  <div class="wx-auth-note">保持关注,即可一直自动登录</div>
230
- ${c.generateCodeInputs()}
255
+ ${a.generateCodeInputs()}
231
256
  </div>
232
257
 
233
258
  <!-- 消息提示 -->
@@ -246,18 +271,18 @@ const c = {
246
271
  setTimeout(() => {
247
272
  const e = document.querySelectorAll(".wx-auth-input");
248
273
  e.length && e.forEach((t, o) => {
249
- t.addEventListener("input", (n) => {
250
- const r = n.target.value.replace(/\D/g, "");
251
- n.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => m.verifyCode(), 300);
252
- }), t.addEventListener("keydown", (n) => {
253
- const r = n.target;
254
- n.key === "Backspace" && !r.value && o > 0 ? e[o - 1].focus() : n.key === "ArrowLeft" && o > 0 ? (n.preventDefault(), e[o - 1].focus()) : n.key === "ArrowRight" && o < 5 && (n.preventDefault(), e[o + 1].focus());
255
- }), t.addEventListener("paste", (n) => {
256
- n.preventDefault();
257
- const r = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
258
- r && (r.split("").forEach((u, f) => {
259
- e[f] && (e[f].value = u);
260
- }), r.length === 6 && setTimeout(() => m.verifyCode(), 300));
274
+ t.addEventListener("input", (r) => {
275
+ const n = r.target.value.replace(/\D/g, "");
276
+ r.target.value = n, n && o < 5 && e[o + 1].focus(), o === 5 && n && setTimeout(() => w.verifyCode(), 300);
277
+ }), t.addEventListener("keydown", (r) => {
278
+ const n = r.target;
279
+ r.key === "Backspace" && !n.value && o > 0 ? e[o - 1].focus() : r.key === "ArrowLeft" && o > 0 ? (r.preventDefault(), e[o - 1].focus()) : r.key === "ArrowRight" && o < 5 && (r.preventDefault(), e[o + 1].focus());
280
+ }), t.addEventListener("paste", (r) => {
281
+ r.preventDefault();
282
+ const n = r.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
283
+ n && (n.split("").forEach((l, f) => {
284
+ e[f] && (e[f].value = l);
285
+ }), n.length === 6 && setTimeout(() => w.verifyCode(), 300));
261
286
  });
262
287
  });
263
288
  }, 100);
@@ -265,19 +290,19 @@ const c = {
265
290
  // 显示弹窗
266
291
  show() {
267
292
  let e = document.getElementById("wx-auth-modal");
268
- e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.querySelectorAll(".wx-auth-input").forEach((r) => r.value = "");
293
+ 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((n) => n.value = "");
269
294
  const o = e.querySelector(".wx-auth-message");
270
295
  o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
271
- const n = e.querySelector(".wx-auth-btn-primary");
272
- n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), e.style.display = "flex", l.isOpen = !0, h.enable({
296
+ const r = e.querySelector(".wx-auth-btn-primary");
297
+ r && (r.disabled = !1, r.textContent = "登录", r.style.background = ""), e.style.display = "flex", c.isOpen = !0, h.enable({
273
298
  modalId: "wx-auth-modal",
274
- getState: () => l,
299
+ getState: () => c,
275
300
  onRestore: () => {
276
301
  this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
277
- const r = document.querySelector(".wx-auth-wechat-name");
278
- r && s.wechatName && (r.textContent = `"${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
279
- const u = document.querySelector(".wx-auth-input");
280
- u && u.focus();
302
+ const n = document.querySelector(".wx-auth-wechat-name");
303
+ n && s.wechatName && (n.textContent = `"${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
304
+ const l = document.querySelector(".wx-auth-input");
305
+ l && l.focus();
281
306
  }, 100);
282
307
  }
283
308
  });
@@ -285,7 +310,7 @@ const c = {
285
310
  // 隐藏弹窗
286
311
  hide() {
287
312
  const e = document.getElementById("wx-auth-modal");
288
- e && (e.style.display = "none", l.isOpen = !1, h.disable());
313
+ e && (e.style.display = "none", c.isOpen = !1, h.disable());
289
314
  },
290
315
  // 设置二维码
291
316
  setQrCode(e) {
@@ -310,10 +335,10 @@ const c = {
310
335
  const e = document.querySelectorAll(".wx-auth-input");
311
336
  e.forEach((t) => t.value = ""), e[0] && e[0].focus();
312
337
  }
313
- }, m = {
338
+ }, w = {
314
339
  // 初始化
315
340
  init(e = {}) {
316
- if (s = { ...w, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
341
+ if (s = { ...y, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
317
342
  console.error("[WxAuth] apiBase is required");
318
343
  return;
319
344
  }
@@ -321,10 +346,10 @@ const c = {
321
346
  const t = document.referrer;
322
347
  if (t)
323
348
  try {
324
- a = new URL(t).hostname;
349
+ u = new URL(t).hostname;
325
350
  } catch {
326
351
  }
327
- !a && window.location.hostname && (a = window.location.hostname), a || (a = "default"), console.log("[WxAuth] 自动获取 siteId:", a);
352
+ !u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
328
353
  }
329
354
  console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
330
355
  },
@@ -338,38 +363,28 @@ const c = {
338
363
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
339
364
  */
340
365
  async silentCheck() {
341
- const e = c.getToken();
366
+ const e = a.getToken();
342
367
  if (!e) return !1;
343
- const t = a ? `&siteId=${encodeURIComponent(a)}` : "", o = `token=${encodeURIComponent(e)}`;
344
- try {
345
- const n = await c.request(
346
- `${s.apiBase}/api/auth/check?${o}${t}`
347
- );
348
- return n.authenticated ? (n.token && c.setToken(n.token), this.onVerified(n.user), !0) : !1;
349
- } catch (n) {
350
- return console.error("[WxAuth] silentCheck 请求失败:", n), !1;
351
- }
368
+ const t = await m(e);
369
+ return t.kind === "ok" ? (t.result.token && a.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
352
370
  },
353
371
  // 自动检测凭证并验证(内部使用)
354
372
  async autoCheck() {
355
- const e = c.getToken();
373
+ const e = a.getToken();
356
374
  if (!e)
357
375
  return this.showAuthModal(), !1;
358
- const t = a ? `&siteId=${encodeURIComponent(a)}` : "", o = `token=${encodeURIComponent(e)}`;
359
- try {
360
- const n = await c.request(
361
- `${s.apiBase}/api/auth/check?${o}${t}`
362
- );
363
- return n.authenticated ? (console.log("[WxAuth] 自动认证成功(凭证)"), n.token && c.setToken(n.token), this.onVerified(n.user), !0) : (this.showAuthModal(), !1);
364
- } catch (n) {
365
- return console.error("[WxAuth] 自动验证失败:", n), this.showAuthModal(), !1;
366
- }
376
+ const t = await m(e);
377
+ return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && a.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
378
+ code: "server_error",
379
+ retryable: !0,
380
+ message: "登录服务暂时不可用,请稍后重试"
381
+ }), !1) : (this.showAuthModal(), !1);
367
382
  },
368
383
  // 显示认证弹窗(内部使用)
369
384
  async showAuthModal() {
370
385
  d.show();
371
386
  try {
372
- const t = a ? `?siteId=${encodeURIComponent(a)}` : "", o = await c.request(
387
+ const t = u ? `?siteId=${encodeURIComponent(u)}` : "", o = await a.request(
373
388
  `${s.apiBase}/api/sdk/config${t}`
374
389
  );
375
390
  o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
@@ -386,19 +401,20 @@ const c = {
386
401
  // 主入口:需要验证时调用
387
402
  // 凭证仅签名 Token(Cookie 优先 + localStorage 兜底),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
388
403
  async requireAuth() {
389
- const e = c.getToken();
390
- if (e)
391
- try {
392
- const t = a ? `&siteId=${encodeURIComponent(a)}` : "", o = `token=${encodeURIComponent(e)}`, n = await c.request(
393
- `${s.apiBase}/api/auth/check?${o}${t}`
394
- );
395
- if (n.authenticated)
396
- return console.log("[WxAuth] 已认证(凭证)"), n.token && c.setToken(n.token), this.onVerified(n.user), !0;
397
- } catch (t) {
398
- console.error("[WxAuth] 凭证检查失败:", t);
399
- }
404
+ const e = a.getToken();
405
+ if (e) {
406
+ const t = await m(e);
407
+ if (t.kind === "ok")
408
+ return console.log("[WxAuth] 已认证(凭证)"), t.result.token && a.setToken(t.result.token), this.onVerified(t.result.user), !0;
409
+ if (t.kind === "transient")
410
+ return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
411
+ code: "server_error",
412
+ retryable: !0,
413
+ message: "登录服务暂时不可用,请稍后重试"
414
+ }), !1;
415
+ }
400
416
  return await this.showAuthModal(), new Promise((t) => {
401
- l.resolveAuth = t;
417
+ c.resolveAuth = t;
402
418
  });
403
419
  },
404
420
  // 验证验证码
@@ -413,21 +429,27 @@ const c = {
413
429
  );
414
430
  t && (t.disabled = !0, t.textContent = "登录中...");
415
431
  try {
416
- const o = a ? `&siteId=${encodeURIComponent(a)}` : "", n = await c.request(
432
+ const o = u ? `&siteId=${encodeURIComponent(u)}` : "", r = await a.request(
417
433
  `${s.apiBase}/api/auth/check?authToken=${e}${o}`
418
434
  );
419
- n.authenticated ? (n.token && c.setToken(n.token), t && (t.textContent = "✅ 已登录", t.style.background = "#07C160"), setTimeout(() => {
420
- this.onVerified(n.user), this.close(!0);
421
- }, 500)) : (d.showMessage("验证码错误或已过期", "error"), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
422
- } catch {
423
- d.showMessage("登录失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "登录");
435
+ r.authenticated ? (r.token && a.setToken(r.token), t && (t.textContent = "✅ 已登录", t.style.background = "#07C160"), setTimeout(() => {
436
+ this.onVerified(r.user), this.close(!0);
437
+ }, 500)) : (d.showMessage(
438
+ r.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
439
+ "error"
440
+ ), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
441
+ } catch (o) {
442
+ d.showMessage(
443
+ v(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
444
+ "error"
445
+ ), t && (t.disabled = !1, t.textContent = "登录");
424
446
  }
425
447
  },
426
448
  // 关闭弹窗
427
449
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
428
450
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
429
451
  close(e = !1) {
430
- d.hide(), l.resolveAuth && (l.resolveAuth(!1), l.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
452
+ d.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
431
453
  },
432
454
  // 清空本地认证凭证(双重删除:Cookie + localStorage)
433
455
  // 用于"退出登录 / 清空认证状态"按钮。
@@ -435,7 +457,7 @@ const c = {
435
457
  // SDK 会凭备份静默恢复(getToken 优先 Cookie、localStorage 兜底),
436
458
  // 造成"清不掉"的假象——所以必须走这里而非只删 Cookie。
437
459
  clearToken() {
438
- c.clearToken();
460
+ a.clearToken();
439
461
  },
440
462
  // 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
441
463
  // 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
@@ -443,8 +465,10 @@ const c = {
443
465
  // (根治「A 域退出、B 域还能用」的双写恢复问题)。
444
466
  // 幂等安全:网络失败 /* 后端不可达 */ 时静默降级为仅本地清理(clearToken),
445
467
  // 不阻塞退出流程;token 无效也会返回 success(本地照常清理)。
468
+ // 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
469
+ // 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
446
470
  async revoke() {
447
- const e = c.getToken();
471
+ const e = a.getToken();
448
472
  if (e)
449
473
  try {
450
474
  const t = s.apiBase && !/\/$/.test(s.apiBase) ? s.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
@@ -461,14 +485,14 @@ const c = {
461
485
  },
462
486
  // 验证成功回调
463
487
  onVerified(e) {
464
- console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), l.resolveAuth && (l.resolveAuth(!0), l.resolveAuth = null);
488
+ console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), c.resolveAuth && (c.resolveAuth(!0), c.resolveAuth = null);
465
489
  },
466
490
  // 错误回调
467
491
  onError(e) {
468
492
  console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
469
493
  }
470
494
  };
471
- typeof window < "u" && (window.WxAuth = Object.freeze(m));
495
+ typeof window < "u" && (window.WxAuth = Object.freeze(w));
472
496
  export {
473
- m as WxAuth
497
+ w as WxAuth
474
498
  };
@@ -1,6 +1,6 @@
1
1
  (function(f,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(f=typeof globalThis<"u"?globalThis:f||self,p(f.WxAuthSDK={}))})(this,(function(f){"use strict";var p=document.createElement("style");p.textContent=`.wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:30px;padding:0;opacity:.85;flex-shrink:0}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:4px;font-weight:500}.wx-auth-note{font-size:12px;color:#888;margin-bottom:14px;line-height:1.4;white-space:nowrap}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}.wx-auth-note{color:#aaa}.wx-auth-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-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(p);const a={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(a.isProtected||typeof window>"u")return;a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!0,a.restorePending=!1,a.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const i of n.removedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;const l=i;if(l.id===e.modalId||l.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.safeRestore(e);return}}}),a.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!a.isProtected)return;const{getState:o}=e;if(!o().isOpen){a.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||h.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?h.isHidden(n):null}),h.safeRestore(e)),a.isProtected&&(a.rafId=requestAnimationFrame(t))};a.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!1,a.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!a.restorePending){a.restorePending=!0;try{h.restoreFn(e)}finally{requestAnimationFrame(()=>{a.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(i){i.style.display="flex",i.style.visibility="visible",i.style.opacity="1";return}n()}},m={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let r={...m},s="",u={isOpen:!1,resolveAuth:null,currentStep:"qr"};function g(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const c={getRootDomain(){return g(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+365*24*60*60*1e3);const n=this.getRootDomain(),i=n?`;domain=${n}`:"",w=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${i}${w};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",i=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${i};SameSite=Strict`},get storageKey(){return"wxauth-token"},getToken(){const e=this.getCookie("wxauth-token");if(e)return e;try{return window.localStorage.getItem(this.storageKey)}catch{return null}},setToken(e){this.setCookie("wxauth-token",e);try{window.localStorage.setItem(this.storageKey,e)}catch{}},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem(this.storageKey)}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},d={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=r.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
3
- <div class="wx-auth-overlay" ${r.required?'onclick="event.preventDefault()"':""}></div>
2
+ /*$vite$:1*/`,document.head.appendChild(p);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(i.isProtected||typeof window>"u")return;i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!0,i.restorePending=!1,i.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const l=r;if(l.id===e.modalId||l.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.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||h.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?h.isHidden(n):null}),h.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{h.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()}},g={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...g},u="",c={isOpen:!1,resolveAuth:null,currentStep:"qr"};function k(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const s={getRootDomain(){return k(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+365*24*60*60*1e3);const n=this.getRootDomain(),r=n?`;domain=${n}`:"",x=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${r}${x};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`},get storageKey(){return"wxauth-token"},getToken(){const e=this.getCookie("wxauth-token");if(e)return e;try{return window.localStorage.getItem(this.storageKey)}catch{return null}},setToken(e){this.setCookie("wxauth-token",e);try{window.localStorage.setItem(this.storageKey,e)}catch{}},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem(this.storageKey)}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok){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}},y=[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 v(e){return new Promise(t=>setTimeout(t,e))}async function m(e){const t=u?`&siteId=${encodeURIComponent(u)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await s.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>=y.length)return{kind:"transient"};await v(y[n])}}const d={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>';return e.innerHTML=`
3
+ <div class="wx-auth-overlay" ${a.required?'onclick="event.preventDefault()"':""}></div>
4
4
  <div class="wx-auth-content">
5
5
  <div class="wx-auth-header">
6
6
  <div class="wx-auth-title">微信登录</div>
@@ -19,7 +19,7 @@
19
19
  <div>
20
20
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
21
21
  <div class="wx-auth-note">保持关注,即可一直自动登录</div>
22
- ${c.generateCodeInputs()}
22
+ ${s.generateCodeInputs()}
23
23
  </div>
24
24
 
25
25
  <!-- 消息提示 -->
@@ -31,4 +31,4 @@
31
31
  </div>
32
32
  </div>
33
33
  </div>
34
- `,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const i=n.target.value.replace(/\D/g,"");n.target.value=i,i&&o<5&&e[o+1].focus(),o===5&&i&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const i=n.target;n.key==="Backspace"&&!i.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const i=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);i&&(i.split("").forEach((l,w)=>{e[w]&&(e[w].value=l)}),i.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(i=>i.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),e.style.display="flex",u.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),r.qrcodeUrl&&this.setQrCode(r.qrcodeUrl);const i=document.querySelector(".wx-auth-wechat-name");i&&r.wechatName&&(i.textContent=`"${r.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const l=document.querySelector(".wx-auth-input");l&&l.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",u.isOpen=!1,h.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},x={init(e={}){if(r={...m,...e},!r.apiBase&&typeof window<"u"&&(r.apiBase=window.location.origin),!r.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{s=new URL(t).hostname}catch{}!s&&window.location.hostname&&(s=window.location.hostname),s||(s="default"),console.log("[WxAuth] 自动获取 siteId:",s)}console.log("[WxAuth] SDK initialized",r),typeof window<"u"&&(r.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=s?`&siteId=${encodeURIComponent(s)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await c.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(n.token&&c.setToken(n.token),this.onVerified(n.user),!0):!1}catch(n){return console.error("[WxAuth] silentCheck 请求失败:",n),!1}},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=s?`&siteId=${encodeURIComponent(s)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await c.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(console.log("[WxAuth] 自动认证成功(凭证)"),n.token&&c.setToken(n.token),this.onVerified(n.user),!0):(this.showAuthModal(),!1)}catch(n){return console.error("[WxAuth] 自动验证失败:",n),this.showAuthModal(),!1}},async showAuthModal(){d.show();try{const t=s?`?siteId=${encodeURIComponent(s)}`:"",o=await c.request(`${r.apiBase}/api/sdk/config${t}`);o.wechatName&&!r.wechatName&&(r.wechatName=o.wechatName),o.qrcodeUrl&&!r.qrcodeUrl&&(r.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}r.qrcodeUrl&&d.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&r.wechatName&&(e.textContent=`"${r.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=c.getToken();if(e)try{const t=s?`&siteId=${encodeURIComponent(s)}`:"",o=`token=${encodeURIComponent(e)}`,n=await c.request(`${r.apiBase}/api/auth/check?${o}${t}`);if(n.authenticated)return console.log("[WxAuth] 已认证(凭证)"),n.token&&c.setToken(n.token),this.onVerified(n.user),!0}catch(t){console.error("[WxAuth] 凭证检查失败:",t)}return await this.showAuthModal(),new Promise(t=>{u.resolveAuth=t})},async verifyCode(){const e=d.getVerifyCode();if(!e||e.length!==6){d.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=s?`&siteId=${encodeURIComponent(s)}`:"",n=await c.request(`${r.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token&&c.setToken(n.token),t&&(t.textContent="✅ 已登录",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(d.showMessage("验证码错误或已过期","error"),d.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch{d.showMessage("登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){d.hide(),u.resolveAuth&&(u.resolveAuth(!1),u.resolveAuth=null),!e&&typeof r.onClose=="function"&&r.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=r.apiBase&&!/\/$/.test(r.apiBase)?r.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof r.onVerified=="function"&&r.onVerified(e),u.resolveAuth&&(u.resolveAuth(!0),u.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof r.onError=="function"&&r.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),f.WxAuth=x,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
34
+ `,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>w.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;n.key==="Backspace"&&!r.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((l,x)=>{e[x]&&(e[x].value=l)}),r.length===6&&setTimeout(()=>w.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=""),e.style.display="flex",c.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>c,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(),setTimeout(()=>{const l=document.querySelector(".wx-auth-input");l&&l.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",c.isOpen=!1,h.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},w={init(e={}){if(a={...g,...e},!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{u=new URL(t).hostname}catch{}!u&&window.location.hostname&&(u=window.location.hostname),u||(u="default"),console.log("[WxAuth] 自动获取 siteId:",u)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=s.getToken();if(!e)return!1;const t=await m(e);return t.kind==="ok"?(t.result.token&&s.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=s.getToken();if(!e)return this.showAuthModal(),!1;const t=await m(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&s.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(){d.show();try{const t=u?`?siteId=${encodeURIComponent(u)}`:"",o=await s.request(`${a.apiBase}/api/sdk/config${t}`);o.wechatName&&!a.wechatName&&(a.wechatName=o.wechatName),o.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}a.qrcodeUrl&&d.setQrCode(a.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&a.wechatName&&(e.textContent=`"${a.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=s.getToken();if(e){const t=await m(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&s.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=>{c.resolveAuth=t})},async verifyCode(){const e=d.getVerifyCode();if(!e||e.length!==6){d.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=u?`&siteId=${encodeURIComponent(u)}`:"",n=await s.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token&&s.setToken(n.token),t&&(t.textContent="✅ 已登录",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(d.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),d.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){d.showMessage(b(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){d.hide(),c.resolveAuth&&(c.resolveAuth(!1),c.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){s.clearToken()},async revoke(){const e=s.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),c.resolveAuth&&(c.resolveAuth(!0),c.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(w)),f.WxAuth=w,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.23",
3
+ "version": "1.2.24",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",