wx-auth-sdk 1.2.13 → 1.2.14
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 +21 -0
- package/dist/index.d.ts +1 -0
- package/dist/wx-auth.js +51 -45
- package/dist/wx-auth.umd.js +3 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,6 +35,26 @@ SDK 会自动:
|
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
+
## 登录态与 Cookie 域
|
|
39
|
+
|
|
40
|
+
认证成功后,SDK 将签名 Token 写入 Cookie(**按根域存储,有效期 365 天**),并自动在 localStorage 存一份备份。Cookie 的 `domain` 由**当前页面域名**推导,而不是后端地址(apiBase):
|
|
41
|
+
|
|
42
|
+
| 页面域名 | Cookie 落点 | 登录态共享范围 |
|
|
43
|
+
|---------|------------|---------------|
|
|
44
|
+
| `www.shenzjd.com`(主站) | `.shenzjd.com` | 该域下所有子站共享 |
|
|
45
|
+
| `sub.mysite.com`(第三方接入) | `.mysite.com` | 该域下所有子站共享 |
|
|
46
|
+
| `localhost` / `127.0.0.1` / IP | 不设 domain | 仅当前页面 |
|
|
47
|
+
|
|
48
|
+
规则说明:
|
|
49
|
+
|
|
50
|
+
- **同一注册域内一个认证,全域自动登录**:`sub1.mysite.com` 认证后,`sub2.mysite.com`、根域 `mysite.com` 都能静默通过(凭根域 Cookie)。
|
|
51
|
+
- **跨注册域不共享**:`mysite.com` 与 `other.com` 是相互独立的登录态,需各自认证一次(浏览器安全机制,无法绕过)。
|
|
52
|
+
- **主站已登录 → 子站有登录态**:`panhub.shenzjd.com` 认证后,访问 `parse.shenzjd.com` 等其他子站同样静默通过。
|
|
53
|
+
- **localStorage 备份按站点隔离**:仅作为清 Cookie 后的兜底恢复,真正的跨子域凭证是根域 Cookie。
|
|
54
|
+
- **⚠️ 多级公共后缀**:若页面域名属于 `.com.cn` / `.co.uk` 等多级后缀(如 `site.mysite.com.cn`),"取最后两段"会推导出 `.com.cn`,浏览器会拒绝写入。此类接入需确认域名后再接入。
|
|
55
|
+
|
|
56
|
+
> **为什么 cookie 不跟 apiBase 走?** 早期版本 SDK 曾按 apiBase 域名写 Cookie,导致部署在第三方域名(`apiBase` 指向微信认证后端、页面域名不同)时 Cookie 落错域、后端起总不到凭证、前端反复弹窗(死循环)。SDK 已改为始终按「页面所在域」写 Cookie,与后端地址无关。
|
|
57
|
+
|
|
38
58
|
## API
|
|
39
59
|
|
|
40
60
|
### `WxAuth.init(options)`
|
|
@@ -155,6 +175,7 @@ WxAuth.init({
|
|
|
155
175
|
| 键盘左右/退格导航 | ✅ |
|
|
156
176
|
| 输入完成自动提交 | ✅ |
|
|
157
177
|
| 有 Cookie 静默认证 | ✅ |
|
|
178
|
+
| Cookie 按页面根域写入(跨子域共享) | ✅ |
|
|
158
179
|
| 清 Cookie 自动恢复(签名 Token 双存储:Cookie + localStorage) | ✅ |
|
|
159
180
|
| F12 删弹窗自动恢复 | ✅ |
|
|
160
181
|
|
package/dist/index.d.ts
CHANGED
package/dist/wx-auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const s = {
|
|
2
2
|
observer: null,
|
|
3
3
|
rafId: null,
|
|
4
4
|
isProtected: !1,
|
|
@@ -8,8 +8,8 @@ const r = {
|
|
|
8
8
|
* 启用弹窗保护
|
|
9
9
|
*/
|
|
10
10
|
enable(e) {
|
|
11
|
-
if (
|
|
12
|
-
|
|
11
|
+
if (s.isProtected || typeof window > "u") return;
|
|
12
|
+
s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !0, s.restorePending = !1, s.observer = new MutationObserver((o) => {
|
|
13
13
|
for (const n of o)
|
|
14
14
|
if (n.type === "childList")
|
|
15
15
|
for (const i of n.removedNodes) {
|
|
@@ -20,42 +20,42 @@ const r = {
|
|
|
20
20
|
return;
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
-
}),
|
|
23
|
+
}), s.observer.observe(document.body, {
|
|
24
24
|
childList: !0,
|
|
25
25
|
subtree: !0
|
|
26
26
|
});
|
|
27
27
|
const t = () => {
|
|
28
|
-
if (!
|
|
28
|
+
if (!s.isProtected) return;
|
|
29
29
|
const { getState: o } = e;
|
|
30
30
|
if (!o().isOpen) {
|
|
31
|
-
|
|
31
|
+
s.rafId = null;
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
34
34
|
const n = document.getElementById(e.modalId);
|
|
35
35
|
(!n || !n.isConnected || h.isHidden(n)) && (console.warn(
|
|
36
36
|
"[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
|
|
37
37
|
{ has: !!n, connected: n?.isConnected, hidden: n ? h.isHidden(n) : null }
|
|
38
|
-
), h.safeRestore(e)),
|
|
38
|
+
), h.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
|
|
39
39
|
};
|
|
40
|
-
|
|
40
|
+
s.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
|
|
41
41
|
},
|
|
42
42
|
/**
|
|
43
43
|
* 禁用弹窗保护
|
|
44
44
|
*/
|
|
45
45
|
disable() {
|
|
46
|
-
|
|
46
|
+
s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !1, s.restorePending = !1, console.log("[WxAuth] 弹窗保护已禁用");
|
|
47
47
|
},
|
|
48
48
|
/**
|
|
49
49
|
* 同一帧内避免重复恢复
|
|
50
50
|
*/
|
|
51
51
|
safeRestore(e) {
|
|
52
|
-
if (!
|
|
53
|
-
|
|
52
|
+
if (!s.restorePending) {
|
|
53
|
+
s.restorePending = !0;
|
|
54
54
|
try {
|
|
55
55
|
h.restoreFn(e);
|
|
56
56
|
} finally {
|
|
57
57
|
requestAnimationFrame(() => {
|
|
58
|
-
|
|
58
|
+
s.restorePending = !1;
|
|
59
59
|
});
|
|
60
60
|
}
|
|
61
61
|
}
|
|
@@ -104,26 +104,24 @@ const r = {
|
|
|
104
104
|
silent: !1
|
|
105
105
|
// 默认不静默
|
|
106
106
|
};
|
|
107
|
-
let
|
|
107
|
+
let r = { ...p }, l = "", u = {
|
|
108
108
|
isOpen: !1,
|
|
109
109
|
resolveAuth: null,
|
|
110
110
|
currentStep: "qr"
|
|
111
111
|
};
|
|
112
|
+
function w(e) {
|
|
113
|
+
try {
|
|
114
|
+
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
115
|
+
return "";
|
|
116
|
+
const t = e.split(".");
|
|
117
|
+
return t.length >= 2 ? "." + t.slice(-2).join(".") : "";
|
|
118
|
+
} catch {
|
|
119
|
+
return "";
|
|
120
|
+
}
|
|
121
|
+
}
|
|
112
122
|
const c = {
|
|
113
|
-
// 从 apiBase 自动推导根域名(用于跨子域名共享 Cookie)
|
|
114
|
-
// auth.shenzjd.com → .shenzjd.com
|
|
115
|
-
// parse.shenzjd.com → .shenzjd.com
|
|
116
|
-
// localhost / 127.0.0.1 / IP → 不设置 domain
|
|
117
123
|
getRootDomain() {
|
|
118
|
-
|
|
119
|
-
const e = new URL(s.apiBase || window.location.origin).hostname;
|
|
120
|
-
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
121
|
-
return "";
|
|
122
|
-
const t = e.split(".");
|
|
123
|
-
return t.length >= 2 ? "." + t.slice(-2).join(".") : "";
|
|
124
|
-
} catch {
|
|
125
|
-
return "";
|
|
126
|
-
}
|
|
124
|
+
return w(window.location.hostname);
|
|
127
125
|
},
|
|
128
126
|
// 获取Cookie
|
|
129
127
|
getCookie(e) {
|
|
@@ -207,10 +205,10 @@ const c = {
|
|
|
207
205
|
// 创建弹窗
|
|
208
206
|
createModal() {
|
|
209
207
|
const e = document.createElement("div");
|
|
210
|
-
e.id = "wx-auth-modal", e.className = "wx-auth-modal",
|
|
211
|
-
const t =
|
|
208
|
+
e.id = "wx-auth-modal", e.className = "wx-auth-modal", r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
|
|
209
|
+
const t = r.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
|
|
212
210
|
return e.innerHTML = `
|
|
213
|
-
<div class="wx-auth-overlay" ${
|
|
211
|
+
<div class="wx-auth-overlay" ${r.required ? 'onclick="event.preventDefault()"' : ""}></div>
|
|
214
212
|
<div class="wx-auth-content">
|
|
215
213
|
<div class="wx-auth-header">
|
|
216
214
|
<div class="wx-auth-title">微信认证</div>
|
|
@@ -267,13 +265,13 @@ const c = {
|
|
|
267
265
|
// 显示弹窗
|
|
268
266
|
show() {
|
|
269
267
|
let e = document.getElementById("wx-auth-modal");
|
|
270
|
-
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"),
|
|
268
|
+
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.style.display = "flex", u.isOpen = !0, h.enable({
|
|
271
269
|
modalId: "wx-auth-modal",
|
|
272
270
|
getState: () => u,
|
|
273
271
|
onRestore: () => {
|
|
274
|
-
this.createModal(),
|
|
272
|
+
this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
|
|
275
273
|
const t = document.querySelector(".wx-auth-wechat-name");
|
|
276
|
-
t &&
|
|
274
|
+
t && r.wechatName && (t.textContent = `"${r.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
|
|
277
275
|
const o = document.querySelector(".wx-auth-input");
|
|
278
276
|
o && o.focus();
|
|
279
277
|
}, 100);
|
|
@@ -311,7 +309,7 @@ const c = {
|
|
|
311
309
|
}, m = {
|
|
312
310
|
// 初始化
|
|
313
311
|
init(e = {}) {
|
|
314
|
-
if (
|
|
312
|
+
if (r = { ...p, ...e }, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
|
|
315
313
|
console.error("[WxAuth] apiBase is required");
|
|
316
314
|
return;
|
|
317
315
|
}
|
|
@@ -324,7 +322,7 @@ const c = {
|
|
|
324
322
|
}
|
|
325
323
|
!l && window.location.hostname && (l = window.location.hostname), l || (l = "default"), console.log("[WxAuth] 自动获取 siteId:", l);
|
|
326
324
|
}
|
|
327
|
-
console.log("[WxAuth] SDK initialized",
|
|
325
|
+
console.log("[WxAuth] SDK initialized", r), typeof window < "u" && (r.silent ? this.silentCheck() : this.autoCheck());
|
|
328
326
|
},
|
|
329
327
|
/**
|
|
330
328
|
* 静默验证(silent 模式专用)
|
|
@@ -338,7 +336,7 @@ const c = {
|
|
|
338
336
|
const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
|
|
339
337
|
try {
|
|
340
338
|
const a = await c.request(
|
|
341
|
-
`${
|
|
339
|
+
`${r.apiBase}/api/auth/check?${i}${n}`
|
|
342
340
|
);
|
|
343
341
|
return a.authenticated ? (a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (c.clearToken(), !1);
|
|
344
342
|
} catch (a) {
|
|
@@ -353,7 +351,7 @@ const c = {
|
|
|
353
351
|
const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
|
|
354
352
|
try {
|
|
355
353
|
const a = await c.request(
|
|
356
|
-
`${
|
|
354
|
+
`${r.apiBase}/api/auth/check?${i}${n}`
|
|
357
355
|
);
|
|
358
356
|
return a.authenticated ? (console.log("[WxAuth] 自动认证成功(凭证)"), a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (c.clearToken(), this.showAuthModal(), !1);
|
|
359
357
|
} catch (a) {
|
|
@@ -365,15 +363,15 @@ const c = {
|
|
|
365
363
|
d.show();
|
|
366
364
|
try {
|
|
367
365
|
const t = l ? `?siteId=${encodeURIComponent(l)}` : "", o = await c.request(
|
|
368
|
-
`${
|
|
366
|
+
`${r.apiBase}/api/sdk/config${t}`
|
|
369
367
|
);
|
|
370
|
-
o.wechatName && !
|
|
368
|
+
o.wechatName && !r.wechatName && (r.wechatName = o.wechatName), o.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = o.qrcodeUrl);
|
|
371
369
|
} catch (t) {
|
|
372
370
|
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
|
|
373
371
|
}
|
|
374
|
-
|
|
372
|
+
r.qrcodeUrl && d.setQrCode(r.qrcodeUrl);
|
|
375
373
|
const e = document.querySelector(".wx-auth-wechat-name");
|
|
376
|
-
e &&
|
|
374
|
+
e && r.wechatName && (e.textContent = `"${r.wechatName}"`), setTimeout(() => {
|
|
377
375
|
const t = document.querySelector(".wx-auth-input");
|
|
378
376
|
t && t.focus();
|
|
379
377
|
}, 100);
|
|
@@ -384,7 +382,7 @@ const c = {
|
|
|
384
382
|
if (e || t)
|
|
385
383
|
try {
|
|
386
384
|
const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`, a = await c.request(
|
|
387
|
-
`${
|
|
385
|
+
`${r.apiBase}/api/auth/check?${i}${n}`
|
|
388
386
|
);
|
|
389
387
|
if (a.authenticated)
|
|
390
388
|
return console.log("[WxAuth] 已认证(凭证)"), a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
|
|
@@ -409,7 +407,7 @@ const c = {
|
|
|
409
407
|
t && (t.disabled = !0, t.textContent = "验证中...");
|
|
410
408
|
try {
|
|
411
409
|
const o = l ? `&siteId=${encodeURIComponent(l)}` : "", n = await c.request(
|
|
412
|
-
`${
|
|
410
|
+
`${r.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
413
411
|
);
|
|
414
412
|
n.authenticated ? (n.token ? c.setToken(n.token) : n.user && n.user.openid && c.setCookie("wxauth-openid", n.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
|
|
415
413
|
this.onVerified(n.user), this.close(!0);
|
|
@@ -422,15 +420,23 @@ const c = {
|
|
|
422
420
|
// skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
|
|
423
421
|
// (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
|
|
424
422
|
close(e = !1) {
|
|
425
|
-
d.hide(), u.resolveAuth && (u.resolveAuth(!1), u.resolveAuth = null), !e && typeof
|
|
423
|
+
d.hide(), u.resolveAuth && (u.resolveAuth(!1), u.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
|
|
424
|
+
},
|
|
425
|
+
// 清空本地认证凭证(双重删除:Cookie + localStorage)
|
|
426
|
+
// 用于"退出登录 / 清空认证状态"按钮。
|
|
427
|
+
// 注意:signedToken 双存储备份(localStorage)若不清,清 Cookie 后
|
|
428
|
+
// SDK 会凭备份静默恢复(getToken 优先 Cookie、localStorage 兜底),
|
|
429
|
+
// 造成"清不掉"的假象——所以必须走这里而非只删 Cookie。
|
|
430
|
+
clearToken() {
|
|
431
|
+
c.clearToken();
|
|
426
432
|
},
|
|
427
433
|
// 验证成功回调
|
|
428
434
|
onVerified(e) {
|
|
429
|
-
console.log("[WxAuth] 验证成功", e), typeof
|
|
435
|
+
console.log("[WxAuth] 验证成功", e), typeof r.onVerified == "function" && r.onVerified(e), u.resolveAuth && (u.resolveAuth(!0), u.resolveAuth = null);
|
|
430
436
|
},
|
|
431
437
|
// 错误回调
|
|
432
438
|
onError(e) {
|
|
433
|
-
console.error("[WxAuth] 错误", e), typeof
|
|
439
|
+
console.error("[WxAuth] 错误", e), typeof r.onError == "function" && r.onError(e);
|
|
434
440
|
}
|
|
435
441
|
};
|
|
436
442
|
typeof window < "u" && (window.WxAuth = Object.freeze(m));
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function(f,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(f=typeof globalThis<"u"?globalThis:f||self,p(f.WxAuthSDK={}))})(this,(function(f){"use strict";var p=document.createElement("style");p.textContent=`.wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:30px;padding:0;opacity:.85;flex-shrink:0}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:4px;font-weight:500}.wx-auth-note{font-size:12px;color:#888;margin-bottom:14px;line-height:1.4;white-space:nowrap}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}.wx-auth-note{color:#aaa}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(p);const r={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(r.isProtected||typeof window>"u")return;r.observer&&(r.observer.disconnect(),r.observer=null),r.rafId!==null&&(cancelAnimationFrame(r.rafId),r.rafId=null),r.isProtected=!0,r.restorePending=!1,r.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const a of n.removedNodes){if(a.nodeType!==Node.ELEMENT_NODE)continue;const
|
|
2
|
+
/*$vite$:1*/`,document.head.appendChild(p);const r={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(r.isProtected||typeof window>"u")return;r.observer&&(r.observer.disconnect(),r.observer=null),r.rafId!==null&&(cancelAnimationFrame(r.rafId),r.rafId=null),r.isProtected=!0,r.restorePending=!1,r.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const a of n.removedNodes){if(a.nodeType!==Node.ELEMENT_NODE)continue;const c=a;if(c.id===e.modalId||c.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.safeRestore(e);return}}}),r.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!r.isProtected)return;const{getState:o}=e;if(!o().isOpen){r.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)),r.isProtected&&(r.rafId=requestAnimationFrame(t))};r.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){r.observer&&(r.observer.disconnect(),r.observer=null),r.rafId!==null&&(cancelAnimationFrame(r.rafId),r.rafId=null),r.isProtected=!1,r.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!r.restorePending){r.restorePending=!0;try{h.restoreFn(e)}finally{requestAnimationFrame(()=>{r.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 a=document.getElementById(t);if(a){a.style.display="flex",a.style.visibility="visible",a.style.opacity="1";return}n()}},m={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let i={...m},d="",u={isOpen:!1,resolveAuth:null,currentStep:"qr"};function g(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const s={getRootDomain(){return g(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+365*24*60*60*1e3);const n=this.getRootDomain(),a=n?`;domain=${n}`:"",w=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${a}${w};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o};SameSite=Strict`},get storageKey(){return"wxauth-token"},getToken(){const e=this.getCookie("wxauth-token");if(e)return e;try{return window.localStorage.getItem(this.storageKey)}catch{return null}},setToken(e){this.setCookie("wxauth-token",e);try{window.localStorage.setItem(this.storageKey,e)}catch{}},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem(this.storageKey)}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},l={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",i.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=i.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
|
|
3
3
|
<div class="wx-auth-overlay" ${i.required?'onclick="event.preventDefault()"':""}></div>
|
|
4
4
|
<div class="wx-auth-content">
|
|
5
5
|
<div class="wx-auth-header">
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
<div>
|
|
20
20
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
21
21
|
<div class="wx-auth-note">取消关注公众号后将被取消认证,请保持关注</div>
|
|
22
|
-
${
|
|
22
|
+
${s.generateCodeInputs()}
|
|
23
23
|
</div>
|
|
24
24
|
|
|
25
25
|
<!-- 消息提示 -->
|
|
@@ -31,4 +31,4 @@
|
|
|
31
31
|
</div>
|
|
32
32
|
</div>
|
|
33
33
|
</div>
|
|
34
|
-
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const a=n.target.value.replace(/\D/g,"");n.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const a=n.target;n.key==="Backspace"&&!a.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 a=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((
|
|
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 a=n.target.value.replace(/\D/g,"");n.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const a=n.target;n.key==="Backspace"&&!a.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 a=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((c,w)=>{e[w]&&(e[w].value=c)}),a.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),i.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.style.display="flex",u.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),i.qrcodeUrl&&this.setQrCode(i.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&i.wechatName&&(t.textContent=`"${i.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",u.isOpen=!1,h.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},x={init(e={}){if(i={...m,...e},!i.apiBase&&typeof window<"u"&&(i.apiBase=window.location.origin),!i.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{d=new URL(t).hostname}catch{}!d&&window.location.hostname&&(d=window.location.hostname),d||(d="default"),console.log("[WxAuth] 自动获取 siteId:",d)}console.log("[WxAuth] SDK initialized",i),typeof window<"u"&&(i.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=s.getToken(),t=s.getCookie("wxauth-openid");if(!(e||t))return!1;const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const c=await s.request(`${i.apiBase}/api/auth/check?${a}${n}`);return c.authenticated?(c.token&&(s.setToken(c.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(c.user),!0):(s.clearToken(),!1)}catch(c){return console.error("[WxAuth] silentCheck 请求失败:",c),!1}},async autoCheck(){const e=s.getToken(),t=s.getCookie("wxauth-openid");if(!(e||t))return this.showAuthModal(),!1;const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const c=await s.request(`${i.apiBase}/api/auth/check?${a}${n}`);return c.authenticated?(console.log("[WxAuth] 自动认证成功(凭证)"),c.token&&(s.setToken(c.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(c.user),!0):(s.clearToken(),this.showAuthModal(),!1)}catch(c){return console.error("[WxAuth] 自动验证失败:",c),this.showAuthModal(),!1}},async showAuthModal(){l.show();try{const t=d?`?siteId=${encodeURIComponent(d)}`:"",o=await s.request(`${i.apiBase}/api/sdk/config${t}`);o.wechatName&&!i.wechatName&&(i.wechatName=o.wechatName),o.qrcodeUrl&&!i.qrcodeUrl&&(i.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}i.qrcodeUrl&&l.setQrCode(i.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&i.wechatName&&(e.textContent=`"${i.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=s.getToken(),t=s.getCookie("wxauth-openid");if(e||t)try{const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`,c=await s.request(`${i.apiBase}/api/auth/check?${a}${n}`);if(c.authenticated)return console.log("[WxAuth] 已认证(凭证)"),c.token&&(s.setToken(c.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(c.user),!0;s.clearToken()}catch(n){console.error("[WxAuth] 凭证检查失败:",n)}return await this.showAuthModal(),new Promise(n=>{u.resolveAuth=n})},async verifyCode(){const e=l.getVerifyCode();if(!e||e.length!==6){l.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="验证中...");try{const o=d?`&siteId=${encodeURIComponent(d)}`:"",n=await s.request(`${i.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token?s.setToken(n.token):n.user&&n.user.openid&&s.setCookie("wxauth-openid",n.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(l.showMessage("验证码错误或已过期","error"),l.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch{l.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(e=!1){l.hide(),u.resolveAuth&&(u.resolveAuth(!1),u.resolveAuth=null),!e&&typeof i.onClose=="function"&&i.onClose()},clearToken(){s.clearToken()},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof i.onVerified=="function"&&i.onVerified(e),u.resolveAuth&&(u.resolveAuth(!0),u.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof i.onError=="function"&&i.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),f.WxAuth=x,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
|