wx-auth-sdk 1.2.25 → 1.2.27
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 +4 -7
- package/dist/index.d.ts +0 -1
- package/dist/wx-auth.js +148 -148
- package/dist/wx-auth.umd.js +5 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ SDK 会自动:
|
|
|
37
37
|
|
|
38
38
|
## 登录态与 Cookie 域
|
|
39
39
|
|
|
40
|
-
认证成功后,SDK 将签名 Token 写入 Cookie
|
|
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
|
-
-
|
|
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
|
-
|
|
|
177
|
+
| 会话 Cookie 登录态(浏览器关闭即失效,下次重新扫码) | ✅ |
|
|
180
178
|
| F12 删弹窗自动恢复 | ✅ |
|
|
181
179
|
|
|
182
|
-
>
|
|
183
|
-
> 注意:备份按站点隔离(不跨子域);清全部站点数据则无法恢复(符合隐私预期)。
|
|
180
|
+
> **登录态有效期(2026-08-30)**:登录态只活在当前浏览器进程内(会话 Cookie,不再写 localStorage 备份)。关闭浏览器后需重新扫码登录;同一浏览器会话内刷新、新开标签页均保持登录。
|
|
184
181
|
|
|
185
182
|
---
|
|
186
183
|
|
package/dist/index.d.ts
CHANGED
|
@@ -14,7 +14,6 @@ export declare const WxAuth: {
|
|
|
14
14
|
silentCheck(): Promise<boolean>;
|
|
15
15
|
autoCheck(): Promise<boolean>;
|
|
16
16
|
showAuthModal(): Promise<void>;
|
|
17
|
-
syncMpTabs(): void;
|
|
18
17
|
switchMode(mode: LoginMode): void;
|
|
19
18
|
startMpLogin(): Promise<void>;
|
|
20
19
|
requireAuth(): Promise<boolean>;
|
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
|
-
},
|
|
6
|
+
}, p = {
|
|
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
|
|
14
|
-
if (
|
|
15
|
-
for (const
|
|
16
|
-
if (
|
|
17
|
-
const d =
|
|
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
18
|
if (d.id === e.modalId || d.querySelector?.(`#${e.modalId}`)) {
|
|
19
|
-
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),
|
|
19
|
+
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), p.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
|
|
35
|
-
(!
|
|
34
|
+
const n = document.getElementById(e.modalId);
|
|
35
|
+
(!n || !n.isConnected || p.isHidden(n)) && (console.warn(
|
|
36
36
|
"[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
|
|
37
|
-
{ has: !!
|
|
38
|
-
),
|
|
37
|
+
{ has: !!n, connected: n?.isConnected, hidden: n ? p.isHidden(n) : null }
|
|
38
|
+
), p.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
|
-
|
|
55
|
+
p.restoreFn(e);
|
|
56
56
|
} finally {
|
|
57
57
|
requestAnimationFrame(() => {
|
|
58
58
|
i.restorePending = !1;
|
|
@@ -77,14 +77,14 @@ const i = {
|
|
|
77
77
|
* 恢复弹窗
|
|
78
78
|
*/
|
|
79
79
|
restoreFn(e) {
|
|
80
|
-
const { modalId: t, getState: o, onRestore:
|
|
80
|
+
const { modalId: t, getState: o, onRestore: n } = e;
|
|
81
81
|
if (!o().isOpen) return;
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
84
|
-
|
|
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
|
-
|
|
87
|
+
n();
|
|
88
88
|
}
|
|
89
89
|
}, q = {
|
|
90
90
|
apiBase: "https://wx-auth.shenzjd.com",
|
|
@@ -109,7 +109,7 @@ let r = { ...q }, u = "", a = {
|
|
|
109
109
|
resolveAuth: null,
|
|
110
110
|
currentStep: "qr",
|
|
111
111
|
mpSession: null
|
|
112
|
-
}, h =
|
|
112
|
+
}, h = "code", f = 0;
|
|
113
113
|
function A(e) {
|
|
114
114
|
try {
|
|
115
115
|
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
@@ -129,50 +129,38 @@ const c = {
|
|
|
129
129
|
const o = `; ${document.cookie}`.split(`; ${e}=`);
|
|
130
130
|
return o.length === 2 && o.pop()?.split(";").shift() || null;
|
|
131
131
|
},
|
|
132
|
-
// 设置Cookie
|
|
132
|
+
// 设置Cookie(会话 Cookie,2026-08-30:不设 expires —— 浏览器关闭即失效,
|
|
133
|
+
// 下次打开需重新扫码登录;自动设置根域名实现跨子域共享)
|
|
133
134
|
setCookie(e, t) {
|
|
134
|
-
const o =
|
|
135
|
-
|
|
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`;
|
|
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`;
|
|
138
137
|
},
|
|
139
138
|
// 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
|
|
140
139
|
deleteCookie(e) {
|
|
141
|
-
const t = this.getRootDomain(), o = t ? `;domain=${t}` : "",
|
|
142
|
-
document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${
|
|
143
|
-
},
|
|
144
|
-
// ===== 签名 Token
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
},
|
|
153
|
-
// 读取: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 备份不再兜底)
|
|
154
151
|
getToken() {
|
|
155
|
-
|
|
156
|
-
if (e) return e;
|
|
157
|
-
try {
|
|
158
|
-
return window.localStorage.getItem(this.storageKey);
|
|
159
|
-
} catch {
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
152
|
+
return this.getCookie("wxauth-token");
|
|
162
153
|
},
|
|
163
|
-
//
|
|
154
|
+
// 写入:仅会话 Cookie
|
|
164
155
|
setToken(e) {
|
|
165
156
|
this.setCookie("wxauth-token", e);
|
|
166
|
-
try {
|
|
167
|
-
window.localStorage.setItem(this.storageKey, e);
|
|
168
|
-
} catch {
|
|
169
|
-
}
|
|
170
157
|
},
|
|
171
|
-
//
|
|
158
|
+
// 删除:清 Cookie + 防御性清理旧版本 localStorage 备份残留
|
|
159
|
+
// (同时清掉明文 openid Cookie —— 防御性清理,服务端已下线 openid 通道 2026-08-26)
|
|
172
160
|
clearToken() {
|
|
173
161
|
this.deleteCookie("wxauth-token"), this.deleteCookie("wxauth-openid");
|
|
174
162
|
try {
|
|
175
|
-
window.localStorage.removeItem(
|
|
163
|
+
window.localStorage.removeItem("wxauth-token");
|
|
176
164
|
} catch {
|
|
177
165
|
}
|
|
178
166
|
},
|
|
@@ -192,13 +180,13 @@ const c = {
|
|
|
192
180
|
credentials: "include"
|
|
193
181
|
});
|
|
194
182
|
if (!o.ok) {
|
|
195
|
-
const
|
|
196
|
-
throw
|
|
183
|
+
const n = new Error(`HTTP ${o.status}`);
|
|
184
|
+
throw n.status = o.status, n;
|
|
197
185
|
}
|
|
198
186
|
return await o.json();
|
|
199
187
|
} catch (o) {
|
|
200
|
-
const
|
|
201
|
-
throw
|
|
188
|
+
const n = o;
|
|
189
|
+
throw n.status === void 0 && (n.isNetworkError = !0), console.error("[WxAuth] Request error:", o), n;
|
|
202
190
|
}
|
|
203
191
|
},
|
|
204
192
|
// 生成6位验证码输入框HTML
|
|
@@ -209,26 +197,26 @@ const c = {
|
|
|
209
197
|
return e += "</div>", e;
|
|
210
198
|
}
|
|
211
199
|
}, b = [1e3, 3e3];
|
|
212
|
-
function
|
|
200
|
+
function v(e) {
|
|
213
201
|
const t = e;
|
|
214
202
|
return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
|
|
215
203
|
}
|
|
216
|
-
function
|
|
204
|
+
function x(e) {
|
|
217
205
|
return new Promise((t) => setTimeout(t, e));
|
|
218
206
|
}
|
|
219
|
-
const C = 2e3,
|
|
220
|
-
function
|
|
221
|
-
|
|
207
|
+
const C = 2e3, E = 3e3;
|
|
208
|
+
function k() {
|
|
209
|
+
f++;
|
|
222
210
|
}
|
|
223
211
|
async function S(e) {
|
|
224
|
-
for (; e ===
|
|
212
|
+
for (; e === f && a.isOpen; ) {
|
|
225
213
|
const t = a.mpSession;
|
|
226
214
|
if (!t || Date.now() >= t.expiresAt) break;
|
|
227
215
|
try {
|
|
228
216
|
const o = await c.request(
|
|
229
217
|
`${r.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
|
|
230
218
|
);
|
|
231
|
-
if (e !==
|
|
219
|
+
if (e !== f) return;
|
|
232
220
|
if (o.status === "confirmed" && o.token) {
|
|
233
221
|
w.completeLogin(o);
|
|
234
222
|
return;
|
|
@@ -238,36 +226,58 @@ async function S(e) {
|
|
|
238
226
|
break;
|
|
239
227
|
}
|
|
240
228
|
} catch (o) {
|
|
241
|
-
if (e !==
|
|
242
|
-
if (!
|
|
243
|
-
await
|
|
229
|
+
if (e !== f) return;
|
|
230
|
+
if (!v(o)) break;
|
|
231
|
+
await x(E);
|
|
244
232
|
continue;
|
|
245
233
|
}
|
|
246
|
-
await
|
|
234
|
+
await x(C);
|
|
247
235
|
}
|
|
248
|
-
e ===
|
|
236
|
+
e === f && a.isOpen && h === "mp" && l.showMpExpired();
|
|
249
237
|
}
|
|
250
|
-
async function
|
|
238
|
+
async function y(e) {
|
|
251
239
|
const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${r.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
|
|
252
|
-
for (let
|
|
240
|
+
for (let n = 0; ; n++)
|
|
253
241
|
try {
|
|
254
|
-
const
|
|
255
|
-
return
|
|
256
|
-
} catch (
|
|
257
|
-
if (!
|
|
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 (!v(s) || n >= b.length)
|
|
258
246
|
return { kind: "transient" };
|
|
259
|
-
await
|
|
247
|
+
await x(b[n]);
|
|
260
248
|
}
|
|
261
249
|
}
|
|
250
|
+
const I = 300 * 1e3;
|
|
251
|
+
let m = null;
|
|
252
|
+
function T() {
|
|
253
|
+
return !m || Date.now() >= m.expiresAt ? (m = null, null) : {
|
|
254
|
+
wechatName: m.wechatName,
|
|
255
|
+
qrcodeUrl: m.qrcodeUrl
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
async function M() {
|
|
259
|
+
const e = u ? `?siteId=${encodeURIComponent(u)}` : "", t = await c.request(
|
|
260
|
+
`${r.apiBase}/api/sdk/config${e}`
|
|
261
|
+
), o = {
|
|
262
|
+
wechatName: t.wechatName,
|
|
263
|
+
qrcodeUrl: t.qrcodeUrl
|
|
264
|
+
};
|
|
265
|
+
return m = { ...o, expiresAt: Date.now() + I }, o;
|
|
266
|
+
}
|
|
267
|
+
function $(e) {
|
|
268
|
+
e.wechatName && !r.wechatName && (r.wechatName = e.wechatName), e.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = e.qrcodeUrl);
|
|
269
|
+
}
|
|
262
270
|
const l = {
|
|
263
271
|
// 创建弹窗
|
|
272
|
+
// 形态固定为双 tab(2026-08-30 去掉 mpScanEnabled 门控):形态不依赖 config,
|
|
273
|
+
// 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab)结构上不存在
|
|
264
274
|
createModal() {
|
|
265
275
|
const e = document.createElement("div");
|
|
266
276
|
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 =
|
|
277
|
+
const t = r.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>', o = `<div class="wx-auth-tabs">
|
|
268
278
|
<button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
|
|
269
279
|
<button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
|
|
270
|
-
</div
|
|
280
|
+
</div>`, n = `<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
|
|
271
281
|
<div class="wx-auth-qrcode-container wx-auth-mp-container">
|
|
272
282
|
<div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
|
|
273
283
|
<img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
|
|
@@ -278,7 +288,7 @@ const l = {
|
|
|
278
288
|
</div>
|
|
279
289
|
<div class="wx-auth-desc wx-auth-mp-hint">微信扫描二维码,打开小程序确认登录</div>
|
|
280
290
|
<div class="wx-auth-mp-status"></div>
|
|
281
|
-
</div
|
|
291
|
+
</div>`;
|
|
282
292
|
return e.innerHTML = `
|
|
283
293
|
<div class="wx-auth-overlay" ${r.required ? 'onclick="event.preventDefault()"' : ""}></div>
|
|
284
294
|
<div class="wx-auth-content">
|
|
@@ -302,7 +312,6 @@ const l = {
|
|
|
302
312
|
<!-- 验证码输入区域 -->
|
|
303
313
|
<div>
|
|
304
314
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
305
|
-
<div class="wx-auth-note">保持关注,即可一直自动登录</div>
|
|
306
315
|
${c.generateCodeInputs()}
|
|
307
316
|
</div>
|
|
308
317
|
|
|
@@ -313,7 +322,7 @@ const l = {
|
|
|
313
322
|
</div>
|
|
314
323
|
|
|
315
324
|
<!-- 面板二:小程序扫码 -->
|
|
316
|
-
${
|
|
325
|
+
${n}
|
|
317
326
|
|
|
318
327
|
<!-- 消息提示 -->
|
|
319
328
|
<div class="wx-auth-message" style="display:none"></div>
|
|
@@ -326,18 +335,18 @@ const l = {
|
|
|
326
335
|
setTimeout(() => {
|
|
327
336
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
328
337
|
e.length && e.forEach((t, o) => {
|
|
329
|
-
t.addEventListener("input", (
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
}), t.addEventListener("keydown", (
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
}), t.addEventListener("paste", (
|
|
336
|
-
|
|
337
|
-
const
|
|
338
|
-
|
|
339
|
-
e[
|
|
340
|
-
}),
|
|
338
|
+
t.addEventListener("input", (n) => {
|
|
339
|
+
const s = n.target.value.replace(/\D/g, "");
|
|
340
|
+
n.target.value = s, s && o < 5 && e[o + 1].focus(), o === 5 && s && setTimeout(() => w.verifyCode(), 300);
|
|
341
|
+
}), t.addEventListener("keydown", (n) => {
|
|
342
|
+
const s = n.target;
|
|
343
|
+
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());
|
|
344
|
+
}), t.addEventListener("paste", (n) => {
|
|
345
|
+
n.preventDefault();
|
|
346
|
+
const s = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
347
|
+
s && (s.split("").forEach((d, g) => {
|
|
348
|
+
e[g] && (e[g].value = d);
|
|
349
|
+
}), s.length === 6 && setTimeout(() => w.verifyCode(), 300));
|
|
341
350
|
});
|
|
342
351
|
});
|
|
343
352
|
}, 100);
|
|
@@ -345,17 +354,17 @@ const l = {
|
|
|
345
354
|
// 显示弹窗
|
|
346
355
|
show() {
|
|
347
356
|
let e = document.getElementById("wx-auth-modal");
|
|
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((
|
|
357
|
+
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 = "");
|
|
349
358
|
const o = e.querySelector(".wx-auth-message");
|
|
350
359
|
o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
|
|
351
|
-
const
|
|
352
|
-
|
|
360
|
+
const n = e.querySelector(".wx-auth-btn-primary");
|
|
361
|
+
n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), k(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, p.enable({
|
|
353
362
|
modalId: "wx-auth-modal",
|
|
354
363
|
getState: () => a,
|
|
355
364
|
onRestore: () => {
|
|
356
365
|
this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
|
|
357
|
-
const
|
|
358
|
-
|
|
366
|
+
const s = document.querySelector(".wx-auth-wechat-name");
|
|
367
|
+
s && r.wechatName && (s.textContent = `"${r.wechatName}"`), this.bindInputEvents(), h === "mp" && w.switchMode("mp"), setTimeout(() => {
|
|
359
368
|
const d = document.querySelector(".wx-auth-input");
|
|
360
369
|
d && d.focus();
|
|
361
370
|
}, 100);
|
|
@@ -365,7 +374,7 @@ const l = {
|
|
|
365
374
|
// 隐藏弹窗
|
|
366
375
|
hide() {
|
|
367
376
|
const e = document.getElementById("wx-auth-modal");
|
|
368
|
-
e && (e.style.display = "none", a.isOpen = !1,
|
|
377
|
+
e && (e.style.display = "none", a.isOpen = !1, k(), a.mpSession = null, p.disable());
|
|
369
378
|
},
|
|
370
379
|
// 设置二维码
|
|
371
380
|
setQrCode(e) {
|
|
@@ -376,8 +385,8 @@ const l = {
|
|
|
376
385
|
// ===== 小程序扫码面板(2026-08-29)=====
|
|
377
386
|
// 展示小程序码(隐藏 loading 与过期遮罩,保持画面干净)
|
|
378
387
|
setMpQr(e) {
|
|
379
|
-
const t = document.getElementById("wx-auth-modal"), o = t?.querySelector(".wx-auth-mp-qrcode"),
|
|
380
|
-
o && (o.src = e, o.style.display = "block",
|
|
388
|
+
const t = document.getElementById("wx-auth-modal"), o = t?.querySelector(".wx-auth-mp-qrcode"), n = t?.querySelector(".wx-auth-mp-loading");
|
|
389
|
+
o && (o.src = e, o.style.display = "block", n && (n.style.display = "none"), this.setMpExpiredVisible(!1), this.setMpStatus("", !1));
|
|
381
390
|
},
|
|
382
391
|
// 过期遮罩显示/隐藏:盖在二维码上(「二维码已过期」+ 绿色刷新按钮)
|
|
383
392
|
setMpExpiredVisible(e) {
|
|
@@ -386,10 +395,10 @@ const l = {
|
|
|
386
395
|
},
|
|
387
396
|
// 更新扫码面板状态文案;text 为空 = 隐藏状态行;spinner=true 时回列出码 loading
|
|
388
397
|
setMpStatus(e, t) {
|
|
389
|
-
const o = document.getElementById("wx-auth-modal"),
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
if (
|
|
398
|
+
const o = document.getElementById("wx-auth-modal"), n = o?.querySelector(".wx-auth-mp-status");
|
|
399
|
+
n && (n.textContent = e, n.style.display = e ? "block" : "none");
|
|
400
|
+
const s = o?.querySelector(".wx-auth-mp-loading");
|
|
401
|
+
if (s && (s.style.display = t ? "flex" : "none"), t) {
|
|
393
402
|
const d = o?.querySelector(".wx-auth-mp-qrcode");
|
|
394
403
|
d && (d.style.display = "none");
|
|
395
404
|
}
|
|
@@ -418,7 +427,7 @@ const l = {
|
|
|
418
427
|
}, w = {
|
|
419
428
|
// 初始化
|
|
420
429
|
init(e = {}) {
|
|
421
|
-
if (r = { ...q, ...e }, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
|
|
430
|
+
if (r = { ...q, ...e }, m = null, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
|
|
422
431
|
console.error("[WxAuth] apiBase is required");
|
|
423
432
|
return;
|
|
424
433
|
}
|
|
@@ -445,7 +454,7 @@ const l = {
|
|
|
445
454
|
async silentCheck() {
|
|
446
455
|
const e = c.getToken();
|
|
447
456
|
if (!e) return !1;
|
|
448
|
-
const t = await
|
|
457
|
+
const t = await y(e);
|
|
449
458
|
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);
|
|
450
459
|
},
|
|
451
460
|
// 自动检测凭证并验证(内部使用)
|
|
@@ -453,7 +462,7 @@ const l = {
|
|
|
453
462
|
const e = c.getToken();
|
|
454
463
|
if (!e)
|
|
455
464
|
return this.showAuthModal(), !1;
|
|
456
|
-
const t = await
|
|
465
|
+
const t = await y(e);
|
|
457
466
|
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
467
|
code: "server_error",
|
|
459
468
|
retryable: !0,
|
|
@@ -461,46 +470,40 @@ const l = {
|
|
|
461
470
|
}), !1) : (this.showAuthModal(), !1);
|
|
462
471
|
},
|
|
463
472
|
// 显示认证弹窗(内部使用)
|
|
473
|
+
// 2026-08-30 修复「弹窗闪两次」:形态固定双 tab(去掉 mpScanEnabled 门控),
|
|
474
|
+
// UI.show() 同步渲染 + 默认小程序扫码立即出码,全程只有一种形态,无中间态;
|
|
475
|
+
// /api/sdk/config(公众号名称/码图)改为后台拉取,不再阻塞渲染。
|
|
464
476
|
async showAuthModal() {
|
|
465
|
-
l.show();
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
t && t.focus();
|
|
477
|
+
l.show(), this.switchMode("mp");
|
|
478
|
+
let e = T();
|
|
479
|
+
if (!e)
|
|
480
|
+
try {
|
|
481
|
+
e = await M();
|
|
482
|
+
} catch (o) {
|
|
483
|
+
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", o);
|
|
484
|
+
}
|
|
485
|
+
e && $(e), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
|
|
486
|
+
const t = document.querySelector(".wx-auth-wechat-name");
|
|
487
|
+
t && r.wechatName && (t.textContent = `"${r.wechatName}"`), setTimeout(() => {
|
|
488
|
+
const o = document.querySelector(".wx-auth-input");
|
|
489
|
+
o && o.focus();
|
|
479
490
|
}, 100);
|
|
480
491
|
},
|
|
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
492
|
// 切换登录方式(tab 点击 / 默认模式设定)
|
|
490
493
|
switchMode(e) {
|
|
491
|
-
|
|
494
|
+
h = e;
|
|
492
495
|
const t = document.getElementById("wx-auth-modal");
|
|
493
496
|
if (!t) return;
|
|
494
|
-
t.querySelectorAll(".wx-auth-tab").forEach((
|
|
495
|
-
|
|
497
|
+
t.querySelectorAll(".wx-auth-tab").forEach((s) => {
|
|
498
|
+
s.classList.toggle("wx-auth-tab-active", s.dataset.mode === h);
|
|
496
499
|
});
|
|
497
|
-
const o = t.querySelector(".wx-auth-panel-code"),
|
|
498
|
-
o && (o.style.display =
|
|
500
|
+
const o = t.querySelector(".wx-auth-panel-code"), n = t.querySelector(".wx-auth-panel-mp");
|
|
501
|
+
o && (o.style.display = h === "code" ? "" : "none"), n && (n.style.display = h === "mp" ? "" : "none"), h === "mp" ? this.startMpLogin() : k();
|
|
499
502
|
},
|
|
500
503
|
// 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
|
|
501
504
|
async startMpLogin() {
|
|
502
|
-
if (!
|
|
503
|
-
const e = ++
|
|
505
|
+
if (!a.isOpen) return;
|
|
506
|
+
const e = ++f;
|
|
504
507
|
if (l.setMpExpiredVisible(!1), l.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
|
|
505
508
|
l.setMpQr(a.mpSession.qrDataUrl), S(e);
|
|
506
509
|
return;
|
|
@@ -510,7 +513,7 @@ const l = {
|
|
|
510
513
|
method: "POST",
|
|
511
514
|
body: { siteId: u }
|
|
512
515
|
});
|
|
513
|
-
if (e !==
|
|
516
|
+
if (e !== f || !a.isOpen) return;
|
|
514
517
|
if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
|
|
515
518
|
a.mpSession = {
|
|
516
519
|
ticket: String(t.ticket),
|
|
@@ -518,16 +521,16 @@ const l = {
|
|
|
518
521
|
expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
|
|
519
522
|
}, l.setMpQr(a.mpSession.qrDataUrl), S(e);
|
|
520
523
|
} catch (t) {
|
|
521
|
-
if (e !==
|
|
524
|
+
if (e !== f || !a.isOpen) return;
|
|
522
525
|
console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"), l.showMessage("小程序扫码暂不可用,请使用公众号验证码登录", "error");
|
|
523
526
|
}
|
|
524
527
|
},
|
|
525
528
|
// 主入口:需要验证时调用
|
|
526
|
-
// 凭证仅签名 Token
|
|
529
|
+
// 凭证仅签名 Token(会话 Cookie),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
|
|
527
530
|
async requireAuth() {
|
|
528
531
|
const e = c.getToken();
|
|
529
532
|
if (e) {
|
|
530
|
-
const t = await
|
|
533
|
+
const t = await y(e);
|
|
531
534
|
if (t.kind === "ok")
|
|
532
535
|
return console.log("[WxAuth] 已认证(凭证)"), t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0;
|
|
533
536
|
if (t.kind === "transient")
|
|
@@ -546,7 +549,7 @@ const l = {
|
|
|
546
549
|
// 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
|
|
547
550
|
// close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
|
|
548
551
|
completeLogin(e) {
|
|
549
|
-
if (e?.token && c.setToken(e.token), h
|
|
552
|
+
if (e?.token && c.setToken(e.token), h === "mp")
|
|
550
553
|
l.setMpStatus("✅ 登录成功", !1);
|
|
551
554
|
else {
|
|
552
555
|
const t = document.querySelector(".wx-auth-btn-primary");
|
|
@@ -568,16 +571,16 @@ const l = {
|
|
|
568
571
|
);
|
|
569
572
|
t && (t.disabled = !0, t.textContent = "登录中...");
|
|
570
573
|
try {
|
|
571
|
-
const o = u ? `&siteId=${encodeURIComponent(u)}` : "",
|
|
574
|
+
const o = u ? `&siteId=${encodeURIComponent(u)}` : "", n = await c.request(
|
|
572
575
|
`${r.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
573
576
|
);
|
|
574
|
-
|
|
575
|
-
|
|
577
|
+
n.authenticated ? this.completeLogin(n) : (l.showMessage(
|
|
578
|
+
n.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
|
|
576
579
|
"error"
|
|
577
580
|
), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
|
|
578
581
|
} catch (o) {
|
|
579
582
|
l.showMessage(
|
|
580
|
-
|
|
583
|
+
v(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
|
|
581
584
|
"error"
|
|
582
585
|
), t && (t.disabled = !1, t.textContent = "登录");
|
|
583
586
|
}
|
|
@@ -588,17 +591,14 @@ const l = {
|
|
|
588
591
|
close(e = !1) {
|
|
589
592
|
l.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
|
|
590
593
|
},
|
|
591
|
-
//
|
|
594
|
+
// 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
|
|
592
595
|
// 用于"退出登录 / 清空认证状态"按钮。
|
|
593
|
-
// 注意:signedToken 双存储备份(localStorage)若不清,清 Cookie 后
|
|
594
|
-
// SDK 会凭备份静默恢复(getToken 优先 Cookie、localStorage 兜底),
|
|
595
|
-
// 造成"清不掉"的假象——所以必须走这里而非只删 Cookie。
|
|
596
596
|
clearToken() {
|
|
597
597
|
c.clearToken();
|
|
598
598
|
},
|
|
599
599
|
// 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
|
|
600
600
|
// 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
|
|
601
|
-
//
|
|
601
|
+
// 吊销黑名单。此后该 token 在任何设备/子域都无法再通过服务端校验
|
|
602
602
|
// (根治「A 域退出、B 域还能用」的双写恢复问题)。
|
|
603
603
|
// 幂等安全:网络失败 /* 后端不可达 */ 时静默降级为仅本地清理(clearToken),
|
|
604
604
|
// 不阻塞退出流程;token 无效也会返回 success(本地照常清理)。
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
(function(w,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(w=typeof globalThis<"u"?globalThis:w||self,m(w.WxAuthSDK={}))})(this,(function(w){"use strict";var m=document.createElement("style");m.textContent=`.wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:30px;padding:0;opacity:.85;flex-shrink:0}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:4px;font-weight:500}.wx-auth-note{font-size:12px;color:#888;margin-bottom:14px;line-height:1.4;white-space:nowrap}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-tabs{display:flex;gap:8px;margin-bottom:16px}.wx-auth-tab{flex:1;padding:8px 0;font-size:13px;border:1px solid #DCDCDC;background:#f7f7f7;color:#666;border-radius:6px;cursor:pointer;transition:all .2s}.wx-auth-tab:active{transform:scale(.98)}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff;font-weight:600}.wx-auth-mp-loading{height:100%;display:flex;align-items:center;justify-content:center}.wx-auth-spinner{width:28px;height:28px;border:3px solid #e5e5e5;border-top-color:#07c160;border-radius:50%;animation:wxAuthSpin 1s linear infinite}@keyframes wxAuthSpin{to{transform:rotate(360deg)}}.wx-auth-mp-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-mp-container{position:relative}.wx-auth-mp-expired{position:absolute;inset:0;z-index:1;display:none;flex-direction:column;align-items:center;justify-content:center;gap:10px;background:#ffffffeb}.wx-auth-mp-expired-text{font-size:13px;color:#666}.wx-auth-mp-expired .wx-auth-mp-refresh{flex:none;width:auto;margin:0;padding:8px 18px;font-size:13px}.wx-auth-mp-status{font-size:13px;color:#666;margin:4px 0 12px;min-height:18px;line-height:1.4}.wx-auth-mp-hint{margin:12px 0 4px}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}.wx-auth-note{color:#aaa}.wx-auth-input{background:#2a2a2a;border-color:#444;color:#e5e5e5}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16040}.wx-auth-input:disabled{background:#333;color:#888}.wx-auth-qrcode-container{background:#2a2a2a}.wx-auth-tab{background:#2a2a2a;border-color:#444;color:#aaa}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff}.wx-auth-spinner{border-color:#444;border-top-color:#07c160}.wx-auth-mp-status{color:#aaa}.wx-auth-mp-expired{background:#1a1a1aeb}.wx-auth-mp-expired-text{color:#aaa}.wx-auth-btn-secondary{background:#2a2a2a;color:#e5e5e5}.wx-auth-btn-secondary:hover:not(:disabled){background:#333}.wx-auth-message-info{background:#0d2a1f;color:#7cc4ff;border-color:#1f4a6b}.wx-auth-message-success{background:#0d2a1a;color:#4ade80;border-color:#1f6b3a}.wx-auth-message-error{background:#2a0d0d;color:#f87171;border-color:#6b1f1f}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},
|
|
2
|
+
/*$vite$:1*/`,document.head.appendChild(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={enable(e){if(i.isProtected||typeof window>"u")return;i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!0,i.restorePending=!1,i.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const d=r;if(d.id===e.modalId||d.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),f.safeRestore(e);return}}}),i.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!i.isProtected)return;const{getState:o}=e;if(!o().isOpen){i.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||f.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?f.isHidden(n):null}),f.safeRestore(e)),i.isProtected&&(i.rafId=requestAnimationFrame(t))};i.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!1,i.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!i.restorePending){i.restorePending=!0;try{f.restoreFn(e)}finally{requestAnimationFrame(()=>{i.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},S={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...S},l="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},h="code",p=0;function I(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 I(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 y(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 E=2e3,T=3e3;function k(){p++}async function C(e){for(;e===p&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==p)return;if(o.status==="confirmed"&&o.token){g.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==p)return;if(!y(o))break;await b(T);continue}await b(E)}e===p&&s.isOpen&&h==="mp"&&u.showMpExpired()}async function v(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await c.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!y(r)||n>=q.length)return{kind:"transient"};await b(q[n])}}const M=300*1e3;let x=null;function $(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function D(){const e=l?`?siteId=${encodeURIComponent(l)}`:"",t=await c.request(`${a.apiBase}/api/sdk/config${e}`),o={wechatName:t.wechatName,qrcodeUrl:t.qrcodeUrl};return x={...o,expiresAt:Date.now()+M},o}function N(e){e.wechatName&&!a.wechatName&&(a.wechatName=e.wechatName),e.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=e.qrcodeUrl)}const u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>',o=`<div class="wx-auth-tabs">
|
|
3
3
|
<button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
|
|
4
4
|
<button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
|
|
5
|
-
</div
|
|
5
|
+
</div>`,n=`<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
|
|
6
6
|
<div class="wx-auth-qrcode-container wx-auth-mp-container">
|
|
7
7
|
<div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
|
|
8
8
|
<img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
</div>
|
|
14
14
|
<div class="wx-auth-desc wx-auth-mp-hint">微信扫描二维码,打开小程序确认登录</div>
|
|
15
15
|
<div class="wx-auth-mp-status"></div>
|
|
16
|
-
</div
|
|
16
|
+
</div>`;return e.innerHTML=`
|
|
17
17
|
<div class="wx-auth-overlay" ${a.required?'onclick="event.preventDefault()"':""}></div>
|
|
18
18
|
<div class="wx-auth-content">
|
|
19
19
|
<div class="wx-auth-header">
|
|
@@ -36,8 +36,7 @@
|
|
|
36
36
|
<!-- 验证码输入区域 -->
|
|
37
37
|
<div>
|
|
38
38
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
39
|
-
|
|
40
|
-
${u.generateCodeInputs()}
|
|
39
|
+
${c.generateCodeInputs()}
|
|
41
40
|
</div>
|
|
42
41
|
|
|
43
42
|
<!-- 按钮 -->
|
|
@@ -53,4 +52,4 @@
|
|
|
53
52
|
<div class="wx-auth-message" style="display:none"></div>
|
|
54
53
|
</div>
|
|
55
54
|
</div>
|
|
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(()=>
|
|
55
|
+
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>g.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;n.key==="Backspace"&&!r.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((d,A)=>{e[A]&&(e[A].value=d)}),r.length===6&&setTimeout(()=>g.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(r=>r.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),k(),s.mpSession=null,e.style.display="flex",s.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&a.wechatName&&(r.textContent=`"${a.wechatName}"`),this.bindInputEvents(),h==="mp"&&g.switchMode("mp"),setTimeout(()=>{const d=document.querySelector(".wx-auth-input");d&&d.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",s.isOpen=!1,k(),s.mpSession=null,f.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},setMpQr(e){const t=document.getElementById("wx-auth-modal"),o=t?.querySelector(".wx-auth-mp-qrcode"),n=t?.querySelector(".wx-auth-mp-loading");o&&(o.src=e,o.style.display="block",n&&(n.style.display="none"),this.setMpExpiredVisible(!1),this.setMpStatus("",!1))},setMpExpiredVisible(e){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");o&&(o.style.display=e?"flex":"none")},setMpStatus(e,t){const o=document.getElementById("wx-auth-modal"),n=o?.querySelector(".wx-auth-mp-status");n&&(n.textContent=e,n.style.display=e?"block":"none");const r=o?.querySelector(".wx-auth-mp-loading");if(r&&(r.style.display=t?"flex":"none"),t){const d=o?.querySelector(".wx-auth-mp-qrcode");d&&(d.style.display="none")}},showMpExpired(){this.setMpExpiredVisible(!0)},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},g={init(e={}){if(a={...S,...e},x=null,!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{l=new URL(t).hostname}catch{}!l&&window.location.hostname&&(l=window.location.hostname),l||(l="default"),console.log("[WxAuth] 自动获取 siteId:",l)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await v(e);return t.kind==="ok"?(t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=await v(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(){u.show(),this.switchMode("mp");let e=$();if(!e)try{e=await D()}catch(o){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",o)}e&&N(e),a.qrcodeUrl&&u.setQrCode(a.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&a.wechatName&&(t.textContent=`"${a.wechatName}"`),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)},switchMode(e){h=e;const t=document.getElementById("wx-auth-modal");if(!t)return;t.querySelectorAll(".wx-auth-tab").forEach(r=>{r.classList.toggle("wx-auth-tab-active",r.dataset.mode===h)});const o=t.querySelector(".wx-auth-panel-code"),n=t.querySelector(".wx-auth-panel-mp");o&&(o.style.display=h==="code"?"":"none"),n&&(n.style.display=h==="mp"?"":"none"),h==="mp"?this.startMpLogin():k()},async startMpLogin(){if(!s.isOpen)return;const e=++p;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){u.setMpQr(s.mpSession.qrDataUrl),C(e);return}try{const t=await c.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:l}});if(e!==p||!s.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");s.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(s.mpSession.qrDataUrl),C(e)}catch(t){if(e!==p||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码",t),this.switchMode("code"),u.showMessage("小程序扫码暂不可用,请使用公众号验证码登录","error")}},async requireAuth(){const e=c.getToken();if(e){const t=await v(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{s.resolveAuth=t})},completeLogin(e){if(e?.token&&c.setToken(e.token),h==="mp")u.setMpStatus("✅ 登录成功",!1);else{const t=document.querySelector(".wx-auth-btn-primary");t&&(t.textContent="✅ 已登录",t.style.background="#07C160")}setTimeout(()=>{this.onVerified(e?.user),this.close(!0)},500)},async verifyCode(){const e=u.getVerifyCode();if(!e||e.length!==6){u.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=l?`&siteId=${encodeURIComponent(l)}`:"",n=await c.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?this.completeLogin(n):(u.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(y(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof a.onVerified=="function"&&a.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(g)),w.WxAuth=g,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
|