wx-auth-sdk 1.2.23 → 1.2.25

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/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ declare type LoginMode = "mp" | "code";
2
+
1
3
  export declare const WxAuth: {
2
4
  init(options?: Partial<WxAuthConfig>): void;
3
5
  /**
@@ -12,7 +14,14 @@ export declare const WxAuth: {
12
14
  silentCheck(): Promise<boolean>;
13
15
  autoCheck(): Promise<boolean>;
14
16
  showAuthModal(): Promise<void>;
17
+ syncMpTabs(): void;
18
+ switchMode(mode: LoginMode): void;
19
+ startMpLogin(): Promise<void>;
15
20
  requireAuth(): Promise<boolean>;
21
+ completeLogin(result: {
22
+ token?: string;
23
+ user?: any;
24
+ }): void;
16
25
  verifyCode(): Promise<void>;
17
26
  close(skipOnClose?: boolean): void;
18
27
  clearToken(): void;
package/dist/wx-auth.css CHANGED
@@ -1 +1 @@
1
- .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}
1
+ .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}
package/dist/wx-auth.js CHANGED
@@ -3,20 +3,20 @@ const i = {
3
3
  rafId: null,
4
4
  isProtected: !1,
5
5
  restorePending: !1
6
- }, h = {
6
+ }, m = {
7
7
  /**
8
8
  * 启用弹窗保护
9
9
  */
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}`)) {
19
- console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
13
+ for (const s of o)
14
+ if (s.type === "childList")
15
+ for (const n of s.removedNodes) {
16
+ if (n.nodeType !== Node.ELEMENT_NODE) continue;
17
+ const d = n;
18
+ if (d.id === e.modalId || d.querySelector?.(`#${e.modalId}`)) {
19
+ console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), m.safeRestore(e);
20
20
  return;
21
21
  }
22
22
  }
@@ -31,11 +31,11 @@ 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 s = document.getElementById(e.modalId);
35
+ (!s || !s.isConnected || m.isHidden(s)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
- { has: !!n, connected: n?.isConnected, hidden: n ? h.isHidden(n) : null }
38
- ), h.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
37
+ { has: !!s, connected: s?.isConnected, hidden: s ? m.isHidden(s) : null }
38
+ ), m.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
39
39
  };
40
40
  i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
41
41
  },
