wx-auth-sdk 1.2.24 → 1.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,7 +37,7 @@ SDK 会自动:
37
37
 
38
38
  ## 登录态与 Cookie 域
39
39
 
40
- 认证成功后,SDK 将签名 Token 写入 Cookie(**按根域存储,有效期 365 天**),并自动在 localStorage 存一份备份。Cookie 的 `domain` 由**当前页面域名**推导,而不是后端地址(apiBase):
40
+ 认证成功后,SDK 将签名 Token 写入 Cookie(**按根域存储,会话 Cookie——不设有效期,浏览器关闭即失效**)。Cookie 的 `domain` 由**当前页面域名**推导,而不是后端地址(apiBase):
41
41
 
42
42
  | 页面域名 | Cookie 落点 | 登录态共享范围 |
43
43
  |---------|------------|---------------|
@@ -50,7 +50,7 @@ SDK 会自动:
50
50
  - **同一注册域内一个认证,全域自动登录**:`sub1.mysite.com` 认证后,`sub2.mysite.com`、根域 `mysite.com` 都能静默通过(凭根域 Cookie)。
51
51
  - **跨注册域不共享**:`mysite.com` 与 `other.com` 是相互独立的登录态,需各自认证一次(浏览器安全机制,无法绕过)。
52
52
  - **主站已登录 → 子站有登录态**:`panhub.shenzjd.com` 认证后,访问 `parse.shenzjd.com` 等其他子站同样静默通过。
53
- - **localStorage 备份按站点隔离**:仅作为清 Cookie 后的兜底恢复,真正的跨子域凭证是根域 Cookie。
53
+ - **登录态为会话级(2026-08-30)**:Cookie 不设有效期,浏览器关闭后登录态即失效,下次打开需重新扫码登录;同一浏览器会话内刷新、新开标签页均保持登录(web 定位为小程序引流入口的策略,见主仓库 AGENTS.md)。
54
54
  - **⚠️ 多级公共后缀**:若页面域名属于 `.com.cn` / `.co.uk` 等多级后缀(如 `site.mysite.com.cn`),"取最后两段"会推导出 `.com.cn`,浏览器会拒绝写入。此类接入需确认域名后再接入。
55
55
 
56
56
  > **为什么 cookie 不跟 apiBase 走?** 早期版本 SDK 曾按 apiBase 域名写 Cookie,导致部署在第三方域名(`apiBase` 指向微信认证后端、页面域名不同)时 Cookie 落错域、后端起总不到凭证、前端反复弹窗(死循环)。SDK 已改为始终按「页面所在域」写 Cookie,与后端地址无关。
