wx-auth-sdk 1.2.36 → 1.2.38
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 +17 -5
- package/dist/wx-auth.js +129 -99
- package/dist/wx-auth.umd.js +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -84,7 +84,7 @@ SDK 会自动:
|
|
|
84
84
|
|
|
85
85
|
## 登录态与 Cookie 域
|
|
86
86
|
|
|
87
|
-
认证成功后,SDK 将签名 Token 写入 Cookie
|
|
87
|
+
认证成功后,SDK 将签名 Token 写入 Cookie(**按根域存储,会话 Cookie——不设 `expires`,浏览器进程关闭即失效,重新打开浏览器需重新扫码**;同一浏览器会话内刷新/开新标签页不丢登录态)。Cookie 的 `domain` 由**当前页面域名**推导,而不是后端地址(apiBase):
|
|
88
88
|
|
|
89
89
|
| 页面域名 | Cookie 落点 | 登录态共享范围 |
|
|
90
90
|
|---------|------------|---------------|
|
|
@@ -97,7 +97,7 @@ SDK 会自动:
|
|
|
97
97
|
- **同一注册域内一个认证,全域自动登录**:`sub1.mysite.com` 认证后,`sub2.mysite.com`、根域 `mysite.com` 都能静默通过(凭根域 Cookie)。
|
|
98
98
|
- **跨注册域不共享**:`mysite.com` 与 `other.com` 是相互独立的登录态,需各自认证一次(浏览器安全机制,无法绕过)。
|
|
99
99
|
- **主站已登录 → 子站有登录态**:`panhub.shenzjd.com` 认证后,访问 `parse.shenzjd.com` 等其他子站同样静默通过。
|
|
100
|
-
-
|
|
100
|
+
- **登录态统一会话级(2026-09-05)**:Cookie 不设 `expires`,浏览器进程关闭即失效、重新打开需重新扫码(2026-09-04 曾临时改为 3 天持久,随激励解锁下线回退);同一浏览器会话内刷新/开新标签不丢;小程序扫码与公众号验证码两种登录方式一致(策略沿革见主仓库 AGENTS.md「登录态有效期」)。
|
|
101
101
|
- **⚠️ 多级公共后缀**:若页面域名属于 `.com.cn` / `.co.uk` 等多级后缀(如 `site.mysite.com.cn`),"取最后两段"会推导出 `.com.cn`,浏览器会拒绝写入。此类接入需确认域名后再接入。
|
|
102
102
|
|
|
103
103
|
> **为什么 cookie 不跟 apiBase 走?** 早期版本 SDK 曾按 apiBase 域名写 Cookie,导致部署在第三方域名(`apiBase` 指向微信认证后端、页面域名不同)时 Cookie 落错域、后端起总不到凭证、前端反复弹窗(死循环)。SDK 已改为始终按「页面所在域」写 Cookie,与后端地址无关。
|
|
@@ -149,7 +149,7 @@ WxAuth.init({
|
|
|
149
149
|
初始化 WxAuth.init()
|
|
150
150
|
│
|
|
151
151
|
▼
|
|
152
|
-
读取 Cookie
|
|
152
|
+
读取 Cookie(会话级,浏览器进程内有效)
|
|
153
153
|
│
|
|
154
154
|
├── 有效 ──────────── onVerified() ✅ 静默通过
|
|
155
155
|
│
|
|
@@ -248,11 +248,23 @@ interface AuthUser {
|
|
|
248
248
|
| 输入完成自动提交 | ✅ |
|
|
249
249
|
| 有 Cookie 静默认证 | ✅ |
|
|
250
250
|
| Cookie 按页面根域写入(跨子域共享) | ✅ |
|
|
251
|
-
|
|
|
251
|
+
| 会话 Cookie 登录态(浏览器进程内共享,关闭即失效) | ✅ |
|
|
252
252
|
| 服务抖动/限流重试,不误清凭证、不误弹码框 | ✅ |
|
|
253
253
|
| F12 删弹窗自动恢复 | ✅ |
|
|
254
254
|
|
|
255
|
-
> **登录态有效期(2026-09-
|
|
255
|
+
> **登录态有效期(2026-09-05)**:web 登录态为**会话级**——Cookie 不设 `expires`,浏览器进程关闭即失效,重新打开浏览器需重新扫码;小程序扫码 / 公众号验证码一致。同一浏览器会话内刷新/开新标签页不丢登录态;不写 localStorage 备份。2026-09-04 曾短暂改为 3 天持久,随激励解锁下线回退(详见主仓库 AGENTS.md)。
|
|
256
|
+
|
|
257
|
+
---
|
|
258
|
+
|
|
259
|
+
## 平台能力:GitHub(可选)
|
|
260
|
+
|
|
261
|
+
wx-auth 不止是登录后端,还是**账号系统 + GitHub 能力平台**:用户(微信主账号)可绑定 GitHub,第三方网页领取短命 installation token 后**浏览器直连 GitHub** 操作其仓库内容(图床是第一个能力)。SDK 与站点导航组件会自动带上 GitHub 绑定/安装入口,接入方无需处理任何 GitHub 凭证。
|
|
262
|
+
|
|
263
|
+
- 状态判定:`GET /api/github/setups`(绑定 / 安装 / 能力就绪度)
|
|
264
|
+
- 开通能力:`POST /api/github/setup`(建仓 + 挂仓,幂等)
|
|
265
|
+
- 领 token:`POST /api/github/token`(8 小时有效,浏览器直传 GitHub 用)
|
|
266
|
+
|
|
267
|
+
接入三步(引导 / 开通 / 领 token 直传)的完整话术见主仓库 `docs/subsite-integration.md`,或接入方案开环时直接联系我们获取接入说明。
|
|
256
268
|
|
|
257
269
|
---
|
|
258
270
|
|
package/dist/wx-auth.js
CHANGED
|
@@ -12,9 +12,9 @@ const i = {
|
|
|
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
13
|
for (const n of o)
|
|
14
14
|
if (n.type === "childList")
|
|
15
|
-
for (const
|
|
16
|
-
if (
|
|
17
|
-
const d =
|
|
15
|
+
for (const r of n.removedNodes) {
|
|
16
|
+
if (r.nodeType !== Node.ELEMENT_NODE) continue;
|
|
17
|
+
const d = r;
|
|
18
18
|
if (d.id === e.modalId || d.querySelector?.(`#${e.modalId}`)) {
|
|
19
19
|
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), p.safeRestore(e);
|
|
20
20
|
return;
|
|
@@ -79,9 +79,9 @@ const i = {
|
|
|
79
79
|
restoreFn(e) {
|
|
80
80
|
const { modalId: t, getState: o, onRestore: n } = e;
|
|
81
81
|
if (!o().isOpen) return;
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
84
|
-
|
|
82
|
+
const r = document.getElementById(t);
|
|
83
|
+
if (r) {
|
|
84
|
+
r.style.display = "flex", r.style.visibility = "visible", r.style.opacity = "1";
|
|
85
85
|
return;
|
|
86
86
|
}
|
|
87
87
|
n();
|
|
@@ -104,7 +104,7 @@ const i = {
|
|
|
104
104
|
silent: !1
|
|
105
105
|
// 默认不静默
|
|
106
106
|
};
|
|
107
|
-
let
|
|
107
|
+
let s = { ...q }, u = "", v = "", a = {
|
|
108
108
|
isOpen: !1,
|
|
109
109
|
resolveAuth: null,
|
|
110
110
|
currentStep: "qr",
|
|
@@ -120,7 +120,7 @@ function E(e) {
|
|
|
120
120
|
return "";
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
-
const
|
|
123
|
+
const l = {
|
|
124
124
|
getRootDomain() {
|
|
125
125
|
return E(window.location.hostname);
|
|
126
126
|
},
|
|
@@ -130,9 +130,9 @@ const u = {
|
|
|
130
130
|
return o.length === 2 && o.pop()?.split(";").shift() || null;
|
|
131
131
|
},
|
|
132
132
|
// Cookie 写入底层(domainStr 传空串 = host-only,落在当前 host 本域)
|
|
133
|
-
writeCookieRaw(e, t, o, n,
|
|
134
|
-
const d = n ? `;domain=${n}` : "",
|
|
135
|
-
document.cookie = `${e}=${
|
|
133
|
+
writeCookieRaw(e, t, o, n, r = !1) {
|
|
134
|
+
const d = n ? `;domain=${n}` : "", A = window.location.protocol === "https:" ? ";Secure" : "", I = r ? ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : o !== void 0 ? `;expires=${new Date(Date.now() + o).toUTCString()}` : "";
|
|
135
|
+
document.cookie = `${e}=${r ? "" : t};path=/${d}${I}${A};SameSite=Strict`;
|
|
136
136
|
},
|
|
137
137
|
// 设置Cookie(2026-09-04:不传 maxAgeMs 时仍是会话 Cookie —— 浏览器关闭即失效;
|
|
138
138
|
// 传入 maxAgeMs 则写持久 Cookie;自动设置根域名实现跨子域共享)
|
|
@@ -177,6 +177,33 @@ const u = {
|
|
|
177
177
|
} catch {
|
|
178
178
|
}
|
|
179
179
|
},
|
|
180
|
+
// ===== 设备标识(2026-09-12,风控)=====
|
|
181
|
+
// wxauth-device:随机 32 位 hex 持久 Cookie(1 年),localStorage 镜像兜底
|
|
182
|
+
// (Cookie 被清理/写入失败时从镜像恢复,避免设备身份漂移)。
|
|
183
|
+
// 注意:这是设备身份不是凭证——退出登录(clearToken/revoke)不清除它。
|
|
184
|
+
getOrCreateDeviceId() {
|
|
185
|
+
if (v) return v;
|
|
186
|
+
let e = this.getCookie("wxauth-device");
|
|
187
|
+
if (!e)
|
|
188
|
+
try {
|
|
189
|
+
e = window.localStorage.getItem("wxauth-device");
|
|
190
|
+
} catch {
|
|
191
|
+
}
|
|
192
|
+
if (!e || !/^[A-Za-z0-9_-]{1,64}$/.test(e)) {
|
|
193
|
+
const t = new Uint8Array(16);
|
|
194
|
+
if (typeof crypto < "u" && crypto.getRandomValues)
|
|
195
|
+
crypto.getRandomValues(t);
|
|
196
|
+
else
|
|
197
|
+
for (let o = 0; o < 16; o++) t[o] = Math.floor(Math.random() * 256);
|
|
198
|
+
e = Array.from(t).map((o) => o.toString(16).padStart(2, "0")).join("");
|
|
199
|
+
}
|
|
200
|
+
this.setCookie("wxauth-device", e, 365 * 86400 * 1e3);
|
|
201
|
+
try {
|
|
202
|
+
window.localStorage.setItem("wxauth-device", e);
|
|
203
|
+
} catch {
|
|
204
|
+
}
|
|
205
|
+
return v = e, e;
|
|
206
|
+
},
|
|
180
207
|
// 发送请求
|
|
181
208
|
// 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
|
|
182
209
|
// 供调用方区分「明确未认证」与「瞬时失败」——后者不应触发重新验证(2026-08-29)
|
|
@@ -209,16 +236,16 @@ const u = {
|
|
|
209
236
|
e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
|
|
210
237
|
return e += "</div>", e;
|
|
211
238
|
}
|
|
212
|
-
},
|
|
213
|
-
function
|
|
239
|
+
}, C = [1e3, 3e3];
|
|
240
|
+
function b(e) {
|
|
214
241
|
const t = e;
|
|
215
242
|
return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
|
|
216
243
|
}
|
|
217
244
|
function y(e) {
|
|
218
245
|
return new Promise((t) => setTimeout(t, e));
|
|
219
246
|
}
|
|
220
|
-
const T = 3e3,
|
|
221
|
-
function
|
|
247
|
+
const T = 3e3, M = 2e3, $ = 3e3;
|
|
248
|
+
function k() {
|
|
222
249
|
h++;
|
|
223
250
|
}
|
|
224
251
|
async function S(e) {
|
|
@@ -227,8 +254,8 @@ async function S(e) {
|
|
|
227
254
|
const t = a.mpSession;
|
|
228
255
|
if (!t || Date.now() >= t.expiresAt) break;
|
|
229
256
|
try {
|
|
230
|
-
const o = await
|
|
231
|
-
`${
|
|
257
|
+
const o = await l.request(
|
|
258
|
+
`${s.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
|
|
232
259
|
);
|
|
233
260
|
if (e !== h) return;
|
|
234
261
|
if (o.status === "confirmed" && o.token) {
|
|
@@ -241,28 +268,28 @@ async function S(e) {
|
|
|
241
268
|
}
|
|
242
269
|
} catch (o) {
|
|
243
270
|
if (e !== h) return;
|
|
244
|
-
if (!
|
|
245
|
-
await y(
|
|
271
|
+
if (!b(o)) break;
|
|
272
|
+
await y($);
|
|
246
273
|
continue;
|
|
247
274
|
}
|
|
248
|
-
await y(
|
|
275
|
+
await y(M);
|
|
249
276
|
}
|
|
250
|
-
e === h && a.isOpen && f === "mp" &&
|
|
277
|
+
e === h && a.isOpen && f === "mp" && c.showMpExpired();
|
|
251
278
|
}
|
|
252
279
|
}
|
|
253
|
-
async function
|
|
254
|
-
const t =
|
|
280
|
+
async function g(e) {
|
|
281
|
+
const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${s.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
|
|
255
282
|
for (let n = 0; ; n++)
|
|
256
283
|
try {
|
|
257
|
-
const
|
|
258
|
-
return
|
|
259
|
-
} catch (
|
|
260
|
-
if (!
|
|
284
|
+
const r = await l.request(o);
|
|
285
|
+
return r.authenticated ? { kind: "ok", result: r } : r.error === "rate_limited" || r.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: r };
|
|
286
|
+
} catch (r) {
|
|
287
|
+
if (!b(r) || n >= C.length)
|
|
261
288
|
return { kind: "transient" };
|
|
262
|
-
await y(
|
|
289
|
+
await y(C[n]);
|
|
263
290
|
}
|
|
264
291
|
}
|
|
265
|
-
const
|
|
292
|
+
const D = 300 * 1e3;
|
|
266
293
|
let m = null;
|
|
267
294
|
function L() {
|
|
268
295
|
return !m || Date.now() >= m.expiresAt ? (m = null, null) : {
|
|
@@ -270,26 +297,26 @@ function L() {
|
|
|
270
297
|
qrcodeUrl: m.qrcodeUrl
|
|
271
298
|
};
|
|
272
299
|
}
|
|
273
|
-
async function
|
|
274
|
-
const e =
|
|
275
|
-
`${
|
|
300
|
+
async function P() {
|
|
301
|
+
const e = u ? `?siteId=${encodeURIComponent(u)}` : "", t = await l.request(
|
|
302
|
+
`${s.apiBase}/api/sdk/config${e}`
|
|
276
303
|
), o = {
|
|
277
304
|
wechatName: t.wechatName,
|
|
278
305
|
qrcodeUrl: t.qrcodeUrl
|
|
279
306
|
};
|
|
280
|
-
return m = { ...o, expiresAt: Date.now() +
|
|
307
|
+
return m = { ...o, expiresAt: Date.now() + D }, o;
|
|
281
308
|
}
|
|
282
|
-
function
|
|
283
|
-
e.wechatName && !
|
|
309
|
+
function R(e) {
|
|
310
|
+
e.wechatName && !s.wechatName && (s.wechatName = e.wechatName), e.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = e.qrcodeUrl);
|
|
284
311
|
}
|
|
285
|
-
const
|
|
312
|
+
const c = {
|
|
286
313
|
// 创建弹窗
|
|
287
314
|
// 形态固定为双 tab(2026-08-30 去掉 mpScanEnabled 门控):形态不依赖 config,
|
|
288
315
|
// 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab)结构上不存在
|
|
289
316
|
createModal() {
|
|
290
317
|
const e = document.createElement("div");
|
|
291
|
-
e.id = "wx-auth-modal", e.className = "wx-auth-modal",
|
|
292
|
-
const t =
|
|
318
|
+
e.id = "wx-auth-modal", e.className = "wx-auth-modal", s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
|
|
319
|
+
const t = s.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>', o = `<div class="wx-auth-tabs">
|
|
293
320
|
<button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
|
|
294
321
|
<button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
|
|
295
322
|
</div>`, n = `<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
|
|
@@ -305,7 +332,7 @@ const l = {
|
|
|
305
332
|
<div class="wx-auth-mp-status"></div>
|
|
306
333
|
</div>`;
|
|
307
334
|
return e.innerHTML = `
|
|
308
|
-
<div class="wx-auth-overlay" ${
|
|
335
|
+
<div class="wx-auth-overlay" ${s.required ? 'onclick="event.preventDefault()"' : ""}></div>
|
|
309
336
|
<div class="wx-auth-content">
|
|
310
337
|
<div class="wx-auth-header">
|
|
311
338
|
<div class="wx-auth-title">微信登录</div>
|
|
@@ -327,7 +354,7 @@ const l = {
|
|
|
327
354
|
<!-- 验证码输入区域 -->
|
|
328
355
|
<div>
|
|
329
356
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
330
|
-
${
|
|
357
|
+
${l.generateCodeInputs()}
|
|
331
358
|
</div>
|
|
332
359
|
|
|
333
360
|
<!-- 按钮 -->
|
|
@@ -351,17 +378,17 @@ const l = {
|
|
|
351
378
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
352
379
|
e.length && e.forEach((t, o) => {
|
|
353
380
|
t.addEventListener("input", (n) => {
|
|
354
|
-
const
|
|
355
|
-
n.target.value =
|
|
381
|
+
const r = n.target.value.replace(/\D/g, "");
|
|
382
|
+
n.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => w.verifyCode(), 300);
|
|
356
383
|
}), t.addEventListener("keydown", (n) => {
|
|
357
|
-
const
|
|
358
|
-
n.key === "Backspace" && !
|
|
384
|
+
const r = n.target;
|
|
385
|
+
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());
|
|
359
386
|
}), t.addEventListener("paste", (n) => {
|
|
360
387
|
n.preventDefault();
|
|
361
|
-
const
|
|
362
|
-
|
|
388
|
+
const r = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
389
|
+
r && (r.split("").forEach((d, x) => {
|
|
363
390
|
e[x] && (e[x].value = d);
|
|
364
|
-
}),
|
|
391
|
+
}), r.length === 6 && setTimeout(() => w.verifyCode(), 300));
|
|
365
392
|
});
|
|
366
393
|
});
|
|
367
394
|
}, 100);
|
|
@@ -369,17 +396,17 @@ const l = {
|
|
|
369
396
|
// 显示弹窗
|
|
370
397
|
show() {
|
|
371
398
|
let e = document.getElementById("wx-auth-modal");
|
|
372
|
-
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"),
|
|
399
|
+
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.querySelectorAll(".wx-auth-input").forEach((r) => r.value = "");
|
|
373
400
|
const o = e.querySelector(".wx-auth-message");
|
|
374
401
|
o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
|
|
375
402
|
const n = e.querySelector(".wx-auth-btn-primary");
|
|
376
|
-
n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""),
|
|
403
|
+
n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), k(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, p.enable({
|
|
377
404
|
modalId: "wx-auth-modal",
|
|
378
405
|
getState: () => a,
|
|
379
406
|
onRestore: () => {
|
|
380
|
-
this.createModal(),
|
|
381
|
-
const
|
|
382
|
-
|
|
407
|
+
this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
|
|
408
|
+
const r = document.querySelector(".wx-auth-wechat-name");
|
|
409
|
+
r && s.wechatName && (r.textContent = `"${s.wechatName}"`), this.bindInputEvents(), f === "mp" && w.switchMode("mp"), setTimeout(() => {
|
|
383
410
|
const d = document.querySelector(".wx-auth-input");
|
|
384
411
|
d && d.focus();
|
|
385
412
|
}, 100);
|
|
@@ -389,7 +416,7 @@ const l = {
|
|
|
389
416
|
// 隐藏弹窗
|
|
390
417
|
hide() {
|
|
391
418
|
const e = document.getElementById("wx-auth-modal");
|
|
392
|
-
e && (e.style.display = "none", a.isOpen = !1,
|
|
419
|
+
e && (e.style.display = "none", a.isOpen = !1, k(), a.mpSession = null, p.disable());
|
|
393
420
|
},
|
|
394
421
|
// 设置二维码
|
|
395
422
|
setQrCode(e) {
|
|
@@ -412,8 +439,8 @@ const l = {
|
|
|
412
439
|
setMpStatus(e, t) {
|
|
413
440
|
const o = document.getElementById("wx-auth-modal"), n = o?.querySelector(".wx-auth-mp-status");
|
|
414
441
|
n && (n.textContent = e, n.style.display = e ? "block" : "none");
|
|
415
|
-
const
|
|
416
|
-
if (
|
|
442
|
+
const r = o?.querySelector(".wx-auth-mp-loading");
|
|
443
|
+
if (r && (r.style.display = t ? "flex" : "none"), t) {
|
|
417
444
|
const d = o?.querySelector(".wx-auth-mp-qrcode");
|
|
418
445
|
d && (d.style.display = "none");
|
|
419
446
|
}
|
|
@@ -442,7 +469,7 @@ const l = {
|
|
|
442
469
|
}, w = {
|
|
443
470
|
// 初始化
|
|
444
471
|
init(e = {}) {
|
|
445
|
-
if (
|
|
472
|
+
if (s = { ...q, ...e }, m = null, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
|
|
446
473
|
console.error("[WxAuth] apiBase is required");
|
|
447
474
|
return;
|
|
448
475
|
}
|
|
@@ -450,12 +477,14 @@ const l = {
|
|
|
450
477
|
const t = document.referrer;
|
|
451
478
|
if (t)
|
|
452
479
|
try {
|
|
453
|
-
|
|
480
|
+
u = new URL(t).hostname;
|
|
454
481
|
} catch {
|
|
455
482
|
}
|
|
456
|
-
!
|
|
483
|
+
!u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
|
|
484
|
+
const o = l.getOrCreateDeviceId();
|
|
485
|
+
console.log("[WxAuth] deviceId:", o);
|
|
457
486
|
}
|
|
458
|
-
console.log("[WxAuth] SDK initialized",
|
|
487
|
+
console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
|
|
459
488
|
},
|
|
460
489
|
/**
|
|
461
490
|
* 静默验证(silent 模式专用)
|
|
@@ -467,18 +496,18 @@ const l = {
|
|
|
467
496
|
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
468
497
|
*/
|
|
469
498
|
async silentCheck() {
|
|
470
|
-
const e =
|
|
499
|
+
const e = l.getToken();
|
|
471
500
|
if (!e) return !1;
|
|
472
|
-
const t = await
|
|
473
|
-
return t.kind === "ok" ? (t.result.token &&
|
|
501
|
+
const t = await g(e);
|
|
502
|
+
return t.kind === "ok" ? (t.result.token && l.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
|
|
474
503
|
},
|
|
475
504
|
// 自动检测凭证并验证(内部使用)
|
|
476
505
|
async autoCheck() {
|
|
477
|
-
const e =
|
|
506
|
+
const e = l.getToken();
|
|
478
507
|
if (!e)
|
|
479
508
|
return this.showAuthModal(), !1;
|
|
480
|
-
const t = await
|
|
481
|
-
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token &&
|
|
509
|
+
const t = await g(e);
|
|
510
|
+
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && l.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
|
|
482
511
|
code: "server_error",
|
|
483
512
|
retryable: !0,
|
|
484
513
|
message: "登录服务暂时不可用,请稍后重试"
|
|
@@ -489,17 +518,17 @@ const l = {
|
|
|
489
518
|
// UI.show() 同步渲染 + 默认小程序扫码立即出码,全程只有一种形态,无中间态;
|
|
490
519
|
// /api/sdk/config(公众号名称/码图)改为后台拉取,不再阻塞渲染。
|
|
491
520
|
async showAuthModal() {
|
|
492
|
-
|
|
521
|
+
c.show(), this.switchMode("mp");
|
|
493
522
|
let e = L();
|
|
494
523
|
if (!e)
|
|
495
524
|
try {
|
|
496
|
-
e = await
|
|
525
|
+
e = await P();
|
|
497
526
|
} catch (o) {
|
|
498
527
|
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", o);
|
|
499
528
|
}
|
|
500
|
-
e &&
|
|
529
|
+
e && R(e), s.qrcodeUrl && c.setQrCode(s.qrcodeUrl);
|
|
501
530
|
const t = document.querySelector(".wx-auth-wechat-name");
|
|
502
|
-
t &&
|
|
531
|
+
t && s.wechatName && (t.textContent = `"${s.wechatName}"`), setTimeout(() => {
|
|
503
532
|
const o = document.querySelector(".wx-auth-input");
|
|
504
533
|
o && o.focus();
|
|
505
534
|
}, 100);
|
|
@@ -509,24 +538,24 @@ const l = {
|
|
|
509
538
|
f = e;
|
|
510
539
|
const t = document.getElementById("wx-auth-modal");
|
|
511
540
|
if (!t) return;
|
|
512
|
-
t.querySelectorAll(".wx-auth-tab").forEach((
|
|
513
|
-
|
|
541
|
+
t.querySelectorAll(".wx-auth-tab").forEach((r) => {
|
|
542
|
+
r.classList.toggle("wx-auth-tab-active", r.dataset.mode === f);
|
|
514
543
|
});
|
|
515
544
|
const o = t.querySelector(".wx-auth-panel-code"), n = t.querySelector(".wx-auth-panel-mp");
|
|
516
|
-
o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() :
|
|
545
|
+
o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : k();
|
|
517
546
|
},
|
|
518
547
|
// 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
|
|
519
548
|
async startMpLogin() {
|
|
520
549
|
if (!a.isOpen) return;
|
|
521
550
|
const e = ++h;
|
|
522
|
-
if (
|
|
523
|
-
|
|
551
|
+
if (c.setMpExpiredVisible(!1), c.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
|
|
552
|
+
c.setMpQr(a.mpSession.qrDataUrl), S(e);
|
|
524
553
|
return;
|
|
525
554
|
}
|
|
526
555
|
try {
|
|
527
|
-
const t = await
|
|
556
|
+
const t = await l.request(`${s.apiBase}/api/auth/mp-scan/create`, {
|
|
528
557
|
method: "POST",
|
|
529
|
-
body: { siteId:
|
|
558
|
+
body: { siteId: u }
|
|
530
559
|
});
|
|
531
560
|
if (e !== h || !a.isOpen) return;
|
|
532
561
|
if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
|
|
@@ -534,21 +563,21 @@ const l = {
|
|
|
534
563
|
ticket: String(t.ticket),
|
|
535
564
|
qrDataUrl: String(t.qrDataUrl),
|
|
536
565
|
expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
|
|
537
|
-
},
|
|
566
|
+
}, c.setMpQr(a.mpSession.qrDataUrl), S(e);
|
|
538
567
|
} catch (t) {
|
|
539
568
|
if (e !== h || !a.isOpen) return;
|
|
540
|
-
console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"),
|
|
569
|
+
console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"), c.showMessage("小程序扫码暂不可用,请使用公众号验证码登录", "error");
|
|
541
570
|
}
|
|
542
571
|
},
|
|
543
572
|
// 主入口:需要验证时调用
|
|
544
573
|
// 凭证仅签名 Token(登录 Cookie,会话级,2026-09-05),不再兼容明文 openid
|
|
545
574
|
// (2026-08-26 服务端已下线 openid 通道)
|
|
546
575
|
async requireAuth() {
|
|
547
|
-
const e =
|
|
576
|
+
const e = l.getToken();
|
|
548
577
|
if (e) {
|
|
549
|
-
const t = await
|
|
578
|
+
const t = await g(e);
|
|
550
579
|
if (t.kind === "ok")
|
|
551
|
-
return console.log("[WxAuth] 已认证(凭证)"), t.result.token &&
|
|
580
|
+
return console.log("[WxAuth] 已认证(凭证)"), t.result.token && l.setToken(t.result.token), this.onVerified(t.result.user), !0;
|
|
552
581
|
if (t.kind === "transient")
|
|
553
582
|
return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
|
|
554
583
|
code: "server_error",
|
|
@@ -565,8 +594,8 @@ const l = {
|
|
|
565
594
|
// 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
|
|
566
595
|
// close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
|
|
567
596
|
completeLogin(e) {
|
|
568
|
-
if (e?.token &&
|
|
569
|
-
|
|
597
|
+
if (e?.token && l.setToken(e.token), f === "mp")
|
|
598
|
+
c.setMpStatus("✅ 登录成功", !1);
|
|
570
599
|
else {
|
|
571
600
|
const t = document.querySelector(".wx-auth-btn-primary");
|
|
572
601
|
t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
|
|
@@ -577,9 +606,9 @@ const l = {
|
|
|
577
606
|
},
|
|
578
607
|
// 验证验证码
|
|
579
608
|
async verifyCode() {
|
|
580
|
-
const e =
|
|
609
|
+
const e = c.getVerifyCode();
|
|
581
610
|
if (!e || e.length !== 6) {
|
|
582
|
-
|
|
611
|
+
c.showMessage("请输入6位验证码", "error");
|
|
583
612
|
return;
|
|
584
613
|
}
|
|
585
614
|
const t = document.querySelector(
|
|
@@ -587,16 +616,16 @@ const l = {
|
|
|
587
616
|
);
|
|
588
617
|
t && (t.disabled = !0, t.textContent = "登录中...");
|
|
589
618
|
try {
|
|
590
|
-
const o =
|
|
591
|
-
`${
|
|
619
|
+
const o = u ? `&siteId=${encodeURIComponent(u)}` : "", n = `&deviceId=${encodeURIComponent(l.getOrCreateDeviceId())}`, r = await l.request(
|
|
620
|
+
`${s.apiBase}/api/auth/check?authToken=${e}${o}${n}`
|
|
592
621
|
);
|
|
593
|
-
|
|
594
|
-
|
|
622
|
+
r.authenticated ? this.completeLogin(r) : (c.showMessage(
|
|
623
|
+
r.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
|
|
595
624
|
"error"
|
|
596
|
-
),
|
|
625
|
+
), c.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
|
|
597
626
|
} catch (o) {
|
|
598
|
-
|
|
599
|
-
|
|
627
|
+
c.showMessage(
|
|
628
|
+
b(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
|
|
600
629
|
"error"
|
|
601
630
|
), t && (t.disabled = !1, t.textContent = "登录");
|
|
602
631
|
}
|
|
@@ -605,12 +634,12 @@ const l = {
|
|
|
605
634
|
// skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
|
|
606
635
|
// (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
|
|
607
636
|
close(e = !1) {
|
|
608
|
-
|
|
637
|
+
c.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
|
|
609
638
|
},
|
|
610
639
|
// 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
|
|
611
640
|
// 用于"退出登录 / 清空认证状态"按钮。
|
|
612
641
|
clearToken() {
|
|
613
|
-
|
|
642
|
+
l.clearToken();
|
|
614
643
|
},
|
|
615
644
|
// 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
|
|
616
645
|
// 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
|
|
@@ -621,13 +650,14 @@ const l = {
|
|
|
621
650
|
// 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
|
|
622
651
|
// 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
|
|
623
652
|
async revoke() {
|
|
624
|
-
const e =
|
|
653
|
+
const e = l.getToken();
|
|
625
654
|
if (e)
|
|
626
655
|
try {
|
|
627
|
-
const t =
|
|
656
|
+
const t = s.apiBase && !/\/$/.test(s.apiBase) ? s.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
|
|
628
657
|
method: "POST",
|
|
629
658
|
headers: { "Content-Type": "application/json" },
|
|
630
|
-
|
|
659
|
+
// deviceId 显式携带(跨站 SameSite 下 Cookie 不可靠);设备身份不因退出而清除
|
|
660
|
+
body: JSON.stringify({ token: e, deviceId: l.getOrCreateDeviceId() }),
|
|
631
661
|
credentials: "include"
|
|
632
662
|
});
|
|
633
663
|
o.ok || console.warn("[WxAuth] revoke 请求失败,降级本地清理", o.status);
|
|
@@ -638,11 +668,11 @@ const l = {
|
|
|
638
668
|
},
|
|
639
669
|
// 验证成功回调
|
|
640
670
|
onVerified(e) {
|
|
641
|
-
console.log("[WxAuth] 验证成功", e), typeof
|
|
671
|
+
console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), a.resolveAuth && (a.resolveAuth(!0), a.resolveAuth = null);
|
|
642
672
|
},
|
|
643
673
|
// 错误回调
|
|
644
674
|
onError(e) {
|
|
645
|
-
console.error("[WxAuth] 错误", e), typeof
|
|
675
|
+
console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
|
|
646
676
|
}
|
|
647
677
|
};
|
|
648
678
|
typeof window < "u" && (window.WxAuth = Object.freeze(w));
|
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()}},q={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...q},l="",b="",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}`:"",R=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}${R};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{}},getOrCreateDeviceId(){if(b)return b;let e=this.getCookie("wxauth-device");if(!e)try{e=window.localStorage.getItem("wxauth-device")}catch{}if(!e||!/^[A-Za-z0-9_-]{1,64}$/.test(e)){const t=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let o=0;o<16;o++)t[o]=Math.floor(Math.random()*256);e=Array.from(t).map(o=>o.toString(16).padStart(2,"0")).join("")}this.setCookie("wxauth-device",e,365*86400*1e3);try{window.localStorage.setItem("wxauth-device",e)}catch{}return b=e,e},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},A=[1e3,3e3];function k(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,M=2e3,D=3e3;function v(){h++}async function I(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(!k(o))break;await y(D);continue}await y(M)}e===h&&s.isOpen&&p==="mp"&&u.showMpExpired()}}async function C(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(!k(r)||n>=A.length)return{kind:"transient"};await y(A[n])}}const $=300*1e3;let x=null;function P(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function U(){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()+$},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,S)=>{e[S]&&(e[S].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=""),v(),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,v(),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={...q,...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);const o=c.getOrCreateDeviceId();console.log("[WxAuth] deviceId:",o)}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 C(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 C(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=P();if(!e)try{e=await U()}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():v()},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),I(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),I(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 C(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=`&deviceId=${encodeURIComponent(c.getOrCreateDeviceId())}`,r=await c.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}${n}`);r.authenticated?this.completeLogin(r):(u.showMessage(r.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(k(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,deviceId:c.getOrCreateDeviceId()}),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"})}));
|