@@ -52,7 +52,7 @@ const i = {
52
52
  if (!i.restorePending) {
53
53
  i.restorePending = !0;
54
54
  try {
55
- h.restoreFn(e);
55
+ m.restoreFn(e);
56
56
  } finally {
57
57
  requestAnimationFrame(() => {
58
58
  i.restorePending = !1;
@@ -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: s } = 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
+ s();
88
88
  }
89
- }, w = {
89
+ }, q = {
90
90
  apiBase: "https://wx-auth.shenzjd.com",
91
91
  // 后端API地址(默认值)
92
92
  onVerified: null,
@@ -104,12 +104,13 @@ const i = {
104
104
  silent: !1
105
105
  // 默认不静默
106
106
  };
107
- let s = { ...w }, a = "", l = {
107
+ let r = { ...q }, u = "", a = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
- currentStep: "qr"
111
- };
112
- function p(e) {
110
+ currentStep: "qr",
111
+ mpSession: null
112
+ }, h = !1, f = "code", p = 0;
113
+ function A(e) {
113
114
  try {
114
115
  if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
115
116
  return "";
@@ -121,7 +122,7 @@ function p(e) {
121
122
  }
122
123
  const c = {
123
124
  getRootDomain() {
124
- return p(window.location.hostname);
125
+ return A(window.location.hostname);
125
126
  },
126
127
  // 获取Cookie
127
128
  getCookie(e) {
@@ -132,13 +133,13 @@ const c = {
132
133
  setCookie(e, t) {
133
134
  const o = /* @__PURE__ */ new Date();
134
135
  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`;
136
+ const s = this.getRootDomain(), n = s ? `;domain=${s}` : "", y = window.location.protocol === "https:" ? ";Secure" : "";
137
+ document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${n}${y};SameSite=Strict`;
137
138
  },
138
139
  // 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
139
140
  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`;
141
+ const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", n = window.location.protocol === "https:" ? ";Secure" : "";
142
+ document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${n};SameSite=Strict`;
142
143
  },
143
144
  // ===== 签名 Token 双存储(Cookie 主 + localStorage 备份) =====
144
145
  // 目标:用户清除 Cookie 后,若服务端认证状态仍有效,可凭备份静默恢复。
@@ -176,6 +177,9 @@ const c = {
176
177
  }
177
178
  },
178
179
  // 发送请求
180
+ // 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
181
+ // 供调用方区分「明确未认证」与「瞬时失败」——后者不应触发重新验证(2026-08-29)
182
+ // body 接受任意可 JSON 序列化对象(实现统一 JSON.stringify,非 BodyInit)
179
183
  async request(e, t = {}) {
180
184
  try {
181
185
  const o = await fetch(e, {
@@ -187,11 +191,14 @@ const c = {
187
191
  body: t.body ? JSON.stringify(t.body) : null,
188
192
  credentials: "include"
189
193
  });
190
- if (!o.ok)
191
- throw new Error(`HTTP ${o.status}`);
194
+ if (!o.ok) {
195
+ const s = new Error(`HTTP ${o.status}`);
196
+ throw s.status = o.status, s;
197
+ }
192
198
  return await o.json();
193
199
  } catch (o) {
194
- throw console.error("[WxAuth] Request error:", o), o;
200
+ const s = o;
201
+ throw s.status === void 0 && (s.isNetworkError = !0), console.error("[WxAuth] Request error:", o), s;
195
202
  }
196
203
  },
197
204
  // 生成6位验证码输入框HTML
@@ -201,42 +208,115 @@ const c = {
201
208
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
202
209
  return e += "</div>", e;
203
210
  }
204
- }, d = {
211
+ }, b = [1e3, 3e3];
212
+ function k(e) {
213
+ const t = e;
214
+ return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
215
+ }
216
+ function v(e) {
217
+ return new Promise((t) => setTimeout(t, e));
218
+ }
219
+ const C = 2e3, T = 3e3;
220
+ function g() {
221
+ p++;
222
+ }
223
+ async function S(e) {
224
+ for (; e === p && a.isOpen; ) {
225
+ const t = a.mpSession;
226
+ if (!t || Date.now() >= t.expiresAt) break;
227
+ try {
228
+ const o = await c.request(
229
+ `${r.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
230
+ );
231
+ if (e !== p) return;
232
+ if (o.status === "confirmed" && o.token) {
233
+ w.completeLogin(o);
234
+ return;
235
+ }
236
+ if (o.status === "expired") {
237
+ a.mpSession = null;
238
+ break;
239
+ }
240
+ } catch (o) {
241
+ if (e !== p) return;
242
+ if (!k(o)) break;
243
+ await v(T);
244
+ continue;
245
+ }
246
+ await v(C);
247
+ }
248
+ e === p && a.isOpen && f === "mp" && l.showMpExpired();
249
+ }
250
+ async function x(e) {
251
+ const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${r.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
252
+ for (let s = 0; ; s++)
253
+ try {
254
+ const n = await c.request(o);
255
+ return n.authenticated ? { kind: "ok", result: n } : n.error === "rate_limited" || n.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: n };
256
+ } catch (n) {
257
+ if (!k(n) || s >= b.length)
258
+ return { kind: "transient" };
259
+ await v(b[s]);
260
+ }
261
+ }
262
+ const l = {
205
263
  // 创建弹窗
206
264
  createModal() {
207
265
  const e = document.createElement("div");
208
- e.id = "wx-auth-modal", e.className = "wx-auth-modal", s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
209
- const t = s.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
266
+ e.id = "wx-auth-modal", e.className = "wx-auth-modal", r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
267
+ const t = r.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>', o = h ? `<div class="wx-auth-tabs">
268
+ <button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
269
+ <button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
270
+ </div>` : "", s = h ? `<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
271
+ <div class="wx-auth-qrcode-container wx-auth-mp-container">
272
+ <div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
273
+ <img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
274
+ <div class="wx-auth-mp-expired" style="display:none">
275
+ <div class="wx-auth-mp-expired-text">二维码已过期</div>
276
+ <button type="button" class="wx-auth-btn wx-auth-btn-primary wx-auth-mp-refresh" onclick="WxAuth.startMpLogin()">刷新二维码</button>
277
+ </div>
278
+ </div>
279
+ <div class="wx-auth-desc wx-auth-mp-hint">微信扫描二维码,打开小程序确认登录</div>
280
+ <div class="wx-auth-mp-status"></div>
281
+ </div>` : "";
210
282
  return e.innerHTML = `
211
- <div class="wx-auth-overlay" ${s.required ? 'onclick="event.preventDefault()"' : ""}></div>
283
+ <div class="wx-auth-overlay" ${r.required ? 'onclick="event.preventDefault()"' : ""}></div>
212
284
  <div class="wx-auth-content">
213
285
  <div class="wx-auth-header">
214
286
  <div class="wx-auth-title">微信登录</div>
215
287
  ${t}
216
288
  </div>
217
289
  <div class="wx-auth-body">
218
- <!-- 二维码区域 -->
219
- <div>
220
- <div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
221
- <div class="wx-auth-qrcode-container">
222
- <img class="wx-auth-qrcode" src="" alt="扫码关注" />
290
+ ${o}
291
+
292
+ <!-- 面板一:公众号验证码 -->
293
+ <div class="wx-auth-panel wx-auth-panel-code">
294
+ <!-- 二维码区域 -->
295
+ <div>
296
+ <div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
297
+ <div class="wx-auth-qrcode-container">
298
+ <img class="wx-auth-qrcode" src="" alt="扫码关注" />
299
+ </div>
300
+ </div>
301
+
302
+ <!-- 验证码输入区域 -->
303
+ <div>
304
+ <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
305
+ <div class="wx-auth-note">保持关注,即可一直自动登录</div>
306
+ ${c.generateCodeInputs()}
223
307
  </div>
224
- </div>
225
308
 
226
- <!-- 验证码输入区域 -->
227
- <div>
228
- <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
229
- <div class="wx-auth-note">保持关注,即可一直自动登录</div>
230
- ${c.generateCodeInputs()}
309
+ <!-- 按钮 -->
310
+ <div class="wx-auth-actions">
311
+ <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
312
+ </div>
231
313
  </div>
232
314
 
315
+ <!-- 面板二:小程序扫码 -->
316
+ ${s}
317
+
233
318
  <!-- 消息提示 -->
234
319
  <div class="wx-auth-message" style="display:none"></div>
235
-
236
- <!-- 按钮 -->
237
- <div class="wx-auth-actions">
238
- <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
239
- </div>
240
320
  </div>
241
321
  </div>
242
322
  `, document.body.appendChild(e), this.bindInputEvents(), e;
@@ -246,18 +326,18 @@ const c = {
246
326
  setTimeout(() => {
247
327
  const e = document.querySelectorAll(".wx-auth-input");
248
328
  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));
329
+ t.addEventListener("input", (s) => {
330
+ const n = s.target.value.replace(/\D/g, "");
331
+ s.target.value = n, n && o < 5 && e[o + 1].focus(), o === 5 && n && setTimeout(() => w.verifyCode(), 300);
332
+ }), t.addEventListener("keydown", (s) => {
333
+ const n = s.target;
334
+ s.key === "Backspace" && !n.value && o > 0 ? e[o - 1].focus() : s.key === "ArrowLeft" && o > 0 ? (s.preventDefault(), e[o - 1].focus()) : s.key === "ArrowRight" && o < 5 && (s.preventDefault(), e[o + 1].focus());
335
+ }), t.addEventListener("paste", (s) => {
336
+ s.preventDefault();
337
+ const n = s.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
338
+ n && (n.split("").forEach((d, y) => {
339
+ e[y] && (e[y].value = d);
340
+ }), n.length === 6 && setTimeout(() => w.verifyCode(), 300));
261
341
  });
262
342
  });
263
343
  }, 100);
@@ -265,19 +345,19 @@ const c = {
265
345
  // 显示弹窗
266
346
  show() {
267
347
  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 = "");
348
+ 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((n) => n.value = "");
269
349
  const o = e.querySelector(".wx-auth-message");
270
350
  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({
351
+ const s = e.querySelector(".wx-auth-btn-primary");
352
+ s && (s.disabled = !1, s.textContent = "登录", s.style.background = ""), g(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, m.enable({
273
353
  modalId: "wx-auth-modal",
274
- getState: () => l,
354
+ getState: () => a,
275
355
  onRestore: () => {
276
- this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
277
- const r = document.querySelector(".wx-auth-wechat-name");
278
- r && s.wechatName && (r.textContent = `"${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
279
- const u = document.querySelector(".wx-auth-input");
280
- u && u.focus();
356
+ this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
357
+ const n = document.querySelector(".wx-auth-wechat-name");
358
+ n && r.wechatName && (n.textContent = `"${r.wechatName}"`), this.bindInputEvents(), h && f === "mp" && w.switchMode("mp"), setTimeout(() => {
359
+ const d = document.querySelector(".wx-auth-input");
360
+ d && d.focus();
281
361
  }, 100);
282
362
  }
283
363
  });
@@ -285,7 +365,7 @@ const c = {
285
365
  // 隐藏弹窗
286
366
  hide() {
287
367
  const e = document.getElementById("wx-auth-modal");
288
- e && (e.style.display = "none", l.isOpen = !1, h.disable());
368
+ e && (e.style.display = "none", a.isOpen = !1, g(), a.mpSession = null, m.disable());
289
369
  },
290
370
  // 设置二维码
291
371
  setQrCode(e) {
@@ -293,6 +373,31 @@ const c = {
293
373
  const t = document.querySelector(".wx-auth-qrcode");
294
374
  t && (t.src = e, t.style.display = "block");
295
375
  },
376
+ // ===== 小程序扫码面板(2026-08-29)=====
377
+ // 展示小程序码(隐藏 loading 与过期遮罩,保持画面干净)
378
+ setMpQr(e) {
379
+ const t = document.getElementById("wx-auth-modal"), o = t?.querySelector(".wx-auth-mp-qrcode"), s = t?.querySelector(".wx-auth-mp-loading");
380
+ o && (o.src = e, o.style.display = "block", s && (s.style.display = "none"), this.setMpExpiredVisible(!1), this.setMpStatus("", !1));
381
+ },
382
+ // 过期遮罩显示/隐藏:盖在二维码上(「二维码已过期」+ 绿色刷新按钮)
383
+ setMpExpiredVisible(e) {
384
+ const o = document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");
385
+ o && (o.style.display = e ? "flex" : "none");
386
+ },
387
+ // 更新扫码面板状态文案;text 为空 = 隐藏状态行;spinner=true 时回列出码 loading
388
+ setMpStatus(e, t) {
389
+ const o = document.getElementById("wx-auth-modal"), s = o?.querySelector(".wx-auth-mp-status");
390
+ s && (s.textContent = e, s.style.display = e ? "block" : "none");
391
+ const n = o?.querySelector(".wx-auth-mp-loading");
392
+ if (n && (n.style.display = t ? "flex" : "none"), t) {
393
+ const d = o?.querySelector(".wx-auth-mp-qrcode");
394
+ d && (d.style.display = "none");
395
+ }
396
+ },
397
+ // 二维码过期/失效:遮罩盖住旧码,用户点「刷新二维码」重新出码
398
+ showMpExpired() {
399
+ this.setMpExpiredVisible(!0);
400
+ },
296
401
  // 显示消息
297
402
  showMessage(e, t = "info") {
298
403
  const o = document.querySelector(".wx-auth-message");
@@ -310,10 +415,10 @@ const c = {
310
415
  const e = document.querySelectorAll(".wx-auth-input");
311
416
  e.forEach((t) => t.value = ""), e[0] && e[0].focus();
312
417
  }
313
- }, m = {
418
+ }, w = {
314
419
  // 初始化
315
420
  init(e = {}) {
316
- if (s = { ...w, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
421
+ if (r = { ...q, ...e }, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
317
422
  console.error("[WxAuth] apiBase is required");
318
423
  return;
319
424
  }
@@ -321,12 +426,12 @@ const c = {
321
426
  const t = document.referrer;
322
427
  if (t)
323
428
  try {
324
- a = new URL(t).hostname;
429
+ u = new URL(t).hostname;
325
430
  } catch {
326
431
  }
327
- !a && window.location.hostname && (a = window.location.hostname), a || (a = "default"), console.log("[WxAuth] 自动获取 siteId:", a);
432
+ !u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
328
433
  }
329
- console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
434
+ console.log("[WxAuth] SDK initialized", r), typeof window < "u" && (r.silent ? this.silentCheck() : this.autoCheck());
330
435
  },
331
436
  /**
332
437
  * 静默验证(silent 模式专用)
@@ -340,72 +445,122 @@ const c = {
340
445
  async silentCheck() {
341
446
  const e = c.getToken();
342
447
  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
- }
448
+ const t = await x(e);
449
+ 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);
352
450
  },
353
451
  // 自动检测凭证并验证(内部使用)
354
452
  async autoCheck() {
355
453
  const e = c.getToken();
356
454
  if (!e)
357
455
  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
- }
456
+ const t = await x(e);
457
+ 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({
458
+ code: "server_error",
459
+ retryable: !0,
460
+ message: "登录服务暂时不可用,请稍后重试"
461
+ }), !1) : (this.showAuthModal(), !1);
367
462
  },
368
463
  // 显示认证弹窗(内部使用)
369
464
  async showAuthModal() {
370
- d.show();
465
+ l.show();
371
466
  try {
372
- const t = a ? `?siteId=${encodeURIComponent(a)}` : "", o = await c.request(
373
- `${s.apiBase}/api/sdk/config${t}`
467
+ const t = u ? `?siteId=${encodeURIComponent(u)}` : "", o = await c.request(
468
+ `${r.apiBase}/api/sdk/config${t}`
374
469
  );
375
- o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
470
+ o.wechatName && !r.wechatName && (r.wechatName = o.wechatName), o.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = o.qrcodeUrl), h = !!o.mpScanEnabled;
376
471
  } catch (t) {
377
472
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
378
473
  }
379
- s.qrcodeUrl && d.setQrCode(s.qrcodeUrl);
474
+ this.syncMpTabs(), this.switchMode(h ? "mp" : "code"), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
380
475
  const e = document.querySelector(".wx-auth-wechat-name");
381
- e && s.wechatName && (e.textContent = `"${s.wechatName}"`), setTimeout(() => {
476
+ e && r.wechatName && (e.textContent = `"${r.wechatName}"`), setTimeout(() => {
382
477
  const t = document.querySelector(".wx-auth-input");
383
478
  t && t.focus();
384
479
  }, 100);
385
480
  },
481
+ // 按 mpScanAvailable 校正弹窗 DOM:缺 tab(首次打开时后端才返回开关)或多余
482
+ // tab(开关翻转)时重建弹窗。其余情况不动(避免清空用户输入)
483
+ syncMpTabs() {
484
+ const e = document.getElementById("wx-auth-modal");
485
+ if (!e) return;
486
+ const t = !!e.querySelector(".wx-auth-tabs");
487
+ h !== t && (e.remove(), l.createModal());
488
+ },
489
+ // 切换登录方式(tab 点击 / 默认模式设定)
490
+ switchMode(e) {
491
+ f = h ? e : "code";
492
+ const t = document.getElementById("wx-auth-modal");
493
+ if (!t) return;
494
+ t.querySelectorAll(".wx-auth-tab").forEach((n) => {
495
+ n.classList.toggle("wx-auth-tab-active", n.dataset.mode === f);
496
+ });
497
+ const o = t.querySelector(".wx-auth-panel-code"), s = t.querySelector(".wx-auth-panel-mp");
498
+ o && (o.style.display = f === "code" ? "" : "none"), s && (s.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : g();
499
+ },
500
+ // 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
501
+ async startMpLogin() {
502
+ if (!h || !a.isOpen) return;
503
+ const e = ++p;
504
+ if (l.setMpExpiredVisible(!1), l.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
505
+ l.setMpQr(a.mpSession.qrDataUrl), S(e);
506
+ return;
507
+ }
508
+ try {
509
+ const t = await c.request(`${r.apiBase}/api/auth/mp-scan/create`, {
510
+ method: "POST",
511
+ body: { siteId: u }
512
+ });
513
+ if (e !== p || !a.isOpen) return;
514
+ if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
515
+ a.mpSession = {
516
+ ticket: String(t.ticket),
517
+ qrDataUrl: String(t.qrDataUrl),
518
+ expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
519
+ }, l.setMpQr(a.mpSession.qrDataUrl), S(e);
520
+ } catch (t) {
521
+ if (e !== p || !a.isOpen) return;
522
+ console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"), l.showMessage("小程序扫码暂不可用,请使用公众号验证码登录", "error");
523
+ }
524
+ },
386
525
  // 主入口:需要验证时调用
387
526
  // 凭证仅签名 Token(Cookie 优先 + localStorage 兜底),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
388
527
  async requireAuth() {
389
528
  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
- }
529
+ if (e) {
530
+ const t = await x(e);
531
+ if (t.kind === "ok")
532
+ return console.log("[WxAuth] 已认证(凭证)"), t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0;
533
+ if (t.kind === "transient")
534
+ return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
535
+ code: "server_error",
536
+ retryable: !0,
537
+ message: "登录服务暂时不可用,请稍后重试"
538
+ }), !1;
539
+ }
400
540
  return await this.showAuthModal(), new Promise((t) => {
401
- l.resolveAuth = t;
541
+ a.resolveAuth = t;
402
542
  });
403
543
  },
544
+ // 共享登录成功路径(验证码校验成功 / 小程序扫码确认成功均走这里)
545
+ // 顺序很重要:必须先 onVerified() 触发 resolveAuth(true),
546
+ // 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
547
+ // close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
548
+ completeLogin(e) {
549
+ if (e?.token && c.setToken(e.token), h && f === "mp")
550
+ l.setMpStatus("✅ 登录成功", !1);
551
+ else {
552
+ const t = document.querySelector(".wx-auth-btn-primary");
553
+ t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
554
+ }
555
+ setTimeout(() => {
556
+ this.onVerified(e?.user), this.close(!0);
557
+ }, 500);
558
+ },
404
559
  // 验证验证码
405
560
  async verifyCode() {
406
- const e = d.getVerifyCode();
561
+ const e = l.getVerifyCode();
407
562
  if (!e || e.length !== 6) {
408
- d.showMessage("请输入6位验证码", "error");
563
+ l.showMessage("请输入6位验证码", "error");
409
564
  return;
410
565
  }
411
566
  const t = document.querySelector(
@@ -413,21 +568,25 @@ const c = {
413
568
  );
414
569
  t && (t.disabled = !0, t.textContent = "登录中...");
415
570
  try {
416
- const o = a ? `&siteId=${encodeURIComponent(a)}` : "", n = await c.request(
417
- `${s.apiBase}/api/auth/check?authToken=${e}${o}`
571
+ const o = u ? `&siteId=${encodeURIComponent(u)}` : "", s = await c.request(
572
+ `${r.apiBase}/api/auth/check?authToken=${e}${o}`
418
573
  );
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 = "登录");
574
+ s.authenticated ? this.completeLogin(s) : (l.showMessage(
575
+ s.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
576
+ "error"
577
+ ), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
578
+ } catch (o) {
579
+ l.showMessage(
580
+ k(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
581
+ "error"
582
+ ), t && (t.disabled = !1, t.textContent = "登录");
424
583
  }
425
584
  },
426
585
  // 关闭弹窗
427
586
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
428
587
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
429
588
  close(e = !1) {
430
- d.hide(), l.resolveAuth && (l.resolveAuth(!1), l.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
589
+ l.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
431
590
  },
432
591
  // 清空本地认证凭证(双重删除:Cookie + localStorage)
433
592
  // 用于"退出登录 / 清空认证状态"按钮。
@@ -443,11 +602,13 @@ const c = {
443
602
  // (根治「A 域退出、B 域还能用」的双写恢复问题)。
444
603
  // 幂等安全:网络失败 /* 后端不可达 */ 时静默降级为仅本地清理(clearToken),
445
604
  // 不阻塞退出流程;token 无效也会返回 success(本地照常清理)。
605
+ // 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
606
+ // 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
446
607
  async revoke() {
447
608
  const e = c.getToken();
448
609
  if (e)
449
610
  try {
450
- const t = s.apiBase && !/\/$/.test(s.apiBase) ? s.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
611
+ const t = r.apiBase && !/\/$/.test(r.apiBase) ? r.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
451
612
  method: "POST",
452
613
  headers: { "Content-Type": "application/json" },
453
614
  body: JSON.stringify({ token: e }),
@@ -461,14 +622,14 @@ const c = {
461
622
  },
462
623
  // 验证成功回调
463
624
  onVerified(e) {
464
- console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), l.resolveAuth && (l.resolveAuth(!0), l.resolveAuth = null);
625
+ console.log("[WxAuth] 验证成功", e), typeof r.onVerified == "function" && r.onVerified(e), a.resolveAuth && (a.resolveAuth(!0), a.resolveAuth = null);
465
626
  },
466
627
  // 错误回调
467
628
  onError(e) {
468
- console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
629
+ console.error("[WxAuth] 错误", e), typeof r.onError == "function" && r.onError(e);
469
630
  }
470
631
  };
471
- typeof window < "u" && (window.WxAuth = Object.freeze(m));
632
+ typeof window < "u" && (window.WxAuth = Object.freeze(w));
472
633
  export {
473
- m as WxAuth
634
+ w as WxAuth
474
635
  };
@@ -1,34 +1,56 @@
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>
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},x={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] 检测到弹窗被删除,正在恢复..."),x.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||x.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?x.isHidden(n):null}),x.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{x.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="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},h=!1,p="code",f=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 u={getRootDomain(){return T(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}`:"",g=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${r}${g};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}},A=[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 k(e){return new Promise(t=>setTimeout(t,e))}const I=2e3,E=3e3;function v(){f++}async function C(e){for(;e===f&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await u.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==f)return;if(o.status==="confirmed"&&o.token){y.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==f)return;if(!b(o))break;await k(E);continue}await k(I)}e===f&&s.isOpen&&p==="mp"&&c.showMpExpired()}async function S(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await u.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>=A.length)return{kind:"transient"};await k(A[n])}}const c={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=h?`<div class="wx-auth-tabs">
3
+ <button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
4
+ <button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
5
+ </div>`:"",n=h?`<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
6
+ <div class="wx-auth-qrcode-container wx-auth-mp-container">
7
+ <div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
8
+ <img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
9
+ <div class="wx-auth-mp-expired" style="display:none">
10
+ <div class="wx-auth-mp-expired-text">二维码已过期</div>
11
+ <button type="button" class="wx-auth-btn wx-auth-btn-primary wx-auth-mp-refresh" onclick="WxAuth.startMpLogin()">刷新二维码</button>
12
+ </div>
13
+ </div>
14
+ <div class="wx-auth-desc wx-auth-mp-hint">微信扫描二维码,打开小程序确认登录</div>
15
+ <div class="wx-auth-mp-status"></div>
16
+ </div>`:"";return e.innerHTML=`
17
+ <div class="wx-auth-overlay" ${a.required?'onclick="event.preventDefault()"':""}></div>
4
18
  <div class="wx-auth-content">
5
19
  <div class="wx-auth-header">
6
20
  <div class="wx-auth-title">微信登录</div>
7
21
  ${t}
8
22
  </div>
9
23
  <div class="wx-auth-body">
10
- <!-- 二维码区域 -->
11
- <div>
12
- <div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
13
- <div class="wx-auth-qrcode-container">
14
- <img class="wx-auth-qrcode" src="" alt="扫码关注" />
24
+ ${o}
25
+
26
+ <!-- 面板一:公众号验证码 -->
27
+ <div class="wx-auth-panel wx-auth-panel-code">
28
+ <!-- 二维码区域 -->
29
+ <div>
30
+ <div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
31
+ <div class="wx-auth-qrcode-container">
32
+ <img class="wx-auth-qrcode" src="" alt="扫码关注" />
33
+ </div>
34
+ </div>
35
+
36
+ <!-- 验证码输入区域 -->
37
+ <div>
38
+ <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
39
+ <div class="wx-auth-note">保持关注,即可一直自动登录</div>
40
+ ${u.generateCodeInputs()}
15
41
  </div>
16
- </div>
17
42
 
18
- <!-- 验证码输入区域 -->
19
- <div>
20
- <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
21
- <div class="wx-auth-note">保持关注,即可一直自动登录</div>
22
- ${c.generateCodeInputs()}
43
+ <!-- 按钮 -->
44
+ <div class="wx-auth-actions">
45
+ <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
46
+ </div>
23
47
  </div>
24
48
 
49
+ <!-- 面板二:小程序扫码 -->
50
+ ${n}
51
+
25
52
  <!-- 消息提示 -->
26
53
  <div class="wx-auth-message" style="display:none"></div>
27
-
28
- <!-- 按钮 -->
29
- <div class="wx-auth-actions">
30
- <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
31
- </div>
32
54
  </div>
33
55
  </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"})}));
56
+ `,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(()=>y.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,g)=>{e[g]&&(e[g].value=d)}),r.length===6&&setTimeout(()=>y.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,x.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(),h&&p==="mp"&&y.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,x.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()}},y={init(e={}){if(a={...q,...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{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=u.getToken();if(!e)return!1;const t=await S(e);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)},async autoCheck(){const e=u.getToken();if(!e)return this.showAuthModal(),!1;const t=await S(e);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({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(){c.show();try{const t=l?`?siteId=${encodeURIComponent(l)}`:"",o=await u.request(`${a.apiBase}/api/sdk/config${t}`);o.wechatName&&!a.wechatName&&(a.wechatName=o.wechatName),o.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=o.qrcodeUrl),h=!!o.mpScanEnabled}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}this.syncMpTabs(),this.switchMode(h?"mp":"code"),a.qrcodeUrl&&c.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)},syncMpTabs(){const e=document.getElementById("wx-auth-modal");if(!e)return;const t=!!e.querySelector(".wx-auth-tabs");h!==t&&(e.remove(),c.createModal())},switchMode(e){p=h?e:"code";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(!h||!s.isOpen)return;const e=++f;if(c.setMpExpiredVisible(!1),c.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){c.setMpQr(s.mpSession.qrDataUrl),C(e);return}try{const t=await u.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:l}});if(e!==f||!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},c.setMpQr(s.mpSession.qrDataUrl),C(e)}catch(t){if(e!==f||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码",t),this.switchMode("code"),c.showMessage("小程序扫码暂不可用,请使用公众号验证码登录","error")}},async requireAuth(){const e=u.getToken();if(e){const t=await S(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&u.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&&u.setToken(e.token),h&&p==="mp")c.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=c.getVerifyCode();if(!e||e.length!==6){c.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 u.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?this.completeLogin(n):(c.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),c.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){c.showMessage(b(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){c.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){u.clearToken()},async revoke(){const e=u.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(y)),w.WxAuth=y,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.23",
3
+ "version": "1.2.25",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",