@@ -139,8 +139,6 @@ WxAuth.init({
139
139
  │ └──────┘ │
140
140
  │ │
141
141
  │ 2. 发送"验证码"获取 │
142
- │ 取消关注公众号后将被 │ ← 新增提示
143
- │ 取消认证,请保持关注 │
144
142
  │ [_][_][_][_][_][_] │
145
143
  │ │
146
144
  │ [ 验证 ] │
@@ -176,11 +174,10 @@ WxAuth.init({
176
174
  | 输入完成自动提交 | ✅ |
177
175
  | 有 Cookie 静默认证 | ✅ |
178
176
  | Cookie 按页面根域写入(跨子域共享) | ✅ |
179
- | 清 Cookie 自动恢复(签名 Token 双存储:Cookie + localStorage) | ✅ |
177
+ | 会话 Cookie 登录态(浏览器关闭即失效,下次重新扫码) | ✅ |
180
178
  | F12 删弹窗自动恢复 | ✅ |
181
179
 
182
- > **清 Cookie 恢复说明**:Token 同时存 Cookie 与 localStorage。清除 Cookie 后,只要服务端认证状态仍有效,SDK 会凭 localStorage 备份静默恢复并重写 Cookie。
183
- > 注意:备份按站点隔离(不跨子域);清全部站点数据则无法恢复(符合隐私预期)。
180
+ > **登录态有效期(2026-08-30)**:登录态只活在当前浏览器进程内(会话 Cookie,不再写 localStorage 备份)。关闭浏览器后需重新扫码登录;同一浏览器会话内刷新、新开标签页均保持登录。
184
181
 
185
182
  ---
186
183
 
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 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
- console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
13
+ for (const n of o)
14
+ if (n.type === "childList")
15
+ for (const s of n.removedNodes) {
16
+ if (s.nodeType !== Node.ELEMENT_NODE) continue;
17
+ const d = s;
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 r = document.getElementById(e.modalId);
35
- (!r || !r.isConnected || h.isHidden(r)) && (console.warn(
34
+ const n = document.getElementById(e.modalId);
35
+ (!n || !n.isConnected || m.isHidden(n)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
- { has: !!r, connected: r?.isConnected, hidden: r ? h.isHidden(r) : null }
38
- ), h.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
37
+ { has: !!n, connected: n?.isConnected, hidden: n ? m.isHidden(n) : 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: r } = e;
80
+ const { modalId: t, getState: o, onRestore: n } = e;
81
81
  if (!o().isOpen) return;
82
- const n = document.getElementById(t);
83
- if (n) {
84
- n.style.display = "flex", n.style.visibility = "visible", n.style.opacity = "1";
82
+ const s = document.getElementById(t);
83
+ if (s) {
84
+ s.style.display = "flex", s.style.visibility = "visible", s.style.opacity = "1";
85
85
  return;
86
86
  }
87
- r();
87
+ n();
88
88
  }
89
- }, y = {
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 = { ...y }, u = "", c = {
107
+ let r = { ...q }, u = "", a = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
- currentStep: "qr"
111
- };
112
- function k(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 "";
@@ -119,65 +120,54 @@ function k(e) {
119
120
  return "";
120
121
  }
121
122
  }
122
- const a = {
123
+ const c = {
123
124
  getRootDomain() {
124
- return k(window.location.hostname);
125
+ return A(window.location.hostname);
125
126
  },
126
127
  // 获取Cookie
127
128
  getCookie(e) {
128
129
  const o = `; ${document.cookie}`.split(`; ${e}=`);
129
130
  return o.length === 2 && o.pop()?.split(";").shift() || null;
130
131
  },
131
- // 设置Cookie(30天过期,自动设置根域名实现跨子域共享)
132
+ // 设置Cookie(会话 Cookie,2026-08-30:不设 expires —— 浏览器关闭即失效,
133
+ // 下次打开需重新扫码登录;自动设置根域名实现跨子域共享)
132
134
  setCookie(e, t) {
133
- const o = /* @__PURE__ */ new Date();
134
- o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
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`;
135
+ const o = this.getRootDomain(), n = o ? `;domain=${o}` : "", d = window.location.protocol === "https:" ? ";Secure" : "";
136
+ document.cookie = `${e}=${t};path=/${n}${d};SameSite=Strict`;
137
137
  },
138
138
  // 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
139
139
  deleteCookie(e) {
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
- },
143
- // ===== 签名 Token 双存储(Cookie 主 + localStorage 备份) =====
144
- // 目标:用户清除 Cookie 后,若服务端认证状态仍有效,可凭备份静默恢复。
145
- // 存储的是签名 Token(HMAC,不可伪造),而非明文 openid(永久凭证),
146
- // 与 Cookie 同策略(均非 HttpOnly),安全模型零降级。
147
- // 注意:localStorage 按站点隔离(不跨子域),Cookie 是根域共享。
148
- // localStorage 备份的 key(避免与接入方业务 key 冲突,加前缀)
149
- get storageKey() {
150
- return "wxauth-token";
151
- },
152
- // 读取:Cookie 优先(权威),localStorage 兜底(备份,用于恢复)
140
+ const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", s = window.location.protocol === "https:" ? ";Secure" : "";
141
+ document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${s};SameSite=Strict`;
142
+ },
143
+ // ===== 签名 Token 存储(会话 Cookie,2026-08-30)=====
144
+ // 登录态策略:登录态只活在当前浏览器进程内——Cookie 不设 expires,浏览器
145
+ // 关闭即失效,下次打开需重新扫码(web 定位为小程序引流入口,见 AGENTS.md)。
146
+ // 旧版本的 localStorage 备份已移除:备份会让登录态在浏览器重启后"复活",
147
+ // 击穿会话语义;clearToken 保留对旧备份 key 的防御性清理(升级用户的残留)。
148
+ // 存储的是签名 Token(HMAC,不可伪造),而非明文 openid(永久凭证)。
149
+ // 注意:Cookie 是根域共享;localStorage 按站点隔离,且不再读取。
150
+ // 读取:仅会话 Cookie(旧版本 localStorage 备份不再兜底)
153
151
  getToken() {
154
- const e = this.getCookie("wxauth-token");
155
- if (e) return e;
156
- try {
157
- return window.localStorage.getItem(this.storageKey);
158
- } catch {
159
- return null;
160
- }
152
+ return this.getCookie("wxauth-token");
161
153
  },
162
- // 写入:Cookie + localStorage 双写(验证成功后调用,同步刷新备份)
154
+ // 写入:仅会话 Cookie
163
155
  setToken(e) {
164
156
  this.setCookie("wxauth-token", e);
165
- try {
166
- window.localStorage.setItem(this.storageKey, e);
167
- } catch {
168
- }
169
157
  },
170
- // 删除:双删(同时清掉明文 openid Cookie —— 防御性清理,服务端已下线 openid 通道 2026-08-26)
158
+ // 删除:清 Cookie + 防御性清理旧版本 localStorage 备份残留
159
+ // (同时清掉明文 openid Cookie —— 防御性清理,服务端已下线 openid 通道 2026-08-26)
171
160
  clearToken() {
172
161
  this.deleteCookie("wxauth-token"), this.deleteCookie("wxauth-openid");
173
162
  try {
174
- window.localStorage.removeItem(this.storageKey);
163
+ window.localStorage.removeItem("wxauth-token");
175
164
  } catch {
176
165
  }
177
166
  },
178
167
  // 发送请求
179
168
  // 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
180
169
  // 供调用方区分「明确未认证」与「瞬时失败」——后者不应触发重新验证(2026-08-29)
170
+ // body 接受任意可 JSON 序列化对象(实现统一 JSON.stringify,非 BodyInit)
181
171
  async request(e, t = {}) {
182
172
  try {
183
173
  const o = await fetch(e, {
@@ -190,13 +180,13 @@ const a = {
190
180
  credentials: "include"
191
181
  });
192
182
  if (!o.ok) {
193
- const r = new Error(`HTTP ${o.status}`);
194
- throw r.status = o.status, r;
183
+ const n = new Error(`HTTP ${o.status}`);
184
+ throw n.status = o.status, n;
195
185
  }
196
186
  return await o.json();
197
187
  } catch (o) {
198
- const r = o;
199
- throw r.status === void 0 && (r.isNetworkError = !0), console.error("[WxAuth] Request error:", o), r;
188
+ const n = o;
189
+ throw n.status === void 0 && (n.isNetworkError = !0), console.error("[WxAuth] Request error:", o), n;
200
190
  }
201
191
  },
202
192
  // 生成6位验证码输入框HTML
@@ -206,62 +196,114 @@ const a = {
206
196
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
207
197
  return e += "</div>", e;
208
198
  }
209
- }, p = [1e3, 3e3];
210
- function v(e) {
199
+ }, b = [1e3, 3e3];
200
+ function k(e) {
211
201
  const t = e;
212
202
  return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
213
203
  }
214
- function g(e) {
204
+ function x(e) {
215
205
  return new Promise((t) => setTimeout(t, e));
216
206
  }
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++)
207
+ const C = 2e3, E = 3e3;
208
+ function v() {
209
+ p++;
210
+ }
211
+ async function S(e) {
212
+ for (; e === p && a.isOpen; ) {
213
+ const t = a.mpSession;
214
+ if (!t || Date.now() >= t.expiresAt) break;
220
215
  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)
216
+ const o = await c.request(
217
+ `${r.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
218
+ );
219
+ if (e !== p) return;
220
+ if (o.status === "confirmed" && o.token) {
221
+ w.completeLogin(o);
222
+ return;
223
+ }
224
+ if (o.status === "expired") {
225
+ a.mpSession = null;
226
+ break;
227
+ }
228
+ } catch (o) {
229
+ if (e !== p) return;
230
+ if (!k(o)) break;
231
+ await x(E);
232
+ continue;
233
+ }
234
+ await x(C);
235
+ }
236
+ e === p && a.isOpen && f === "mp" && l.showMpExpired();
237
+ }
238
+ async function y(e) {
239
+ const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${r.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
240
+ for (let n = 0; ; n++)
241
+ try {
242
+ const s = await c.request(o);
243
+ return s.authenticated ? { kind: "ok", result: s } : s.error === "rate_limited" || s.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: s };
244
+ } catch (s) {
245
+ if (!k(s) || n >= b.length)
225
246
  return { kind: "transient" };
226
- await g(p[r]);
247
+ await x(b[n]);
227
248
  }
228
249
  }
229
- const d = {
250
+ const l = {
230
251
  // 创建弹窗
231
252
  createModal() {
232
253
  const e = document.createElement("div");
233
- e.id = "wx-auth-modal", e.className = "wx-auth-modal", s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
234
- const t = s.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
254
+ e.id = "wx-auth-modal", e.className = "wx-auth-modal", r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
255
+ const t = r.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>', o = h ? `<div class="wx-auth-tabs">
256
+ <button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
257
+ <button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
258
+ </div>` : "", n = h ? `<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
259
+ <div class="wx-auth-qrcode-container wx-auth-mp-container">
260
+ <div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
261
+ <img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
262
+ <div class="wx-auth-mp-expired" style="display:none">
263
+ <div class="wx-auth-mp-expired-text">二维码已过期</div>
264
+ <button type="button" class="wx-auth-btn wx-auth-btn-primary wx-auth-mp-refresh" onclick="WxAuth.startMpLogin()">刷新二维码</button>
265
+ </div>
266
+ </div>
267
+ <div class="wx-auth-desc wx-auth-mp-hint">微信扫描二维码,打开小程序确认登录</div>
268
+ <div class="wx-auth-mp-status"></div>
269
+ </div>` : "";
235
270
  return e.innerHTML = `
236
- <div class="wx-auth-overlay" ${s.required ? 'onclick="event.preventDefault()"' : ""}></div>
271
+ <div class="wx-auth-overlay" ${r.required ? 'onclick="event.preventDefault()"' : ""}></div>
237
272
  <div class="wx-auth-content">
238
273
  <div class="wx-auth-header">
239
274
  <div class="wx-auth-title">微信登录</div>
240
275
  ${t}
241
276
  </div>
242
277
  <div class="wx-auth-body">
243
- <!-- 二维码区域 -->
244
- <div>
245
- <div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
246
- <div class="wx-auth-qrcode-container">
247
- <img class="wx-auth-qrcode" src="" alt="扫码关注" />
278
+ ${o}
279
+
280
+ <!-- 面板一:公众号验证码 -->
281
+ <div class="wx-auth-panel wx-auth-panel-code">
282
+ <!-- 二维码区域 -->
283
+ <div>
284
+ <div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
285
+ <div class="wx-auth-qrcode-container">
286
+ <img class="wx-auth-qrcode" src="" alt="扫码关注" />
287
+ </div>
288
+ </div>
289
+
290
+ <!-- 验证码输入区域 -->
291
+ <div>
292
+ <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
293
+ ${c.generateCodeInputs()}
248
294
  </div>
249
- </div>
250
295
 
251
- <!-- 验证码输入区域 -->
252
- <div>
253
- <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
254
- <div class="wx-auth-note">保持关注,即可一直自动登录</div>
255
- ${a.generateCodeInputs()}
296
+ <!-- 按钮 -->
297
+ <div class="wx-auth-actions">
298
+ <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
299
+ </div>
256
300
  </div>
257
301
 
302
+ <!-- 面板二:小程序扫码 -->
303
+ ${n}
304
+
258
305
  <!-- 消息提示 -->
259
306
  <div class="wx-auth-message" style="display:none"></div>
260
-
261
- <!-- 按钮 -->
262
- <div class="wx-auth-actions">
263
- <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
264
- </div>
265
307
  </div>
266
308
  </div>
267
309
  `, document.body.appendChild(e), this.bindInputEvents(), e;
@@ -271,18 +313,18 @@ const d = {
271
313
  setTimeout(() => {
272
314
  const e = document.querySelectorAll(".wx-auth-input");
273
315
  e.length && e.forEach((t, o) => {
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));
316
+ t.addEventListener("input", (n) => {
317
+ const s = n.target.value.replace(/\D/g, "");
318
+ n.target.value = s, s && o < 5 && e[o + 1].focus(), o === 5 && s && setTimeout(() => w.verifyCode(), 300);
319
+ }), t.addEventListener("keydown", (n) => {
320
+ const s = n.target;
321
+ n.key === "Backspace" && !s.value && o > 0 ? e[o - 1].focus() : n.key === "ArrowLeft" && o > 0 ? (n.preventDefault(), e[o - 1].focus()) : n.key === "ArrowRight" && o < 5 && (n.preventDefault(), e[o + 1].focus());
322
+ }), t.addEventListener("paste", (n) => {
323
+ n.preventDefault();
324
+ const s = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
325
+ s && (s.split("").forEach((d, g) => {
326
+ e[g] && (e[g].value = d);
327
+ }), s.length === 6 && setTimeout(() => w.verifyCode(), 300));
286
328
  });
287
329
  });
288
330
  }, 100);
@@ -290,19 +332,19 @@ const d = {
290
332
  // 显示弹窗
291
333
  show() {
292
334
  let e = document.getElementById("wx-auth-modal");
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 = "");
335
+ e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.querySelectorAll(".wx-auth-input").forEach((s) => s.value = "");
294
336
  const o = e.querySelector(".wx-auth-message");
295
337
  o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
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({
338
+ const n = e.querySelector(".wx-auth-btn-primary");
339
+ n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), v(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, m.enable({
298
340
  modalId: "wx-auth-modal",
299
- getState: () => c,
341
+ getState: () => a,
300
342
  onRestore: () => {
301
- this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
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();
343
+ this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
344
+ const s = document.querySelector(".wx-auth-wechat-name");
345
+ s && r.wechatName && (s.textContent = `"${r.wechatName}"`), this.bindInputEvents(), h && f === "mp" && w.switchMode("mp"), setTimeout(() => {
346
+ const d = document.querySelector(".wx-auth-input");
347
+ d && d.focus();
306
348
  }, 100);
307
349
  }
308
350
  });
@@ -310,7 +352,7 @@ const d = {
310
352
  // 隐藏弹窗
311
353
  hide() {
312
354
  const e = document.getElementById("wx-auth-modal");
313
- e && (e.style.display = "none", c.isOpen = !1, h.disable());
355
+ e && (e.style.display = "none", a.isOpen = !1, v(), a.mpSession = null, m.disable());
314
356
  },
315
357
  // 设置二维码
316
358
  setQrCode(e) {
@@ -318,6 +360,31 @@ const d = {
318
360
  const t = document.querySelector(".wx-auth-qrcode");
319
361
  t && (t.src = e, t.style.display = "block");
320
362
  },
363
+ // ===== 小程序扫码面板(2026-08-29)=====
364
+ // 展示小程序码(隐藏 loading 与过期遮罩,保持画面干净)
365
+ setMpQr(e) {
366
+ const t = document.getElementById("wx-auth-modal"), o = t?.querySelector(".wx-auth-mp-qrcode"), n = t?.querySelector(".wx-auth-mp-loading");
367
+ o && (o.src = e, o.style.display = "block", n && (n.style.display = "none"), this.setMpExpiredVisible(!1), this.setMpStatus("", !1));
368
+ },
369
+ // 过期遮罩显示/隐藏:盖在二维码上(「二维码已过期」+ 绿色刷新按钮)
370
+ setMpExpiredVisible(e) {
371
+ const o = document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");
372
+ o && (o.style.display = e ? "flex" : "none");
373
+ },
374
+ // 更新扫码面板状态文案;text 为空 = 隐藏状态行;spinner=true 时回列出码 loading
375
+ setMpStatus(e, t) {
376
+ const o = document.getElementById("wx-auth-modal"), n = o?.querySelector(".wx-auth-mp-status");
377
+ n && (n.textContent = e, n.style.display = e ? "block" : "none");
378
+ const s = o?.querySelector(".wx-auth-mp-loading");
379
+ if (s && (s.style.display = t ? "flex" : "none"), t) {
380
+ const d = o?.querySelector(".wx-auth-mp-qrcode");
381
+ d && (d.style.display = "none");
382
+ }
383
+ },
384
+ // 二维码过期/失效:遮罩盖住旧码,用户点「刷新二维码」重新出码
385
+ showMpExpired() {
386
+ this.setMpExpiredVisible(!0);
387
+ },
321
388
  // 显示消息
322
389
  showMessage(e, t = "info") {
323
390
  const o = document.querySelector(".wx-auth-message");
@@ -338,7 +405,7 @@ const d = {
338
405
  }, w = {
339
406
  // 初始化
340
407
  init(e = {}) {
341
- if (s = { ...y, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
408
+ if (r = { ...q, ...e }, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
342
409
  console.error("[WxAuth] apiBase is required");
343
410
  return;
344
411
  }
@@ -351,7 +418,7 @@ const d = {
351
418
  }
352
419
  !u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
353
420
  }
354
- console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
421
+ console.log("[WxAuth] SDK initialized", r), typeof window < "u" && (r.silent ? this.silentCheck() : this.autoCheck());
355
422
  },
356
423
  /**
357
424
  * 静默验证(silent 模式专用)
@@ -363,18 +430,18 @@ const d = {
363
430
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
364
431
  */
365
432
  async silentCheck() {
366
- const e = a.getToken();
433
+ const e = c.getToken();
367
434
  if (!e) return !1;
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);
435
+ const t = await y(e);
436
+ 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);
370
437
  },
371
438
  // 自动检测凭证并验证(内部使用)
372
439
  async autoCheck() {
373
- const e = a.getToken();
440
+ const e = c.getToken();
374
441
  if (!e)
375
442
  return this.showAuthModal(), !1;
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({
443
+ const t = await y(e);
444
+ 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({
378
445
  code: "server_error",
379
446
  retryable: !0,
380
447
  message: "登录服务暂时不可用,请稍后重试"
@@ -382,30 +449,74 @@ const d = {
382
449
  },
383
450
  // 显示认证弹窗(内部使用)
384
451
  async showAuthModal() {
385
- d.show();
452
+ l.show();
386
453
  try {
387
- const t = u ? `?siteId=${encodeURIComponent(u)}` : "", o = await a.request(
388
- `${s.apiBase}/api/sdk/config${t}`
454
+ const t = u ? `?siteId=${encodeURIComponent(u)}` : "", o = await c.request(
455
+ `${r.apiBase}/api/sdk/config${t}`
389
456
  );
390
- o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
457
+ o.wechatName && !r.wechatName && (r.wechatName = o.wechatName), o.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = o.qrcodeUrl), h = !!o.mpScanEnabled;
391
458
  } catch (t) {
392
459
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
393
460
  }
394
- s.qrcodeUrl && d.setQrCode(s.qrcodeUrl);
461
+ this.syncMpTabs(), this.switchMode(h ? "mp" : "code"), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
395
462
  const e = document.querySelector(".wx-auth-wechat-name");
396
- e && s.wechatName && (e.textContent = `"${s.wechatName}"`), setTimeout(() => {
463
+ e && r.wechatName && (e.textContent = `"${r.wechatName}"`), setTimeout(() => {
397
464
  const t = document.querySelector(".wx-auth-input");
398
465
  t && t.focus();
399
466
  }, 100);
400
467
  },
468
+ // 按 mpScanAvailable 校正弹窗 DOM:缺 tab(首次打开时后端才返回开关)或多余
469
+ // tab(开关翻转)时重建弹窗。其余情况不动(避免清空用户输入)
470
+ syncMpTabs() {
471
+ const e = document.getElementById("wx-auth-modal");
472
+ if (!e) return;
473
+ const t = !!e.querySelector(".wx-auth-tabs");
474
+ h !== t && (e.remove(), l.createModal());
475
+ },
476
+ // 切换登录方式(tab 点击 / 默认模式设定)
477
+ switchMode(e) {
478
+ f = h ? e : "code";
479
+ const t = document.getElementById("wx-auth-modal");
480
+ if (!t) return;
481
+ t.querySelectorAll(".wx-auth-tab").forEach((s) => {
482
+ s.classList.toggle("wx-auth-tab-active", s.dataset.mode === f);
483
+ });
484
+ const o = t.querySelector(".wx-auth-panel-code"), n = t.querySelector(".wx-auth-panel-mp");
485
+ o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : v();
486
+ },
487
+ // 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
488
+ async startMpLogin() {
489
+ if (!h || !a.isOpen) return;
490
+ const e = ++p;
491
+ if (l.setMpExpiredVisible(!1), l.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
492
+ l.setMpQr(a.mpSession.qrDataUrl), S(e);
493
+ return;
494
+ }
495
+ try {
496
+ const t = await c.request(`${r.apiBase}/api/auth/mp-scan/create`, {
497
+ method: "POST",
498
+ body: { siteId: u }
499
+ });
500
+ if (e !== p || !a.isOpen) return;
501
+ if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
502
+ a.mpSession = {
503
+ ticket: String(t.ticket),
504
+ qrDataUrl: String(t.qrDataUrl),
505
+ expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
506
+ }, l.setMpQr(a.mpSession.qrDataUrl), S(e);
507
+ } catch (t) {
508
+ if (e !== p || !a.isOpen) return;
509
+ console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"), l.showMessage("小程序扫码暂不可用,请使用公众号验证码登录", "error");
510
+ }
511
+ },
401
512
  // 主入口:需要验证时调用
402
- // 凭证仅签名 Token(Cookie 优先 + localStorage 兜底),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
513
+ // 凭证仅签名 Token(会话 Cookie),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
403
514
  async requireAuth() {
404
- const e = a.getToken();
515
+ const e = c.getToken();
405
516
  if (e) {
406
- const t = await m(e);
517
+ const t = await y(e);
407
518
  if (t.kind === "ok")
408
- return console.log("[WxAuth] 已认证(凭证)"), t.result.token && a.setToken(t.result.token), this.onVerified(t.result.user), !0;
519
+ return console.log("[WxAuth] 已认证(凭证)"), t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0;
409
520
  if (t.kind === "transient")
410
521
  return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
411
522
  code: "server_error",
@@ -414,14 +525,29 @@ const d = {
414
525
  }), !1;
415
526
  }
416
527
  return await this.showAuthModal(), new Promise((t) => {
417
- c.resolveAuth = t;
528
+ a.resolveAuth = t;
418
529
  });
419
530
  },
531
+ // 共享登录成功路径(验证码校验成功 / 小程序扫码确认成功均走这里)
532
+ // 顺序很重要:必须先 onVerified() 触发 resolveAuth(true),
533
+ // 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
534
+ // close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
535
+ completeLogin(e) {
536
+ if (e?.token && c.setToken(e.token), h && f === "mp")
537
+ l.setMpStatus("✅ 登录成功", !1);
538
+ else {
539
+ const t = document.querySelector(".wx-auth-btn-primary");
540
+ t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
541
+ }
542
+ setTimeout(() => {
543
+ this.onVerified(e?.user), this.close(!0);
544
+ }, 500);
545
+ },
420
546
  // 验证验证码
421
547
  async verifyCode() {
422
- const e = d.getVerifyCode();
548
+ const e = l.getVerifyCode();
423
549
  if (!e || e.length !== 6) {
424
- d.showMessage("请输入6位验证码", "error");
550
+ l.showMessage("请输入6位验证码", "error");
425
551
  return;
426
552
  }
427
553
  const t = document.querySelector(
@@ -429,18 +555,16 @@ const d = {
429
555
  );
430
556
  t && (t.disabled = !0, t.textContent = "登录中...");
431
557
  try {
432
- const o = u ? `&siteId=${encodeURIComponent(u)}` : "", r = await a.request(
433
- `${s.apiBase}/api/auth/check?authToken=${e}${o}`
558
+ const o = u ? `&siteId=${encodeURIComponent(u)}` : "", n = await c.request(
559
+ `${r.apiBase}/api/auth/check?authToken=${e}${o}`
434
560
  );
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" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
561
+ n.authenticated ? this.completeLogin(n) : (l.showMessage(
562
+ n.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
439
563
  "error"
440
- ), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
564
+ ), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
441
565
  } catch (o) {
442
- d.showMessage(
443
- v(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
566
+ l.showMessage(
567
+ k(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
444
568
  "error"
445
569
  ), t && (t.disabled = !1, t.textContent = "登录");
446
570
  }
@@ -449,29 +573,26 @@ const d = {
449
573
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
450
574
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
451
575
  close(e = !1) {
452
- d.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
576
+ l.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
453
577
  },
454
- // 清空本地认证凭证(双重删除:Cookie + localStorage)
578
+ // 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
455
579
  // 用于"退出登录 / 清空认证状态"按钮。
456
- // 注意:signedToken 双存储备份(localStorage)若不清,清 Cookie 后
457
- // SDK 会凭备份静默恢复(getToken 优先 Cookie、localStorage 兜底),
458
- // 造成"清不掉"的假象——所以必须走这里而非只删 Cookie。
459
580
  clearToken() {
460
- a.clearToken();
581
+ c.clearToken();
461
582
  },
462
583
  // 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
463
584
  // 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
464
- // 吊销黑名单。此后任意子域/设备的 localStorage 备份都无法再恢复登录态
585
+ // 吊销黑名单。此后该 token 在任何设备/子域都无法再通过服务端校验
465
586
  // (根治「A 域退出、B 域还能用」的双写恢复问题)。
466
587
  // 幂等安全:网络失败 /* 后端不可达 */ 时静默降级为仅本地清理(clearToken),
467
588
  // 不阻塞退出流程;token 无效也会返回 success(本地照常清理)。
468
589
  // 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
469
590
  // 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
470
591
  async revoke() {
471
- const e = a.getToken();
592
+ const e = c.getToken();
472
593
  if (e)
473
594
  try {
474
- const t = s.apiBase && !/\/$/.test(s.apiBase) ? s.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
595
+ const t = r.apiBase && !/\/$/.test(r.apiBase) ? r.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
475
596
  method: "POST",
476
597
  headers: { "Content-Type": "application/json" },
477
598
  body: JSON.stringify({ token: e }),
@@ -485,11 +606,11 @@ const d = {
485
606
  },
486
607
  // 验证成功回调
487
608
  onVerified(e) {
488
- console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), c.resolveAuth && (c.resolveAuth(!0), c.resolveAuth = null);
609
+ console.log("[WxAuth] 验证成功", e), typeof r.onVerified == "function" && r.onVerified(e), a.resolveAuth && (a.resolveAuth(!0), a.resolveAuth = null);
489
610
  },
490
611
  // 错误回调
491
612
  onError(e) {
492
- console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
613
+ console.error("[WxAuth] 错误", e), typeof r.onError == "function" && r.onError(e);
493
614
  }
494
615
  };
495
616
  typeof window < "u" && (window.WxAuth = Object.freeze(w));
@@ -1,5 +1,19 @@
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 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=`
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()}},S={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...S},l="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},h=!1,p="code",f=0;function E(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const u={getRootDomain(){return E(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=this.getRootDomain(),n=o?`;domain=${o}`:"",d=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};path=/${n}${d};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",r=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`},getToken(){return this.getCookie("wxauth-token")},setToken(e){this.setCookie("wxauth-token",e)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},q=[1e3,3e3];function g(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function b(e){return new Promise(t=>setTimeout(t,e))}const I=2e3,M=3e3;function k(){f++}async function A(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(!g(o))break;await b(M);continue}await b(I)}e===f&&s.isOpen&&p==="mp"&&c.showMpExpired()}async function v(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await 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(!g(r)||n>=q.length)return{kind:"transient"};await b(q[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=`
3
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">
@@ -7,28 +21,35 @@
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
+ ${u.generateCodeInputs()}
15
40
  </div>
16
- </div>
17
41
 
18
- <!-- 验证码输入区域 -->
19
- <div>
20
- <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
21
- <div class="wx-auth-note">保持关注,即可一直自动登录</div>
22
- ${s.generateCodeInputs()}
42
+ <!-- 按钮 -->
43
+ <div class="wx-auth-actions">
44
+ <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
45
+ </div>
23
46
  </div>
24
47
 
48
+ <!-- 面板二:小程序扫码 -->
49
+ ${n}
50
+
25
51
  <!-- 消息提示 -->
26
52
  <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
53
  </div>
33
54
  </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 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"})}));
55
+ `,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>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,C)=>{e[C]&&(e[C].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=""),k(),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,k(),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={...S,...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 v(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 v(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():k()},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),A(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),A(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 v(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(g(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.24",
3
+ "version": "1.2.26",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",