wx-auth-sdk 1.2.35 → 1.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/wx-auth.js +61 -51
- package/dist/wx-auth.umd.js +2 -2
- package/package.json +1 -1
package/dist/wx-auth.js
CHANGED
|
@@ -104,13 +104,13 @@ const i = {
|
|
|
104
104
|
silent: !1
|
|
105
105
|
// 默认不静默
|
|
106
106
|
};
|
|
107
|
-
let r = { ...q },
|
|
107
|
+
let r = { ...q }, c = "", a = {
|
|
108
108
|
isOpen: !1,
|
|
109
109
|
resolveAuth: null,
|
|
110
110
|
currentStep: "qr",
|
|
111
111
|
mpSession: null
|
|
112
112
|
}, f = "code", h = 0;
|
|
113
|
-
function
|
|
113
|
+
function E(e) {
|
|
114
114
|
try {
|
|
115
115
|
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
116
116
|
return "";
|
|
@@ -120,25 +120,35 @@ function C(e) {
|
|
|
120
120
|
return "";
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
-
const
|
|
123
|
+
const u = {
|
|
124
124
|
getRootDomain() {
|
|
125
|
-
return
|
|
125
|
+
return E(window.location.hostname);
|
|
126
126
|
},
|
|
127
127
|
// 获取Cookie
|
|
128
128
|
getCookie(e) {
|
|
129
129
|
const o = `; ${document.cookie}`.split(`; ${e}=`);
|
|
130
130
|
return o.length === 2 && o.pop()?.split(";").shift() || null;
|
|
131
131
|
},
|
|
132
|
+
// Cookie 写入底层(domainStr 传空串 = host-only,落在当前 host 本域)
|
|
133
|
+
writeCookieRaw(e, t, o, n, s = !1) {
|
|
134
|
+
const d = n ? `;domain=${n}` : "", C = window.location.protocol === "https:" ? ";Secure" : "", A = s ? ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : o !== void 0 ? `;expires=${new Date(Date.now() + o).toUTCString()}` : "";
|
|
135
|
+
document.cookie = `${e}=${s ? "" : t};path=/${d}${A}${C};SameSite=Strict`;
|
|
136
|
+
},
|
|
132
137
|
// 设置Cookie(2026-09-04:不传 maxAgeMs 时仍是会话 Cookie —— 浏览器关闭即失效;
|
|
133
138
|
// 传入 maxAgeMs 则写持久 Cookie;自动设置根域名实现跨子域共享)
|
|
139
|
+
// 2026-09-06:根域写入后回读校验——公共后缀域名(vercel.app / netlify.app /
|
|
140
|
+
// pages.dev 等共享托管域,均在 Public Suffix List)禁止写 domain Cookie,
|
|
141
|
+
// 浏览器会静默丢弃导致登录态存不下来;此时降级为 host-only(落当前 host 本域)
|
|
134
142
|
setCookie(e, t, o) {
|
|
135
|
-
const n = this.getRootDomain()
|
|
136
|
-
|
|
143
|
+
const n = this.getRootDomain();
|
|
144
|
+
this.writeCookieRaw(e, t, o, n), n && !this.getCookie(e) && this.writeCookieRaw(e, t, o, "");
|
|
137
145
|
},
|
|
138
146
|
// 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
|
|
147
|
+
// 2026-09-06:公共后缀域名降级场景下 cookie 可能是 host-only 写入的,
|
|
148
|
+
// 根域 + 本域各删一次,保证两种存储形态都能清干净
|
|
139
149
|
deleteCookie(e) {
|
|
140
|
-
const t = this.getRootDomain()
|
|
141
|
-
|
|
150
|
+
const t = this.getRootDomain();
|
|
151
|
+
this.writeCookieRaw(e, "", void 0, t, !0), t && this.writeCookieRaw(e, "", void 0, "", !0);
|
|
142
152
|
},
|
|
143
153
|
// ===== 签名 Token 存储(会话 Cookie,2026-09-05 恢复)=====
|
|
144
154
|
// 登录态策略:web 登录态为会话级——不设 expires,浏览器进程关闭即失效,
|
|
@@ -204,20 +214,20 @@ function g(e) {
|
|
|
204
214
|
const t = e;
|
|
205
215
|
return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
|
|
206
216
|
}
|
|
207
|
-
function
|
|
217
|
+
function y(e) {
|
|
208
218
|
return new Promise((t) => setTimeout(t, e));
|
|
209
219
|
}
|
|
210
|
-
const
|
|
211
|
-
function
|
|
220
|
+
const T = 3e3, I = 2e3, M = 3e3;
|
|
221
|
+
function v() {
|
|
212
222
|
h++;
|
|
213
223
|
}
|
|
214
224
|
async function S(e) {
|
|
215
|
-
if (await
|
|
225
|
+
if (await y(T), !(e !== h || !a.isOpen)) {
|
|
216
226
|
for (; e === h && a.isOpen; ) {
|
|
217
227
|
const t = a.mpSession;
|
|
218
228
|
if (!t || Date.now() >= t.expiresAt) break;
|
|
219
229
|
try {
|
|
220
|
-
const o = await
|
|
230
|
+
const o = await u.request(
|
|
221
231
|
`${r.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
|
|
222
232
|
);
|
|
223
233
|
if (e !== h) return;
|
|
@@ -232,44 +242,44 @@ async function S(e) {
|
|
|
232
242
|
} catch (o) {
|
|
233
243
|
if (e !== h) return;
|
|
234
244
|
if (!g(o)) break;
|
|
235
|
-
await
|
|
245
|
+
await y(M);
|
|
236
246
|
continue;
|
|
237
247
|
}
|
|
238
|
-
await
|
|
248
|
+
await y(I);
|
|
239
249
|
}
|
|
240
250
|
e === h && a.isOpen && f === "mp" && l.showMpExpired();
|
|
241
251
|
}
|
|
242
252
|
}
|
|
243
|
-
async function
|
|
244
|
-
const t =
|
|
253
|
+
async function k(e) {
|
|
254
|
+
const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `${r.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
|
|
245
255
|
for (let n = 0; ; n++)
|
|
246
256
|
try {
|
|
247
|
-
const s = await
|
|
257
|
+
const s = await u.request(o);
|
|
248
258
|
return s.authenticated ? { kind: "ok", result: s } : s.error === "rate_limited" || s.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: s };
|
|
249
259
|
} catch (s) {
|
|
250
260
|
if (!g(s) || n >= b.length)
|
|
251
261
|
return { kind: "transient" };
|
|
252
|
-
await
|
|
262
|
+
await y(b[n]);
|
|
253
263
|
}
|
|
254
264
|
}
|
|
255
|
-
const
|
|
265
|
+
const $ = 300 * 1e3;
|
|
256
266
|
let m = null;
|
|
257
|
-
function
|
|
267
|
+
function L() {
|
|
258
268
|
return !m || Date.now() >= m.expiresAt ? (m = null, null) : {
|
|
259
269
|
wechatName: m.wechatName,
|
|
260
270
|
qrcodeUrl: m.qrcodeUrl
|
|
261
271
|
};
|
|
262
272
|
}
|
|
263
|
-
async function
|
|
264
|
-
const e =
|
|
273
|
+
async function N() {
|
|
274
|
+
const e = c ? `?siteId=${encodeURIComponent(c)}` : "", t = await u.request(
|
|
265
275
|
`${r.apiBase}/api/sdk/config${e}`
|
|
266
276
|
), o = {
|
|
267
277
|
wechatName: t.wechatName,
|
|
268
278
|
qrcodeUrl: t.qrcodeUrl
|
|
269
279
|
};
|
|
270
|
-
return m = { ...o, expiresAt: Date.now() +
|
|
280
|
+
return m = { ...o, expiresAt: Date.now() + $ }, o;
|
|
271
281
|
}
|
|
272
|
-
function
|
|
282
|
+
function P(e) {
|
|
273
283
|
e.wechatName && !r.wechatName && (r.wechatName = e.wechatName), e.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = e.qrcodeUrl);
|
|
274
284
|
}
|
|
275
285
|
const l = {
|
|
@@ -317,7 +327,7 @@ const l = {
|
|
|
317
327
|
<!-- 验证码输入区域 -->
|
|
318
328
|
<div>
|
|
319
329
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
320
|
-
${
|
|
330
|
+
${u.generateCodeInputs()}
|
|
321
331
|
</div>
|
|
322
332
|
|
|
323
333
|
<!-- 按钮 -->
|
|
@@ -349,8 +359,8 @@ const l = {
|
|
|
349
359
|
}), t.addEventListener("paste", (n) => {
|
|
350
360
|
n.preventDefault();
|
|
351
361
|
const s = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
352
|
-
s && (s.split("").forEach((d,
|
|
353
|
-
e[
|
|
362
|
+
s && (s.split("").forEach((d, x) => {
|
|
363
|
+
e[x] && (e[x].value = d);
|
|
354
364
|
}), s.length === 6 && setTimeout(() => w.verifyCode(), 300));
|
|
355
365
|
});
|
|
356
366
|
});
|
|
@@ -363,7 +373,7 @@ const l = {
|
|
|
363
373
|
const o = e.querySelector(".wx-auth-message");
|
|
364
374
|
o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
|
|
365
375
|
const n = e.querySelector(".wx-auth-btn-primary");
|
|
366
|
-
n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""),
|
|
376
|
+
n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), v(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, p.enable({
|
|
367
377
|
modalId: "wx-auth-modal",
|
|
368
378
|
getState: () => a,
|
|
369
379
|
onRestore: () => {
|
|
@@ -379,7 +389,7 @@ const l = {
|
|
|
379
389
|
// 隐藏弹窗
|
|
380
390
|
hide() {
|
|
381
391
|
const e = document.getElementById("wx-auth-modal");
|
|
382
|
-
e && (e.style.display = "none", a.isOpen = !1,
|
|
392
|
+
e && (e.style.display = "none", a.isOpen = !1, v(), a.mpSession = null, p.disable());
|
|
383
393
|
},
|
|
384
394
|
// 设置二维码
|
|
385
395
|
setQrCode(e) {
|
|
@@ -440,10 +450,10 @@ const l = {
|
|
|
440
450
|
const t = document.referrer;
|
|
441
451
|
if (t)
|
|
442
452
|
try {
|
|
443
|
-
|
|
453
|
+
c = new URL(t).hostname;
|
|
444
454
|
} catch {
|
|
445
455
|
}
|
|
446
|
-
!
|
|
456
|
+
!c && window.location.hostname && (c = window.location.hostname), c || (c = "default"), console.log("[WxAuth] 自动获取 siteId:", c);
|
|
447
457
|
}
|
|
448
458
|
console.log("[WxAuth] SDK initialized", r), typeof window < "u" && (r.silent ? this.silentCheck() : this.autoCheck());
|
|
449
459
|
},
|
|
@@ -457,18 +467,18 @@ const l = {
|
|
|
457
467
|
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
458
468
|
*/
|
|
459
469
|
async silentCheck() {
|
|
460
|
-
const e =
|
|
470
|
+
const e = u.getToken();
|
|
461
471
|
if (!e) return !1;
|
|
462
|
-
const t = await
|
|
463
|
-
return t.kind === "ok" ? (t.result.token &&
|
|
472
|
+
const t = await k(e);
|
|
473
|
+
return t.kind === "ok" ? (t.result.token && u.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
|
|
464
474
|
},
|
|
465
475
|
// 自动检测凭证并验证(内部使用)
|
|
466
476
|
async autoCheck() {
|
|
467
|
-
const e =
|
|
477
|
+
const e = u.getToken();
|
|
468
478
|
if (!e)
|
|
469
479
|
return this.showAuthModal(), !1;
|
|
470
|
-
const t = await
|
|
471
|
-
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token &&
|
|
480
|
+
const t = await k(e);
|
|
481
|
+
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && u.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
|
|
472
482
|
code: "server_error",
|
|
473
483
|
retryable: !0,
|
|
474
484
|
message: "登录服务暂时不可用,请稍后重试"
|
|
@@ -480,14 +490,14 @@ const l = {
|
|
|
480
490
|
// /api/sdk/config(公众号名称/码图)改为后台拉取,不再阻塞渲染。
|
|
481
491
|
async showAuthModal() {
|
|
482
492
|
l.show(), this.switchMode("mp");
|
|
483
|
-
let e =
|
|
493
|
+
let e = L();
|
|
484
494
|
if (!e)
|
|
485
495
|
try {
|
|
486
|
-
e = await
|
|
496
|
+
e = await N();
|
|
487
497
|
} catch (o) {
|
|
488
498
|
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", o);
|
|
489
499
|
}
|
|
490
|
-
e &&
|
|
500
|
+
e && P(e), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
|
|
491
501
|
const t = document.querySelector(".wx-auth-wechat-name");
|
|
492
502
|
t && r.wechatName && (t.textContent = `"${r.wechatName}"`), setTimeout(() => {
|
|
493
503
|
const o = document.querySelector(".wx-auth-input");
|
|
@@ -503,7 +513,7 @@ const l = {
|
|
|
503
513
|
s.classList.toggle("wx-auth-tab-active", s.dataset.mode === f);
|
|
504
514
|
});
|
|
505
515
|
const o = t.querySelector(".wx-auth-panel-code"), n = t.querySelector(".wx-auth-panel-mp");
|
|
506
|
-
o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() :
|
|
516
|
+
o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : v();
|
|
507
517
|
},
|
|
508
518
|
// 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
|
|
509
519
|
async startMpLogin() {
|
|
@@ -514,9 +524,9 @@ const l = {
|
|
|
514
524
|
return;
|
|
515
525
|
}
|
|
516
526
|
try {
|
|
517
|
-
const t = await
|
|
527
|
+
const t = await u.request(`${r.apiBase}/api/auth/mp-scan/create`, {
|
|
518
528
|
method: "POST",
|
|
519
|
-
body: { siteId:
|
|
529
|
+
body: { siteId: c }
|
|
520
530
|
});
|
|
521
531
|
if (e !== h || !a.isOpen) return;
|
|
522
532
|
if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
|
|
@@ -534,11 +544,11 @@ const l = {
|
|
|
534
544
|
// 凭证仅签名 Token(登录 Cookie,会话级,2026-09-05),不再兼容明文 openid
|
|
535
545
|
// (2026-08-26 服务端已下线 openid 通道)
|
|
536
546
|
async requireAuth() {
|
|
537
|
-
const e =
|
|
547
|
+
const e = u.getToken();
|
|
538
548
|
if (e) {
|
|
539
|
-
const t = await
|
|
549
|
+
const t = await k(e);
|
|
540
550
|
if (t.kind === "ok")
|
|
541
|
-
return console.log("[WxAuth] 已认证(凭证)"), t.result.token &&
|
|
551
|
+
return console.log("[WxAuth] 已认证(凭证)"), t.result.token && u.setToken(t.result.token), this.onVerified(t.result.user), !0;
|
|
542
552
|
if (t.kind === "transient")
|
|
543
553
|
return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
|
|
544
554
|
code: "server_error",
|
|
@@ -555,7 +565,7 @@ const l = {
|
|
|
555
565
|
// 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
|
|
556
566
|
// close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
|
|
557
567
|
completeLogin(e) {
|
|
558
|
-
if (e?.token &&
|
|
568
|
+
if (e?.token && u.setToken(e.token), f === "mp")
|
|
559
569
|
l.setMpStatus("✅ 登录成功", !1);
|
|
560
570
|
else {
|
|
561
571
|
const t = document.querySelector(".wx-auth-btn-primary");
|
|
@@ -577,7 +587,7 @@ const l = {
|
|
|
577
587
|
);
|
|
578
588
|
t && (t.disabled = !0, t.textContent = "登录中...");
|
|
579
589
|
try {
|
|
580
|
-
const o =
|
|
590
|
+
const o = c ? `&siteId=${encodeURIComponent(c)}` : "", n = await u.request(
|
|
581
591
|
`${r.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
582
592
|
);
|
|
583
593
|
n.authenticated ? this.completeLogin(n) : (l.showMessage(
|
|
@@ -600,7 +610,7 @@ const l = {
|
|
|
600
610
|
// 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
|
|
601
611
|
// 用于"退出登录 / 清空认证状态"按钮。
|
|
602
612
|
clearToken() {
|
|
603
|
-
|
|
613
|
+
u.clearToken();
|
|
604
614
|
},
|
|
605
615
|
// 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
|
|
606
616
|
// 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
|
|
@@ -611,7 +621,7 @@ const l = {
|
|
|
611
621
|
// 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
|
|
612
622
|
// 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
|
|
613
623
|
async revoke() {
|
|
614
|
-
const e =
|
|
624
|
+
const e = u.getToken();
|
|
615
625
|
if (e)
|
|
616
626
|
try {
|
|
617
627
|
const t = r.apiBase && !/\/$/.test(r.apiBase) ? r.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function(w,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(w=typeof globalThis<"u"?globalThis:w||self,m(w.WxAuthSDK={}))})(this,(function(w){"use strict";var m=document.createElement("style");m.textContent=`.wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:30px;padding:0;opacity:.85;flex-shrink:0}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:4px;font-weight:500}.wx-auth-note{font-size:12px;color:#888;margin-bottom:14px;line-height:1.4;white-space:nowrap}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-tabs{display:flex;gap:8px;margin-bottom:16px}.wx-auth-tab{flex:1;padding:8px 0;font-size:13px;border:1px solid #DCDCDC;background:#f7f7f7;color:#666;border-radius:6px;cursor:pointer;transition:all .2s}.wx-auth-tab:active{transform:scale(.98)}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff;font-weight:600}.wx-auth-mp-loading{height:100%;display:flex;align-items:center;justify-content:center}.wx-auth-spinner{width:28px;height:28px;border:3px solid #e5e5e5;border-top-color:#07c160;border-radius:50%;animation:wxAuthSpin 1s linear infinite}@keyframes wxAuthSpin{to{transform:rotate(360deg)}}.wx-auth-mp-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-mp-container{position:relative}.wx-auth-mp-expired{position:absolute;inset:0;z-index:1;display:none;flex-direction:column;align-items:center;justify-content:center;gap:10px;background:#ffffffeb}.wx-auth-mp-expired-text{font-size:13px;color:#666}.wx-auth-mp-expired .wx-auth-mp-refresh{flex:none;width:auto;margin:0;padding:8px 18px;font-size:13px}.wx-auth-mp-status{font-size:13px;color:#666;margin:4px 0 12px;min-height:18px;line-height:1.4}.wx-auth-mp-hint{margin:12px 0 4px}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}.wx-auth-note{color:#aaa}.wx-auth-input{background:#2a2a2a;border-color:#444;color:#e5e5e5}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16040}.wx-auth-input:disabled{background:#333;color:#888}.wx-auth-qrcode-container{background:#2a2a2a}.wx-auth-tab{background:#2a2a2a;border-color:#444;color:#aaa}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff}.wx-auth-spinner{border-color:#444;border-top-color:#07c160}.wx-auth-mp-status{color:#aaa}.wx-auth-mp-expired{background:#1a1a1aeb}.wx-auth-mp-expired-text{color:#aaa}.wx-auth-btn-secondary{background:#2a2a2a;color:#e5e5e5}.wx-auth-btn-secondary:hover:not(:disabled){background:#333}.wx-auth-message-info{background:#0d2a1f;color:#7cc4ff;border-color:#1f4a6b}.wx-auth-message-success{background:#0d2a1a;color:#4ade80;border-color:#1f6b3a}.wx-auth-message-error{background:#2a0d0d;color:#f87171;border-color:#6b1f1f}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={enable(e){if(i.isProtected||typeof window>"u")return;i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!0,i.restorePending=!1,i.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const d=r;if(d.id===e.modalId||d.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),f.safeRestore(e);return}}}),i.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!i.isProtected)return;const{getState:o}=e;if(!o().isOpen){i.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||f.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?f.isHidden(n):null}),f.safeRestore(e)),i.isProtected&&(i.rafId=requestAnimationFrame(t))};i.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!1,i.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!i.restorePending){i.restorePending=!0;try{f.restoreFn(e)}finally{requestAnimationFrame(()=>{i.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},
|
|
2
|
+
/*$vite$:1*/`,document.head.appendChild(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={enable(e){if(i.isProtected||typeof window>"u")return;i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!0,i.restorePending=!1,i.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const d=r;if(d.id===e.modalId||d.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),f.safeRestore(e);return}}}),i.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!i.isProtected)return;const{getState:o}=e;if(!o().isOpen){i.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||f.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?f.isHidden(n):null}),f.safeRestore(e)),i.isProtected&&(i.rafId=requestAnimationFrame(t))};i.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!1,i.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!i.restorePending){i.restorePending=!0;try{f.restoreFn(e)}finally{requestAnimationFrame(()=>{i.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},S={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...S},l="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},p="code",h=0;function T(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const c={getRootDomain(){return T(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},writeCookieRaw(e,t,o,n,r=!1){const d=n?`;domain=${n}`:"",U=window.location.protocol==="https:"?";Secure":"",N=r?";expires=Thu, 01 Jan 1970 00:00:00 GMT":o!==void 0?`;expires=${new Date(Date.now()+o).toUTCString()}`:"";document.cookie=`${e}=${r?"":t};path=/${d}${N}${U};SameSite=Strict`},setCookie(e,t,o){const n=this.getRootDomain();this.writeCookieRaw(e,t,o,n),n&&!this.getCookie(e)&&this.writeCookieRaw(e,t,o,"")},deleteCookie(e){const t=this.getRootDomain();this.writeCookieRaw(e,"",void 0,t,!0),t&&this.writeCookieRaw(e,"",void 0,"",!0)},getToken(){return this.getCookie("wxauth-token")},setToken(e){this.setCookie("wxauth-token",e)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},q=[1e3,3e3];function b(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function y(e){return new Promise(t=>setTimeout(t,e))}const E=3e3,I=2e3,M=3e3;function k(){h++}async function A(e){if(await y(E),!(e!==h||!s.isOpen)){for(;e===h&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==h)return;if(o.status==="confirmed"&&o.token){g.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==h)return;if(!b(o))break;await y(M);continue}await y(I)}e===h&&s.isOpen&&p==="mp"&&u.showMpExpired()}}async function v(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await c.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!b(r)||n>=q.length)return{kind:"transient"};await y(q[n])}}const D=300*1e3;let x=null;function $(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function P(){const e=l?`?siteId=${encodeURIComponent(l)}`:"",t=await c.request(`${a.apiBase}/api/sdk/config${e}`),o={wechatName:t.wechatName,qrcodeUrl:t.qrcodeUrl};return x={...o,expiresAt:Date.now()+D},o}function L(e){e.wechatName&&!a.wechatName&&(a.wechatName=e.wechatName),e.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=e.qrcodeUrl)}const u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>',o=`<div class="wx-auth-tabs">
|
|
3
3
|
<button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
|
|
4
4
|
<button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
|
|
5
5
|
</div>`,n=`<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
|
|
@@ -52,4 +52,4 @@
|
|
|
52
52
|
<div class="wx-auth-message" style="display:none"></div>
|
|
53
53
|
</div>
|
|
54
54
|
</div>
|
|
55
|
-
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>g.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;n.key==="Backspace"&&!r.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((d,
|
|
55
|
+
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>g.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;n.key==="Backspace"&&!r.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((d,C)=>{e[C]&&(e[C].value=d)}),r.length===6&&setTimeout(()=>g.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(r=>r.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),k(),s.mpSession=null,e.style.display="flex",s.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&a.wechatName&&(r.textContent=`"${a.wechatName}"`),this.bindInputEvents(),p==="mp"&&g.switchMode("mp"),setTimeout(()=>{const d=document.querySelector(".wx-auth-input");d&&d.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",s.isOpen=!1,k(),s.mpSession=null,f.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},setMpQr(e){const t=document.getElementById("wx-auth-modal"),o=t?.querySelector(".wx-auth-mp-qrcode"),n=t?.querySelector(".wx-auth-mp-loading");o&&(o.src=e,o.style.display="block",n&&(n.style.display="none"),this.setMpExpiredVisible(!1),this.setMpStatus("",!1))},setMpExpiredVisible(e){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");o&&(o.style.display=e?"flex":"none")},setMpStatus(e,t){const o=document.getElementById("wx-auth-modal"),n=o?.querySelector(".wx-auth-mp-status");n&&(n.textContent=e,n.style.display=e?"block":"none");const r=o?.querySelector(".wx-auth-mp-loading");if(r&&(r.style.display=t?"flex":"none"),t){const d=o?.querySelector(".wx-auth-mp-qrcode");d&&(d.style.display="none")}},showMpExpired(){this.setMpExpiredVisible(!0)},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},g={init(e={}){if(a={...S,...e},x=null,!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{l=new URL(t).hostname}catch{}!l&&window.location.hostname&&(l=window.location.hostname),l||(l="default"),console.log("[WxAuth] 自动获取 siteId:",l)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await v(e);return t.kind==="ok"?(t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=await v(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(){u.show(),this.switchMode("mp");let e=$();if(!e)try{e=await P()}catch(o){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",o)}e&&L(e),a.qrcodeUrl&&u.setQrCode(a.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&a.wechatName&&(t.textContent=`"${a.wechatName}"`),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)},switchMode(e){p=e;const t=document.getElementById("wx-auth-modal");if(!t)return;t.querySelectorAll(".wx-auth-tab").forEach(r=>{r.classList.toggle("wx-auth-tab-active",r.dataset.mode===p)});const o=t.querySelector(".wx-auth-panel-code"),n=t.querySelector(".wx-auth-panel-mp");o&&(o.style.display=p==="code"?"":"none"),n&&(n.style.display=p==="mp"?"":"none"),p==="mp"?this.startMpLogin():k()},async startMpLogin(){if(!s.isOpen)return;const e=++h;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){u.setMpQr(s.mpSession.qrDataUrl),A(e);return}try{const t=await c.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:l}});if(e!==h||!s.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");s.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(s.mpSession.qrDataUrl),A(e)}catch(t){if(e!==h||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码",t),this.switchMode("code"),u.showMessage("小程序扫码暂不可用,请使用公众号验证码登录","error")}},async requireAuth(){const e=c.getToken();if(e){const t=await v(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{s.resolveAuth=t})},completeLogin(e){if(e?.token&&c.setToken(e.token),p==="mp")u.setMpStatus("✅ 登录成功",!1);else{const t=document.querySelector(".wx-auth-btn-primary");t&&(t.textContent="✅ 已登录",t.style.background="#07C160")}setTimeout(()=>{this.onVerified(e?.user),this.close(!0)},500)},async verifyCode(){const e=u.getVerifyCode();if(!e||e.length!==6){u.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=l?`&siteId=${encodeURIComponent(l)}`:"",n=await c.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?this.completeLogin(n):(u.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(b(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof a.onVerified=="function"&&a.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(g)),w.WxAuth=g,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
|