wx-auth-sdk 1.2.22 → 1.2.24
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/index.d.ts +4 -1
- package/dist/wx-auth.js +119 -93
- package/dist/wx-auth.umd.js +3 -3
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,10 @@ export declare const WxAuth: {
|
|
|
3
3
|
/**
|
|
4
4
|
* 静默验证(silent 模式专用)
|
|
5
5
|
* - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
|
|
6
|
-
* - cookie 无效 / 不存在 →
|
|
6
|
+
* - cookie 无效 / 不存在 → 不清 cookie、不弹窗,仅返回 false
|
|
7
|
+
* (2026-08-28:不再 deleteCookie。失效 cookie 保留,供后端识别"有凭证但
|
|
8
|
+
* 失效"(取关)→ 返回 401 → 前端弹认证弹窗;后端通过有无 cookie 区分
|
|
9
|
+
* "页面用户取关"(401)与"无凭证爬虫"(蜜罐假数据))
|
|
7
10
|
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
8
11
|
*/
|
|
9
12
|
silentCheck(): Promise<boolean>;
|
package/dist/wx-auth.js
CHANGED
|
@@ -10,12 +10,12 @@ const i = {
|
|
|
10
10
|
enable(e) {
|
|
11
11
|
if (i.isProtected || typeof window > "u") return;
|
|
12
12
|
i.observer && (i.observer.disconnect(), i.observer = null), i.rafId !== null && (cancelAnimationFrame(i.rafId), i.rafId = null), i.isProtected = !0, i.restorePending = !1, i.observer = new MutationObserver((o) => {
|
|
13
|
-
for (const
|
|
14
|
-
if (
|
|
15
|
-
for (const
|
|
16
|
-
if (
|
|
17
|
-
const
|
|
18
|
-
if (
|
|
13
|
+
for (const r of o)
|
|
14
|
+
if (r.type === "childList")
|
|
15
|
+
for (const n of r.removedNodes) {
|
|
16
|
+
if (n.nodeType !== Node.ELEMENT_NODE) continue;
|
|
17
|
+
const l = n;
|
|
18
|
+
if (l.id === e.modalId || l.querySelector?.(`#${e.modalId}`)) {
|
|
19
19
|
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
|
|
20
20
|
return;
|
|
21
21
|
}
|
|
@@ -31,10 +31,10 @@ const i = {
|
|
|
31
31
|
i.rafId = null;
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
34
|
-
const
|
|
35
|
-
(!
|
|
34
|
+
const r = document.getElementById(e.modalId);
|
|
35
|
+
(!r || !r.isConnected || h.isHidden(r)) && (console.warn(
|
|
36
36
|
"[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
|
|
37
|
-
{ has: !!
|
|
37
|
+
{ has: !!r, connected: r?.isConnected, hidden: r ? h.isHidden(r) : null }
|
|
38
38
|
), h.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
|
|
39
39
|
};
|
|
40
40
|
i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
|
|
@@ -77,16 +77,16 @@ const i = {
|
|
|
77
77
|
* 恢复弹窗
|
|
78
78
|
*/
|
|
79
79
|
restoreFn(e) {
|
|
80
|
-
const { modalId: t, getState: o, onRestore:
|
|
80
|
+
const { modalId: t, getState: o, onRestore: r } = e;
|
|
81
81
|
if (!o().isOpen) return;
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
84
|
-
|
|
82
|
+
const n = document.getElementById(t);
|
|
83
|
+
if (n) {
|
|
84
|
+
n.style.display = "flex", n.style.visibility = "visible", n.style.opacity = "1";
|
|
85
85
|
return;
|
|
86
86
|
}
|
|
87
|
-
|
|
87
|
+
r();
|
|
88
88
|
}
|
|
89
|
-
},
|
|
89
|
+
}, y = {
|
|
90
90
|
apiBase: "https://wx-auth.shenzjd.com",
|
|
91
91
|
// 后端API地址(默认值)
|
|
92
92
|
onVerified: null,
|
|
@@ -104,12 +104,12 @@ const i = {
|
|
|
104
104
|
silent: !1
|
|
105
105
|
// 默认不静默
|
|
106
106
|
};
|
|
107
|
-
let s = { ...
|
|
107
|
+
let s = { ...y }, u = "", c = {
|
|
108
108
|
isOpen: !1,
|
|
109
109
|
resolveAuth: null,
|
|
110
110
|
currentStep: "qr"
|
|
111
111
|
};
|
|
112
|
-
function
|
|
112
|
+
function k(e) {
|
|
113
113
|
try {
|
|
114
114
|
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
115
115
|
return "";
|
|
@@ -121,7 +121,7 @@ function p(e) {
|
|
|
121
121
|
}
|
|
122
122
|
const a = {
|
|
123
123
|
getRootDomain() {
|
|
124
|
-
return
|
|
124
|
+
return k(window.location.hostname);
|
|
125
125
|
},
|
|
126
126
|
// 获取Cookie
|
|
127
127
|
getCookie(e) {
|
|
@@ -132,13 +132,13 @@ const a = {
|
|
|
132
132
|
setCookie(e, t) {
|
|
133
133
|
const o = /* @__PURE__ */ new Date();
|
|
134
134
|
o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
|
|
135
|
-
const
|
|
136
|
-
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${
|
|
135
|
+
const r = this.getRootDomain(), n = r ? `;domain=${r}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
|
|
136
|
+
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${n}${f};SameSite=Strict`;
|
|
137
137
|
},
|
|
138
138
|
// 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
|
|
139
139
|
deleteCookie(e) {
|
|
140
|
-
const t = this.getRootDomain(), o = t ? `;domain=${t}` : "",
|
|
141
|
-
document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${
|
|
140
|
+
const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", n = window.location.protocol === "https:" ? ";Secure" : "";
|
|
141
|
+
document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${n};SameSite=Strict`;
|
|
142
142
|
},
|
|
143
143
|
// ===== 签名 Token 双存储(Cookie 主 + localStorage 备份) =====
|
|
144
144
|
// 目标:用户清除 Cookie 后,若服务端认证状态仍有效,可凭备份静默恢复。
|
|
@@ -176,6 +176,8 @@ const a = {
|
|
|
176
176
|
}
|
|
177
177
|
},
|
|
178
178
|
// 发送请求
|
|
179
|
+
// 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
|
|
180
|
+
// 供调用方区分「明确未认证」与「瞬时失败」——后者不应触发重新验证(2026-08-29)
|
|
179
181
|
async request(e, t = {}) {
|
|
180
182
|
try {
|
|
181
183
|
const o = await fetch(e, {
|
|
@@ -187,11 +189,14 @@ const a = {
|
|
|
187
189
|
body: t.body ? JSON.stringify(t.body) : null,
|
|
188
190
|
credentials: "include"
|
|
189
191
|
});
|
|
190
|
-
if (!o.ok)
|
|
191
|
-
|
|
192
|
+
if (!o.ok) {
|
|
193
|
+
const r = new Error(`HTTP ${o.status}`);
|
|
194
|
+
throw r.status = o.status, r;
|
|
195
|
+
}
|
|
192
196
|
return await o.json();
|
|
193
197
|
} catch (o) {
|
|
194
|
-
|
|
198
|
+
const r = o;
|
|
199
|
+
throw r.status === void 0 && (r.isNetworkError = !0), console.error("[WxAuth] Request error:", o), r;
|
|
195
200
|
}
|
|
196
201
|
},
|
|
197
202
|
// 生成6位验证码输入框HTML
|
|
@@ -201,7 +206,27 @@ const a = {
|
|
|
201
206
|
e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
|
|
202
207
|
return e += "</div>", e;
|
|
203
208
|
}
|
|
204
|
-
},
|
|
209
|
+
}, p = [1e3, 3e3];
|
|
210
|
+
function v(e) {
|
|
211
|
+
const t = e;
|
|
212
|
+
return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
|
|
213
|
+
}
|
|
214
|
+
function g(e) {
|
|
215
|
+
return new Promise((t) => setTimeout(t, e));
|
|
216
|
+
}
|
|
217
|
+
async function m(e) {
|
|
218
|
+
const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${s.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
|
|
219
|
+
for (let r = 0; ; r++)
|
|
220
|
+
try {
|
|
221
|
+
const n = await a.request(o);
|
|
222
|
+
return n.authenticated ? { kind: "ok", result: n } : n.error === "rate_limited" || n.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: n };
|
|
223
|
+
} catch (n) {
|
|
224
|
+
if (!v(n) || r >= p.length)
|
|
225
|
+
return { kind: "transient" };
|
|
226
|
+
await g(p[r]);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const d = {
|
|
205
230
|
// 创建弹窗
|
|
206
231
|
createModal() {
|
|
207
232
|
const e = document.createElement("div");
|
|
@@ -246,18 +271,18 @@ const a = {
|
|
|
246
271
|
setTimeout(() => {
|
|
247
272
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
248
273
|
e.length && e.forEach((t, o) => {
|
|
249
|
-
t.addEventListener("input", (
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
}), t.addEventListener("keydown", (
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
}), t.addEventListener("paste", (
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
e[f] && (e[f].value =
|
|
260
|
-
}),
|
|
274
|
+
t.addEventListener("input", (r) => {
|
|
275
|
+
const n = r.target.value.replace(/\D/g, "");
|
|
276
|
+
r.target.value = n, n && o < 5 && e[o + 1].focus(), o === 5 && n && setTimeout(() => w.verifyCode(), 300);
|
|
277
|
+
}), t.addEventListener("keydown", (r) => {
|
|
278
|
+
const n = r.target;
|
|
279
|
+
r.key === "Backspace" && !n.value && o > 0 ? e[o - 1].focus() : r.key === "ArrowLeft" && o > 0 ? (r.preventDefault(), e[o - 1].focus()) : r.key === "ArrowRight" && o < 5 && (r.preventDefault(), e[o + 1].focus());
|
|
280
|
+
}), t.addEventListener("paste", (r) => {
|
|
281
|
+
r.preventDefault();
|
|
282
|
+
const n = r.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
283
|
+
n && (n.split("").forEach((l, f) => {
|
|
284
|
+
e[f] && (e[f].value = l);
|
|
285
|
+
}), n.length === 6 && setTimeout(() => w.verifyCode(), 300));
|
|
261
286
|
});
|
|
262
287
|
});
|
|
263
288
|
}, 100);
|
|
@@ -265,19 +290,19 @@ const a = {
|
|
|
265
290
|
// 显示弹窗
|
|
266
291
|
show() {
|
|
267
292
|
let e = document.getElementById("wx-auth-modal");
|
|
268
|
-
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((
|
|
293
|
+
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.querySelectorAll(".wx-auth-input").forEach((n) => n.value = "");
|
|
269
294
|
const o = e.querySelector(".wx-auth-message");
|
|
270
295
|
o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none");
|
|
271
|
-
const
|
|
272
|
-
|
|
296
|
+
const r = e.querySelector(".wx-auth-btn-primary");
|
|
297
|
+
r && (r.disabled = !1, r.textContent = "登录", r.style.background = ""), e.style.display = "flex", c.isOpen = !0, h.enable({
|
|
273
298
|
modalId: "wx-auth-modal",
|
|
274
|
-
getState: () =>
|
|
299
|
+
getState: () => c,
|
|
275
300
|
onRestore: () => {
|
|
276
301
|
this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
const
|
|
280
|
-
|
|
302
|
+
const n = document.querySelector(".wx-auth-wechat-name");
|
|
303
|
+
n && s.wechatName && (n.textContent = `"${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
|
|
304
|
+
const l = document.querySelector(".wx-auth-input");
|
|
305
|
+
l && l.focus();
|
|
281
306
|
}, 100);
|
|
282
307
|
}
|
|
283
308
|
});
|
|
@@ -285,7 +310,7 @@ const a = {
|
|
|
285
310
|
// 隐藏弹窗
|
|
286
311
|
hide() {
|
|
287
312
|
const e = document.getElementById("wx-auth-modal");
|
|
288
|
-
e && (e.style.display = "none",
|
|
313
|
+
e && (e.style.display = "none", c.isOpen = !1, h.disable());
|
|
289
314
|
},
|
|
290
315
|
// 设置二维码
|
|
291
316
|
setQrCode(e) {
|
|
@@ -310,10 +335,10 @@ const a = {
|
|
|
310
335
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
311
336
|
e.forEach((t) => t.value = ""), e[0] && e[0].focus();
|
|
312
337
|
}
|
|
313
|
-
},
|
|
338
|
+
}, w = {
|
|
314
339
|
// 初始化
|
|
315
340
|
init(e = {}) {
|
|
316
|
-
if (s = { ...
|
|
341
|
+
if (s = { ...y, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
|
|
317
342
|
console.error("[WxAuth] apiBase is required");
|
|
318
343
|
return;
|
|
319
344
|
}
|
|
@@ -321,52 +346,45 @@ const a = {
|
|
|
321
346
|
const t = document.referrer;
|
|
322
347
|
if (t)
|
|
323
348
|
try {
|
|
324
|
-
|
|
349
|
+
u = new URL(t).hostname;
|
|
325
350
|
} catch {
|
|
326
351
|
}
|
|
327
|
-
!
|
|
352
|
+
!u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
|
|
328
353
|
}
|
|
329
354
|
console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
|
|
330
355
|
},
|
|
331
356
|
/**
|
|
332
357
|
* 静默验证(silent 模式专用)
|
|
333
358
|
* - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
|
|
334
|
-
* - cookie 无效 / 不存在 →
|
|
359
|
+
* - cookie 无效 / 不存在 → 不清 cookie、不弹窗,仅返回 false
|
|
360
|
+
* (2026-08-28:不再 deleteCookie。失效 cookie 保留,供后端识别"有凭证但
|
|
361
|
+
* 失效"(取关)→ 返回 401 → 前端弹认证弹窗;后端通过有无 cookie 区分
|
|
362
|
+
* "页面用户取关"(401)与"无凭证爬虫"(蜜罐假数据))
|
|
335
363
|
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
336
364
|
*/
|
|
337
365
|
async silentCheck() {
|
|
338
366
|
const e = a.getToken();
|
|
339
367
|
if (!e) return !1;
|
|
340
|
-
const t =
|
|
341
|
-
|
|
342
|
-
const n = await a.request(
|
|
343
|
-
`${s.apiBase}/api/auth/check?${o}${t}`
|
|
344
|
-
);
|
|
345
|
-
return n.authenticated ? (n.token && a.setToken(n.token), this.onVerified(n.user), !0) : (a.clearToken(), !1);
|
|
346
|
-
} catch (n) {
|
|
347
|
-
return console.error("[WxAuth] silentCheck 请求失败:", n), !1;
|
|
348
|
-
}
|
|
368
|
+
const t = await m(e);
|
|
369
|
+
return t.kind === "ok" ? (t.result.token && a.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
|
|
349
370
|
},
|
|
350
371
|
// 自动检测凭证并验证(内部使用)
|
|
351
372
|
async autoCheck() {
|
|
352
373
|
const e = a.getToken();
|
|
353
374
|
if (!e)
|
|
354
375
|
return this.showAuthModal(), !1;
|
|
355
|
-
const t =
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
} catch (n) {
|
|
362
|
-
return console.error("[WxAuth] 自动验证失败:", n), this.showAuthModal(), !1;
|
|
363
|
-
}
|
|
376
|
+
const t = await m(e);
|
|
377
|
+
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && a.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
|
|
378
|
+
code: "server_error",
|
|
379
|
+
retryable: !0,
|
|
380
|
+
message: "登录服务暂时不可用,请稍后重试"
|
|
381
|
+
}), !1) : (this.showAuthModal(), !1);
|
|
364
382
|
},
|
|
365
383
|
// 显示认证弹窗(内部使用)
|
|
366
384
|
async showAuthModal() {
|
|
367
385
|
d.show();
|
|
368
386
|
try {
|
|
369
|
-
const t =
|
|
387
|
+
const t = u ? `?siteId=${encodeURIComponent(u)}` : "", o = await a.request(
|
|
370
388
|
`${s.apiBase}/api/sdk/config${t}`
|
|
371
389
|
);
|
|
372
390
|
o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
|
|
@@ -384,19 +402,19 @@ const a = {
|
|
|
384
402
|
// 凭证仅签名 Token(Cookie 优先 + localStorage 兜底),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
|
|
385
403
|
async requireAuth() {
|
|
386
404
|
const e = a.getToken();
|
|
387
|
-
if (e)
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
405
|
+
if (e) {
|
|
406
|
+
const t = await m(e);
|
|
407
|
+
if (t.kind === "ok")
|
|
408
|
+
return console.log("[WxAuth] 已认证(凭证)"), t.result.token && a.setToken(t.result.token), this.onVerified(t.result.user), !0;
|
|
409
|
+
if (t.kind === "transient")
|
|
410
|
+
return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
|
|
411
|
+
code: "server_error",
|
|
412
|
+
retryable: !0,
|
|
413
|
+
message: "登录服务暂时不可用,请稍后重试"
|
|
414
|
+
}), !1;
|
|
415
|
+
}
|
|
398
416
|
return await this.showAuthModal(), new Promise((t) => {
|
|
399
|
-
|
|
417
|
+
c.resolveAuth = t;
|
|
400
418
|
});
|
|
401
419
|
},
|
|
402
420
|
// 验证验证码
|
|
@@ -411,21 +429,27 @@ const a = {
|
|
|
411
429
|
);
|
|
412
430
|
t && (t.disabled = !0, t.textContent = "登录中...");
|
|
413
431
|
try {
|
|
414
|
-
const o =
|
|
432
|
+
const o = u ? `&siteId=${encodeURIComponent(u)}` : "", r = await a.request(
|
|
415
433
|
`${s.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
416
434
|
);
|
|
417
|
-
|
|
418
|
-
this.onVerified(
|
|
419
|
-
}, 500)) : (d.showMessage(
|
|
420
|
-
|
|
421
|
-
|
|
435
|
+
r.authenticated ? (r.token && a.setToken(r.token), t && (t.textContent = "✅ 已登录", t.style.background = "#07C160"), setTimeout(() => {
|
|
436
|
+
this.onVerified(r.user), this.close(!0);
|
|
437
|
+
}, 500)) : (d.showMessage(
|
|
438
|
+
r.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
|
|
439
|
+
"error"
|
|
440
|
+
), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
|
|
441
|
+
} catch (o) {
|
|
442
|
+
d.showMessage(
|
|
443
|
+
v(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
|
|
444
|
+
"error"
|
|
445
|
+
), t && (t.disabled = !1, t.textContent = "登录");
|
|
422
446
|
}
|
|
423
447
|
},
|
|
424
448
|
// 关闭弹窗
|
|
425
449
|
// skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
|
|
426
450
|
// (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
|
|
427
451
|
close(e = !1) {
|
|
428
|
-
d.hide(),
|
|
452
|
+
d.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
|
|
429
453
|
},
|
|
430
454
|
// 清空本地认证凭证(双重删除:Cookie + localStorage)
|
|
431
455
|
// 用于"退出登录 / 清空认证状态"按钮。
|
|
@@ -441,6 +465,8 @@ const a = {
|
|
|
441
465
|
// (根治「A 域退出、B 域还能用」的双写恢复问题)。
|
|
442
466
|
// 幂等安全:网络失败 /* 后端不可达 */ 时静默降级为仅本地清理(clearToken),
|
|
443
467
|
// 不阻塞退出流程;token 无效也会返回 success(本地照常清理)。
|
|
468
|
+
// 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
|
|
469
|
+
// 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
|
|
444
470
|
async revoke() {
|
|
445
471
|
const e = a.getToken();
|
|
446
472
|
if (e)
|
|
@@ -459,14 +485,14 @@ const a = {
|
|
|
459
485
|
},
|
|
460
486
|
// 验证成功回调
|
|
461
487
|
onVerified(e) {
|
|
462
|
-
console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e),
|
|
488
|
+
console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), c.resolveAuth && (c.resolveAuth(!0), c.resolveAuth = null);
|
|
463
489
|
},
|
|
464
490
|
// 错误回调
|
|
465
491
|
onError(e) {
|
|
466
492
|
console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
|
|
467
493
|
}
|
|
468
494
|
};
|
|
469
|
-
typeof window < "u" && (window.WxAuth = Object.freeze(
|
|
495
|
+
typeof window < "u" && (window.WxAuth = Object.freeze(w));
|
|
470
496
|
export {
|
|
471
|
-
|
|
497
|
+
w as WxAuth
|
|
472
498
|
};
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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-input{background:#2a2a2a;border-color:#444;color:#e5e5e5}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16040}.wx-auth-input:disabled{background:#333;color:#888}.wx-auth-qrcode-container{background:#2a2a2a}.wx-auth-btn-secondary{background:#2a2a2a;color:#e5e5e5}.wx-auth-btn-secondary:hover:not(:disabled){background:#333}.wx-auth-message-info{background:#0d2a1f;color:#7cc4ff;border-color:#1f4a6b}.wx-auth-message-success{background:#0d2a1a;color:#4ade80;border-color:#1f6b3a}.wx-auth-message-error{background:#2a0d0d;color:#f87171;border-color:#6b1f1f}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(p);const
|
|
3
|
-
<div class="wx-auth-overlay" ${
|
|
2
|
+
/*$vite$:1*/`,document.head.appendChild(p);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(i.isProtected||typeof window>"u")return;i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!0,i.restorePending=!1,i.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const l=r;if(l.id===e.modalId||l.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.safeRestore(e);return}}}),i.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!i.isProtected)return;const{getState:o}=e;if(!o().isOpen){i.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||h.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?h.isHidden(n):null}),h.safeRestore(e)),i.isProtected&&(i.rafId=requestAnimationFrame(t))};i.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){i.observer&&(i.observer.disconnect(),i.observer=null),i.rafId!==null&&(cancelAnimationFrame(i.rafId),i.rafId=null),i.isProtected=!1,i.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!i.restorePending){i.restorePending=!0;try{h.restoreFn(e)}finally{requestAnimationFrame(()=>{i.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},g={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...g},u="",c={isOpen:!1,resolveAuth:null,currentStep:"qr"};function k(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const s={getRootDomain(){return k(window.location.hostname)},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+365*24*60*60*1e3);const n=this.getRootDomain(),r=n?`;domain=${n}`:"",x=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${r}${x};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",r=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`},get storageKey(){return"wxauth-token"},getToken(){const e=this.getCookie("wxauth-token");if(e)return e;try{return window.localStorage.getItem(this.storageKey)}catch{return null}},setToken(e){this.setCookie("wxauth-token",e);try{window.localStorage.setItem(this.storageKey,e)}catch{}},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem(this.storageKey)}catch{}},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},y=[1e3,3e3];function b(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function v(e){return new Promise(t=>setTimeout(t,e))}async function m(e){const t=u?`&siteId=${encodeURIComponent(u)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await s.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!b(r)||n>=y.length)return{kind:"transient"};await v(y[n])}}const d={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
|
|
3
|
+
<div class="wx-auth-overlay" ${a.required?'onclick="event.preventDefault()"':""}></div>
|
|
4
4
|
<div class="wx-auth-content">
|
|
5
5
|
<div class="wx-auth-header">
|
|
6
6
|
<div class="wx-auth-title">微信登录</div>
|
|
@@ -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
|
|
34
|
+
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>w.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;n.key==="Backspace"&&!r.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((l,x)=>{e[x]&&(e[x].value=l)}),r.length===6&&setTimeout(()=>w.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(r=>r.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),e.style.display="flex",c.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>c,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&a.wechatName&&(r.textContent=`"${a.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const l=document.querySelector(".wx-auth-input");l&&l.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",c.isOpen=!1,h.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},w={init(e={}){if(a={...g,...e},!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{u=new URL(t).hostname}catch{}!u&&window.location.hostname&&(u=window.location.hostname),u||(u="default"),console.log("[WxAuth] 自动获取 siteId:",u)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=s.getToken();if(!e)return!1;const t=await m(e);return t.kind==="ok"?(t.result.token&&s.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=s.getToken();if(!e)return this.showAuthModal(),!1;const t=await m(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&s.setToken(t.result.token),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(){d.show();try{const t=u?`?siteId=${encodeURIComponent(u)}`:"",o=await s.request(`${a.apiBase}/api/sdk/config${t}`);o.wechatName&&!a.wechatName&&(a.wechatName=o.wechatName),o.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}a.qrcodeUrl&&d.setQrCode(a.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&a.wechatName&&(e.textContent=`"${a.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=s.getToken();if(e){const t=await m(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&s.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{c.resolveAuth=t})},async verifyCode(){const e=d.getVerifyCode();if(!e||e.length!==6){d.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="登录中...");try{const o=u?`&siteId=${encodeURIComponent(u)}`:"",n=await s.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token&&s.setToken(n.token),t&&(t.textContent="✅ 已登录",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(d.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),d.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){d.showMessage(b(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){d.hide(),c.resolveAuth&&(c.resolveAuth(!1),c.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){s.clearToken()},async revoke(){const e=s.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof a.onVerified=="function"&&a.onVerified(e),c.resolveAuth&&(c.resolveAuth(!0),c.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(w)),f.WxAuth=w,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
|