wx-auth-sdk 1.2.43 → 1.2.44
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 +15 -0
- package/dist/wx-auth.js +230 -165
- package/dist/wx-auth.umd.js +2 -2
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -14,6 +14,21 @@ export declare interface RequireAuthOptions {
|
|
|
14
14
|
|
|
15
15
|
export declare const WxAuth: {
|
|
16
16
|
init(options?: Partial<WxAuthConfig>): void;
|
|
17
|
+
/**
|
|
18
|
+
* 取当前匿名票据(同步,不触发签发)。没有或临期返回 null——
|
|
19
|
+
* 一般业务直接用 getOrCreateAnonTicket,本方法供想自己控制签发时机的接入方。
|
|
20
|
+
*/
|
|
21
|
+
getAnonTicket(): string | null;
|
|
22
|
+
/**
|
|
23
|
+
* 取匿名票据,没有/临期则自动向 wx-auth 签发口要一张(并发调用合并为一次)。
|
|
24
|
+
* 签发失败(bot UA 403 / 限流 429 / 断网)返回 null——fail-open:票据系统
|
|
25
|
+
* 故障不阻断业务,是否放行无票请求由接入方自己定夺。
|
|
26
|
+
*
|
|
27
|
+
* 建议在建立 SSE 连接前 await 本方法,把返回值拼在 URL 上:
|
|
28
|
+
* const at = await WxAuth.getOrCreateAnonTicket();
|
|
29
|
+
* const es = new EventSource(`${url}${url.includes("?") ? "&" : "?"}at=${at}`);
|
|
30
|
+
*/
|
|
31
|
+
getOrCreateAnonTicket(): Promise<string | null>;
|
|
17
32
|
/**
|
|
18
33
|
* 静默验证(silent 模式专用)
|
|
19
34
|
* - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
|
package/dist/wx-auth.js
CHANGED
|
@@ -9,12 +9,12 @@ const s = {
|
|
|
9
9
|
*/
|
|
10
10
|
enable(e) {
|
|
11
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((
|
|
13
|
-
for (const
|
|
14
|
-
if (
|
|
15
|
-
for (const
|
|
16
|
-
if (
|
|
17
|
-
const l =
|
|
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((n) => {
|
|
13
|
+
for (const o of n)
|
|
14
|
+
if (o.type === "childList")
|
|
15
|
+
for (const r of o.removedNodes) {
|
|
16
|
+
if (r.nodeType !== Node.ELEMENT_NODE) continue;
|
|
17
|
+
const l = r;
|
|
18
18
|
if (l.id === e.modalId || l.querySelector?.(`#${e.modalId}`)) {
|
|
19
19
|
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), p.safeRestore(e);
|
|
20
20
|
return;
|
|
@@ -26,15 +26,15 @@ const s = {
|
|
|
26
26
|
});
|
|
27
27
|
const t = () => {
|
|
28
28
|
if (!s.isProtected) return;
|
|
29
|
-
const { getState:
|
|
30
|
-
if (!
|
|
29
|
+
const { getState: n } = e;
|
|
30
|
+
if (!n().isOpen) {
|
|
31
31
|
s.rafId = null;
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
34
|
-
const
|
|
35
|
-
(!
|
|
34
|
+
const o = document.getElementById(e.modalId);
|
|
35
|
+
(!o || !o.isConnected || p.isHidden(o)) && (console.warn(
|
|
36
36
|
"[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
|
|
37
|
-
{ has: !!
|
|
37
|
+
{ has: !!o, connected: o?.isConnected, hidden: o ? p.isHidden(o) : null }
|
|
38
38
|
), p.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
|
|
39
39
|
};
|
|
40
40
|
s.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
|
|
@@ -77,16 +77,16 @@ const s = {
|
|
|
77
77
|
* 恢复弹窗
|
|
78
78
|
*/
|
|
79
79
|
restoreFn(e) {
|
|
80
|
-
const { modalId: t, getState:
|
|
81
|
-
if (!
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
84
|
-
|
|
80
|
+
const { modalId: t, getState: n, onRestore: o } = e;
|
|
81
|
+
if (!n().isOpen) return;
|
|
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
|
+
o();
|
|
88
88
|
}
|
|
89
|
-
},
|
|
89
|
+
}, E = {
|
|
90
90
|
apiBase: "https://wx-auth.shenzjd.com",
|
|
91
91
|
// 后端API地址(默认值)
|
|
92
92
|
onVerified: null,
|
|
@@ -106,15 +106,17 @@ const s = {
|
|
|
106
106
|
silent: !1
|
|
107
107
|
// 默认不静默
|
|
108
108
|
};
|
|
109
|
-
let a = { ...
|
|
109
|
+
let a = { ...E }, d = "", k = "", y = null, x = null;
|
|
110
|
+
const A = "wxauth-anon", I = 10080 * 60 * 1e3;
|
|
111
|
+
let i = {
|
|
110
112
|
isOpen: !1,
|
|
111
113
|
resolveAuth: null,
|
|
112
114
|
currentStep: "qr",
|
|
113
115
|
required: !!a.required,
|
|
114
116
|
mpSession: null
|
|
115
117
|
}, f = "mp", h = 0;
|
|
116
|
-
const
|
|
117
|
-
function
|
|
118
|
+
const O = 1440 * 60 * 1e3;
|
|
119
|
+
function $(e) {
|
|
118
120
|
try {
|
|
119
121
|
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
120
122
|
return "";
|
|
@@ -124,28 +126,28 @@ function E(e) {
|
|
|
124
126
|
return "";
|
|
125
127
|
}
|
|
126
128
|
}
|
|
127
|
-
const
|
|
129
|
+
const u = {
|
|
128
130
|
getRootDomain() {
|
|
129
|
-
return
|
|
131
|
+
return $(window.location.hostname);
|
|
130
132
|
},
|
|
131
133
|
// 获取Cookie
|
|
132
134
|
getCookie(e) {
|
|
133
|
-
const
|
|
134
|
-
return
|
|
135
|
+
const n = `; ${document.cookie}`.split(`; ${e}=`);
|
|
136
|
+
return n.length === 2 && n.pop()?.split(";").shift() || null;
|
|
135
137
|
},
|
|
136
138
|
// Cookie 写入底层(domainStr 传空串 = host-only,落在当前 host 本域)
|
|
137
|
-
writeCookieRaw(e, t, o, r
|
|
138
|
-
const l =
|
|
139
|
-
document.cookie = `${e}=${
|
|
139
|
+
writeCookieRaw(e, t, n, o, r = !1) {
|
|
140
|
+
const l = o ? `;domain=${o}` : "", M = window.location.protocol === "https:" ? ";Secure" : "", T = r ? ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : n !== void 0 ? `;expires=${new Date(Date.now() + n).toUTCString()}` : "";
|
|
141
|
+
document.cookie = `${e}=${r ? "" : t};path=/${l}${T}${M};SameSite=Strict`;
|
|
140
142
|
},
|
|
141
143
|
// 设置Cookie(2026-09-04:不传 maxAgeMs 时仍是会话 Cookie —— 浏览器关闭即失效;
|
|
142
144
|
// 传入 maxAgeMs 则写持久 Cookie;自动设置根域名实现跨子域共享)
|
|
143
145
|
// 2026-09-06:根域写入后回读校验——公共后缀域名(vercel.app / netlify.app /
|
|
144
146
|
// pages.dev 等共享托管域,均在 Public Suffix List)禁止写 domain Cookie,
|
|
145
147
|
// 浏览器会静默丢弃导致登录态存不下来;此时降级为 host-only(落当前 host 本域)
|
|
146
|
-
setCookie(e, t,
|
|
147
|
-
const
|
|
148
|
-
this.writeCookieRaw(e, t,
|
|
148
|
+
setCookie(e, t, n) {
|
|
149
|
+
const o = this.getRootDomain();
|
|
150
|
+
this.writeCookieRaw(e, t, n, o), o && !this.getCookie(e) && this.writeCookieRaw(e, t, n, "");
|
|
149
151
|
},
|
|
150
152
|
// 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
|
|
151
153
|
// 2026-09-06:公共后缀域名降级场景下 cookie 可能是 host-only 写入的,
|
|
@@ -154,24 +156,24 @@ const c = {
|
|
|
154
156
|
const t = this.getRootDomain();
|
|
155
157
|
this.writeCookieRaw(e, "", void 0, t, !0), t && this.writeCookieRaw(e, "", void 0, "", !0);
|
|
156
158
|
},
|
|
157
|
-
// ===== 签名 Token 存储(
|
|
158
|
-
// 登录态策略:setToken 写
|
|
159
|
-
//
|
|
160
|
-
//
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
// 不引入 localStorage
|
|
165
|
-
//
|
|
159
|
+
// ===== 签名 Token 存储(1 天持久 Cookie、无滑动续期,2026-09-24)=====
|
|
160
|
+
// 登录态策略:setToken 写 1 天持久 Cookie;silentCheck / autoCheck 校验成功
|
|
161
|
+
// **不回写 token**(回写 = 重置 expires = 滑动续期)——用户登录后 24 小时固定
|
|
162
|
+
// 过期,每天访问都需重新扫码,保证「确认登录 → 小程序激励广告」每天一次曝光。
|
|
163
|
+
// 沿革:2026-08-30 会话级 → 2026-09-04 放宽 3 天 → 2026-09-05 会话级 →
|
|
164
|
+
// 2026-09-19 恢复 7 天 + 滑动续期(当时积分按动作收费)→ 2026-09-24 回到
|
|
165
|
+
// 1 天不续期(积分已删,变现回到登录链路广告,重登次数重新成为收入杠杆)。
|
|
166
|
+
// 不引入 localStorage 备份(备份会让登录态越过 Cookie 过期时间存活,与
|
|
167
|
+
// 「每天重登」直接冲突);clearToken 保留对旧版本备份 key 的防御性清理。
|
|
166
168
|
// 存储的是签名 Token(HMAC,不可伪造),而非明文 openid(永久凭证)。
|
|
167
169
|
// 注意:Cookie 是根域共享;localStorage 按站点隔离,且不再读取。
|
|
168
170
|
// 读取:wxauth-token Cookie(旧版本 localStorage 备份不再兜底)
|
|
169
171
|
getToken() {
|
|
170
172
|
return this.getCookie("wxauth-token");
|
|
171
173
|
},
|
|
172
|
-
// 写入:持久 Cookie(
|
|
174
|
+
// 写入:持久 Cookie(1 天;只在真登录路径调用——校验成功不再回写续期)
|
|
173
175
|
setToken(e) {
|
|
174
|
-
this.setCookie("wxauth-token", e,
|
|
176
|
+
this.setCookie("wxauth-token", e, O);
|
|
175
177
|
},
|
|
176
178
|
// 删除:清 Cookie + 防御性清理旧版本 localStorage 备份残留
|
|
177
179
|
// (同时清掉明文 openid Cookie —— 防御性清理,服务端已下线 openid 通道 2026-08-26)
|
|
@@ -187,7 +189,7 @@ const c = {
|
|
|
187
189
|
// (Cookie 被清理/写入失败时从镜像恢复,避免设备身份漂移)。
|
|
188
190
|
// 注意:这是设备身份不是凭证——退出登录(clearToken/revoke)不清除它。
|
|
189
191
|
getOrCreateDeviceId() {
|
|
190
|
-
if (
|
|
192
|
+
if (k) return k;
|
|
191
193
|
let e = this.getCookie("wxauth-device");
|
|
192
194
|
if (!e)
|
|
193
195
|
try {
|
|
@@ -199,15 +201,52 @@ const c = {
|
|
|
199
201
|
if (typeof crypto < "u" && crypto.getRandomValues)
|
|
200
202
|
crypto.getRandomValues(t);
|
|
201
203
|
else
|
|
202
|
-
for (let
|
|
203
|
-
e = Array.from(t).map((
|
|
204
|
+
for (let n = 0; n < 16; n++) t[n] = Math.floor(Math.random() * 256);
|
|
205
|
+
e = Array.from(t).map((n) => n.toString(16).padStart(2, "0")).join("");
|
|
204
206
|
}
|
|
205
207
|
this.setCookie("wxauth-device", e, 365 * 86400 * 1e3);
|
|
206
208
|
try {
|
|
207
209
|
window.localStorage.setItem("wxauth-device", e);
|
|
208
210
|
} catch {
|
|
209
211
|
}
|
|
210
|
-
return
|
|
212
|
+
return k = e, e;
|
|
213
|
+
},
|
|
214
|
+
// ===== 匿名票据(2026-09-24)=====
|
|
215
|
+
// 从 localStorage 读存储的票据(结构校验,坏数据视为无票)
|
|
216
|
+
readStoredAnonTicket() {
|
|
217
|
+
let e = null;
|
|
218
|
+
try {
|
|
219
|
+
e = window.localStorage.getItem(A);
|
|
220
|
+
} catch {
|
|
221
|
+
}
|
|
222
|
+
if (!e) return null;
|
|
223
|
+
try {
|
|
224
|
+
const t = JSON.parse(e);
|
|
225
|
+
if (typeof t.ticket != "string" || typeof t.anonId != "string" || typeof t.expMs != "number")
|
|
226
|
+
return null;
|
|
227
|
+
const n = t.ticket.split(".");
|
|
228
|
+
return n.length !== 7 || n[0] !== "v1" || parseInt(n[5], 10) * 1e3 !== t.expMs ? null : { ticket: t.ticket, anonId: t.anonId, expMs: t.expMs };
|
|
229
|
+
} catch {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
// 持久写入(localStorage;写失败忽略,本次会话内内存缓存仍可用)
|
|
234
|
+
storeAnonTicket(e, t, n) {
|
|
235
|
+
try {
|
|
236
|
+
window.localStorage.setItem(A, JSON.stringify({ ticket: e, anonId: t, expMs: n }));
|
|
237
|
+
} catch {
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
// 调 wx-auth 签发口拿一张新票(aud = 当前页面 hostname,票与站点绑定)。
|
|
241
|
+
// 403(bot UA) / 429(限流) / 网络失败会抛错,由调用方 catch(fail-open)
|
|
242
|
+
async requestAnonTicket() {
|
|
243
|
+
const e = (a.apiBase || "").replace(/\/$/, "");
|
|
244
|
+
if (!e || typeof window > "u") return null;
|
|
245
|
+
const t = await u.request(`${e}/api/auth/anon`, {
|
|
246
|
+
method: "POST",
|
|
247
|
+
body: { aud: window.location.hostname }
|
|
248
|
+
});
|
|
249
|
+
return !t || typeof t.ticket != "string" || typeof t.anonId != "string" || typeof t.expiresIn != "number" ? null : { ticket: t.ticket, anonId: t.anonId, expMs: Date.now() + t.expiresIn * 1e3 };
|
|
211
250
|
},
|
|
212
251
|
// 发送请求
|
|
213
252
|
// 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
|
|
@@ -215,7 +254,7 @@ const c = {
|
|
|
215
254
|
// body 接受任意可 JSON 序列化对象(实现统一 JSON.stringify,非 BodyInit)
|
|
216
255
|
async request(e, t = {}) {
|
|
217
256
|
try {
|
|
218
|
-
const
|
|
257
|
+
const n = await fetch(e, {
|
|
219
258
|
method: t.method || "GET",
|
|
220
259
|
headers: {
|
|
221
260
|
"Content-Type": "application/json",
|
|
@@ -224,14 +263,14 @@ const c = {
|
|
|
224
263
|
body: t.body ? JSON.stringify(t.body) : null,
|
|
225
264
|
credentials: "include"
|
|
226
265
|
});
|
|
227
|
-
if (!
|
|
228
|
-
const
|
|
229
|
-
throw
|
|
266
|
+
if (!n.ok) {
|
|
267
|
+
const o = new Error(`HTTP ${n.status}`);
|
|
268
|
+
throw o.status = n.status, o;
|
|
230
269
|
}
|
|
231
|
-
return await
|
|
232
|
-
} catch (
|
|
233
|
-
const
|
|
234
|
-
throw
|
|
270
|
+
return await n.json();
|
|
271
|
+
} catch (n) {
|
|
272
|
+
const o = n;
|
|
273
|
+
throw o.status === void 0 && (o.isNetworkError = !0), console.error("[WxAuth] Request error:", n), o;
|
|
235
274
|
}
|
|
236
275
|
},
|
|
237
276
|
// 生成6位验证码输入框HTML
|
|
@@ -241,60 +280,60 @@ const c = {
|
|
|
241
280
|
e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
|
|
242
281
|
return e += "</div>", e;
|
|
243
282
|
}
|
|
244
|
-
},
|
|
245
|
-
function
|
|
283
|
+
}, C = [1e3, 3e3];
|
|
284
|
+
function b(e) {
|
|
246
285
|
const t = e;
|
|
247
286
|
return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
|
|
248
287
|
}
|
|
249
|
-
function
|
|
288
|
+
function g(e) {
|
|
250
289
|
return new Promise((t) => setTimeout(t, e));
|
|
251
290
|
}
|
|
252
|
-
const
|
|
253
|
-
function
|
|
291
|
+
const D = 3e3, P = 2e3, R = 3e3;
|
|
292
|
+
function S() {
|
|
254
293
|
h++;
|
|
255
294
|
}
|
|
256
|
-
async function
|
|
257
|
-
if (await
|
|
295
|
+
async function q(e) {
|
|
296
|
+
if (await g(D), !(e !== h || !i.isOpen)) {
|
|
258
297
|
for (; e === h && i.isOpen; ) {
|
|
259
298
|
const t = i.mpSession;
|
|
260
299
|
if (!t || Date.now() >= t.expiresAt) break;
|
|
261
300
|
try {
|
|
262
|
-
const
|
|
301
|
+
const n = await u.request(
|
|
263
302
|
`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
|
|
264
303
|
);
|
|
265
304
|
if (e !== h) return;
|
|
266
|
-
if (
|
|
267
|
-
m.completeLogin(
|
|
305
|
+
if (n.status === "confirmed" && n.token) {
|
|
306
|
+
m.completeLogin(n);
|
|
268
307
|
return;
|
|
269
308
|
}
|
|
270
|
-
if (
|
|
309
|
+
if (n.status === "expired") {
|
|
271
310
|
i.mpSession = null;
|
|
272
311
|
break;
|
|
273
312
|
}
|
|
274
|
-
} catch (
|
|
313
|
+
} catch (n) {
|
|
275
314
|
if (e !== h) return;
|
|
276
|
-
if (!
|
|
277
|
-
await
|
|
315
|
+
if (!b(n)) break;
|
|
316
|
+
await g(R);
|
|
278
317
|
continue;
|
|
279
318
|
}
|
|
280
|
-
await
|
|
319
|
+
await g(P);
|
|
281
320
|
}
|
|
282
|
-
e === h && i.isOpen && f === "mp" &&
|
|
321
|
+
e === h && i.isOpen && f === "mp" && c.showMpExpired();
|
|
283
322
|
}
|
|
284
323
|
}
|
|
285
324
|
async function v(e) {
|
|
286
|
-
const t = d ? `&siteId=${encodeURIComponent(d)}` : "",
|
|
287
|
-
for (let
|
|
325
|
+
const t = d ? `&siteId=${encodeURIComponent(d)}` : "", n = `${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
|
|
326
|
+
for (let o = 0; ; o++)
|
|
288
327
|
try {
|
|
289
|
-
const
|
|
290
|
-
return
|
|
291
|
-
} catch (
|
|
292
|
-
if (!
|
|
328
|
+
const r = await u.request(n);
|
|
329
|
+
return r.authenticated ? { kind: "ok", result: r } : r.error === "rate_limited" || r.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: r };
|
|
330
|
+
} catch (r) {
|
|
331
|
+
if (!b(r) || o >= C.length)
|
|
293
332
|
return { kind: "transient" };
|
|
294
|
-
await
|
|
333
|
+
await g(C[o]);
|
|
295
334
|
}
|
|
296
335
|
}
|
|
297
|
-
const
|
|
336
|
+
const c = {
|
|
298
337
|
// 创建弹窗
|
|
299
338
|
// 形态固定为双 tab(2026-08-30 去掉 mpScanEnabled 门控):形态不依赖 config,
|
|
300
339
|
// 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab)结构上不存在。
|
|
@@ -302,7 +341,7 @@ const u = {
|
|
|
302
341
|
createModal(e) {
|
|
303
342
|
const t = document.createElement("div");
|
|
304
343
|
t.id = "wx-auth-modal", t.className = "wx-auth-modal", t.classList.add(e ? "wx-auth-required" : "wx-auth-optional");
|
|
305
|
-
const
|
|
344
|
+
const n = "", o = "", r = `<div class="wx-auth-panel wx-auth-panel-mp">
|
|
306
345
|
<div class="wx-auth-qrcode-container wx-auth-mp-container">
|
|
307
346
|
<div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
|
|
308
347
|
<img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
|
|
@@ -321,13 +360,13 @@ const u = {
|
|
|
321
360
|
<div class="wx-auth-title">微信登录</div>
|
|
322
361
|
</div>
|
|
323
362
|
<div class="wx-auth-body">
|
|
324
|
-
${
|
|
363
|
+
${n}
|
|
325
364
|
|
|
326
365
|
<!-- 面板一:公众号验证码(临时停用 2026-09-16,内容见上方 codePanelHtml 注释) -->
|
|
327
|
-
${
|
|
366
|
+
${o}
|
|
328
367
|
|
|
329
368
|
<!-- 面板二:小程序扫码(当前唯一登录方式) -->
|
|
330
|
-
${
|
|
369
|
+
${r}
|
|
331
370
|
|
|
332
371
|
<!-- 消息提示 -->
|
|
333
372
|
<div class="wx-auth-message" style="display:none"></div>
|
|
@@ -344,36 +383,36 @@ const u = {
|
|
|
344
383
|
*/
|
|
345
384
|
syncModalShape(e, t) {
|
|
346
385
|
e.classList.remove("wx-auth-required", "wx-auth-optional"), e.classList.add(t ? "wx-auth-required" : "wx-auth-optional");
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
const
|
|
386
|
+
const n = e.querySelector(".wx-auth-overlay");
|
|
387
|
+
n && (n.onclick = t ? (w) => w.preventDefault() : null);
|
|
388
|
+
const o = e.querySelector(".wx-auth-close");
|
|
350
389
|
if (t) {
|
|
351
|
-
|
|
390
|
+
o?.remove();
|
|
352
391
|
return;
|
|
353
392
|
}
|
|
354
|
-
if (
|
|
355
|
-
const
|
|
356
|
-
if (!
|
|
393
|
+
if (o) return;
|
|
394
|
+
const r = e.querySelector(".wx-auth-header");
|
|
395
|
+
if (!r) return;
|
|
357
396
|
const l = document.createElement("button");
|
|
358
|
-
l.type = "button", l.className = "wx-auth-close", l.setAttribute("aria-label", "关闭"), l.textContent = "×", l.addEventListener("click", () => m.close()),
|
|
397
|
+
l.type = "button", l.className = "wx-auth-close", l.setAttribute("aria-label", "关闭"), l.textContent = "×", l.addEventListener("click", () => m.close()), r.appendChild(l);
|
|
359
398
|
},
|
|
360
399
|
// 绑定输入事件
|
|
361
400
|
bindInputEvents() {
|
|
362
401
|
setTimeout(() => {
|
|
363
402
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
364
|
-
e.length && e.forEach((t,
|
|
365
|
-
t.addEventListener("input", (
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
}), t.addEventListener("keydown", (
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
}), t.addEventListener("paste", (
|
|
372
|
-
|
|
373
|
-
const
|
|
374
|
-
|
|
403
|
+
e.length && e.forEach((t, n) => {
|
|
404
|
+
t.addEventListener("input", (o) => {
|
|
405
|
+
const r = o.target.value.replace(/\D/g, "");
|
|
406
|
+
o.target.value = r, r && n < 5 && e[n + 1].focus(), n === 5 && r && setTimeout(() => m.verifyCode(), 300);
|
|
407
|
+
}), t.addEventListener("keydown", (o) => {
|
|
408
|
+
const r = o.target;
|
|
409
|
+
o.key === "Backspace" && !r.value && n > 0 ? e[n - 1].focus() : o.key === "ArrowLeft" && n > 0 ? (o.preventDefault(), e[n - 1].focus()) : o.key === "ArrowRight" && n < 5 && (o.preventDefault(), e[n + 1].focus());
|
|
410
|
+
}), t.addEventListener("paste", (o) => {
|
|
411
|
+
o.preventDefault();
|
|
412
|
+
const r = o.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
413
|
+
r && (r.split("").forEach((l, w) => {
|
|
375
414
|
e[w] && (e[w].value = l);
|
|
376
|
-
}),
|
|
415
|
+
}), r.length === 6 && setTimeout(() => m.verifyCode(), 300));
|
|
377
416
|
});
|
|
378
417
|
});
|
|
379
418
|
}, 100);
|
|
@@ -385,16 +424,16 @@ const u = {
|
|
|
385
424
|
show(e) {
|
|
386
425
|
const t = e ?? !!a.required;
|
|
387
426
|
i.required = t;
|
|
388
|
-
let
|
|
389
|
-
|
|
390
|
-
const
|
|
391
|
-
|
|
427
|
+
let n = document.getElementById("wx-auth-modal");
|
|
428
|
+
n ? this.syncModalShape(n, t) : n = this.createModal(t);
|
|
429
|
+
const o = n.querySelector(".wx-auth-message");
|
|
430
|
+
o && (o.textContent = "", o.className = "wx-auth-message", o.style.display = "none"), S(), i.mpSession = null, n.style.display = "flex", i.isOpen = !0, p.enable({
|
|
392
431
|
modalId: "wx-auth-modal",
|
|
393
432
|
getState: () => i,
|
|
394
433
|
onRestore: () => {
|
|
395
434
|
this.createModal(i.required), a.qrcodeUrl && this.setQrCode(a.qrcodeUrl);
|
|
396
|
-
const
|
|
397
|
-
|
|
435
|
+
const r = document.querySelector(".wx-auth-wechat-name");
|
|
436
|
+
r && a.wechatName && (r.textContent = `"${a.wechatName}"`), this.bindInputEvents(), f === "mp" && m.switchMode("mp"), setTimeout(() => {
|
|
398
437
|
const l = document.querySelector(".wx-auth-input");
|
|
399
438
|
l && l.focus();
|
|
400
439
|
}, 100);
|
|
@@ -404,7 +443,7 @@ const u = {
|
|
|
404
443
|
// 隐藏弹窗
|
|
405
444
|
hide() {
|
|
406
445
|
const e = document.getElementById("wx-auth-modal");
|
|
407
|
-
e && (e.style.display = "none", i.isOpen = !1,
|
|
446
|
+
e && (e.style.display = "none", i.isOpen = !1, S(), i.mpSession = null, p.disable());
|
|
408
447
|
},
|
|
409
448
|
// 设置二维码
|
|
410
449
|
setQrCode(e) {
|
|
@@ -415,35 +454,35 @@ const u = {
|
|
|
415
454
|
// ===== 小程序扫码面板(2026-08-29)=====
|
|
416
455
|
// 展示小程序码(隐藏 loading 与过期遮罩,保持画面干净)
|
|
417
456
|
setMpQr(e) {
|
|
418
|
-
const t = document.getElementById("wx-auth-modal"),
|
|
419
|
-
|
|
457
|
+
const t = document.getElementById("wx-auth-modal"), n = t?.querySelector(".wx-auth-mp-qrcode"), o = t?.querySelector(".wx-auth-mp-loading");
|
|
458
|
+
n && (n.src = e, n.style.display = "block", o && (o.style.display = "none"), this.setMpExpiredVisible(!1), this.setMpStatus("", !1));
|
|
420
459
|
},
|
|
421
460
|
// 过期遮罩显示/隐藏:盖在二维码上(「二维码已过期」+ 绿色刷新按钮)
|
|
422
461
|
setMpExpiredVisible(e) {
|
|
423
|
-
const
|
|
424
|
-
|
|
462
|
+
const n = document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");
|
|
463
|
+
n && (n.style.display = e ? "flex" : "none");
|
|
425
464
|
},
|
|
426
465
|
// 更新扫码面板状态文案;text 为空 = 隐藏状态行;spinner=true 时回列出码 loading
|
|
427
466
|
setMpStatus(e, t) {
|
|
428
|
-
const
|
|
429
|
-
|
|
430
|
-
const
|
|
431
|
-
if (
|
|
432
|
-
const l =
|
|
467
|
+
const n = document.getElementById("wx-auth-modal"), o = n?.querySelector(".wx-auth-mp-status");
|
|
468
|
+
o && (o.textContent = e, o.style.display = e ? "block" : "none");
|
|
469
|
+
const r = n?.querySelector(".wx-auth-mp-loading");
|
|
470
|
+
if (r && (r.style.display = t ? "flex" : "none"), t) {
|
|
471
|
+
const l = n?.querySelector(".wx-auth-mp-qrcode");
|
|
433
472
|
l && (l.style.display = "none");
|
|
434
473
|
}
|
|
435
474
|
},
|
|
436
475
|
// 二维码过期/失效:遮罩盖住旧码,用户点「刷新二维码」重新出码
|
|
437
476
|
// text:遮罩文案(出码失败时复用同一遮罩,让用户有重试入口)
|
|
438
477
|
showMpExpired(e = "二维码已过期") {
|
|
439
|
-
const
|
|
440
|
-
|
|
478
|
+
const n = document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired-text");
|
|
479
|
+
n && (n.textContent = e), this.setMpExpiredVisible(!0);
|
|
441
480
|
},
|
|
442
481
|
// 显示消息
|
|
443
482
|
showMessage(e, t = "info") {
|
|
444
|
-
const
|
|
445
|
-
|
|
446
|
-
|
|
483
|
+
const n = document.querySelector(".wx-auth-message");
|
|
484
|
+
n && (n.textContent = e, n.className = `wx-auth-message wx-auth-message-${t}`, n.style.display = "block", setTimeout(() => {
|
|
485
|
+
n.textContent === e && (n.style.display = "none");
|
|
447
486
|
}, 3e3));
|
|
448
487
|
},
|
|
449
488
|
// 获取验证码
|
|
@@ -459,7 +498,7 @@ const u = {
|
|
|
459
498
|
}, m = {
|
|
460
499
|
// 初始化
|
|
461
500
|
init(e = {}) {
|
|
462
|
-
if (a = { ...
|
|
501
|
+
if (a = { ...E, ...e }, !a.apiBase && typeof window < "u" && (a.apiBase = window.location.origin), !a.apiBase) {
|
|
463
502
|
console.error("[WxAuth] apiBase is required");
|
|
464
503
|
return;
|
|
465
504
|
}
|
|
@@ -471,11 +510,37 @@ const u = {
|
|
|
471
510
|
} catch {
|
|
472
511
|
}
|
|
473
512
|
!d && window.location.hostname && (d = window.location.hostname), d || (d = "default"), console.log("[WxAuth] 自动获取 siteId:", d);
|
|
474
|
-
const
|
|
475
|
-
console.log("[WxAuth] deviceId:",
|
|
513
|
+
const n = u.getOrCreateDeviceId();
|
|
514
|
+
console.log("[WxAuth] deviceId:", n), this.getOrCreateAnonTicket();
|
|
476
515
|
}
|
|
477
516
|
console.log("[WxAuth] SDK initialized", a), typeof window < "u" && (a.silent ? this.silentCheck() : this.autoCheck());
|
|
478
517
|
},
|
|
518
|
+
// ===== 匿名票据(2026-09-24,访客准入)=====
|
|
519
|
+
/**
|
|
520
|
+
* 取当前匿名票据(同步,不触发签发)。没有或临期返回 null——
|
|
521
|
+
* 一般业务直接用 getOrCreateAnonTicket,本方法供想自己控制签发时机的接入方。
|
|
522
|
+
*/
|
|
523
|
+
getAnonTicket() {
|
|
524
|
+
if (y)
|
|
525
|
+
return y.expMs - Date.now() > I ? y.ticket : null;
|
|
526
|
+
const e = u.readStoredAnonTicket();
|
|
527
|
+
return !e || e.expMs - Date.now() <= I ? null : (y = e, e.ticket);
|
|
528
|
+
},
|
|
529
|
+
/**
|
|
530
|
+
* 取匿名票据,没有/临期则自动向 wx-auth 签发口要一张(并发调用合并为一次)。
|
|
531
|
+
* 签发失败(bot UA 403 / 限流 429 / 断网)返回 null——fail-open:票据系统
|
|
532
|
+
* 故障不阻断业务,是否放行无票请求由接入方自己定夺。
|
|
533
|
+
*
|
|
534
|
+
* 建议在建立 SSE 连接前 await 本方法,把返回值拼在 URL 上:
|
|
535
|
+
* const at = await WxAuth.getOrCreateAnonTicket();
|
|
536
|
+
* const es = new EventSource(`${url}${url.includes("?") ? "&" : "?"}at=${at}`);
|
|
537
|
+
*/
|
|
538
|
+
async getOrCreateAnonTicket() {
|
|
539
|
+
const e = this.getAnonTicket();
|
|
540
|
+
return e || (x || (x = u.requestAnonTicket().then((t) => t ? (y = t, u.storeAnonTicket(t.ticket, t.anonId, t.expMs), t.ticket) : null).catch(() => null).finally(() => {
|
|
541
|
+
x = null;
|
|
542
|
+
})), x);
|
|
543
|
+
},
|
|
479
544
|
/**
|
|
480
545
|
* 静默验证(silent 模式专用)
|
|
481
546
|
* - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
|
|
@@ -486,18 +551,18 @@ const u = {
|
|
|
486
551
|
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
487
552
|
*/
|
|
488
553
|
async silentCheck() {
|
|
489
|
-
const e =
|
|
554
|
+
const e = u.getToken();
|
|
490
555
|
if (!e) return !1;
|
|
491
556
|
const t = await v(e);
|
|
492
|
-
return t.kind === "ok" ? (
|
|
557
|
+
return t.kind === "ok" ? (this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
|
|
493
558
|
},
|
|
494
559
|
// 自动检测凭证并验证(内部使用)
|
|
495
560
|
async autoCheck() {
|
|
496
|
-
const e =
|
|
561
|
+
const e = u.getToken();
|
|
497
562
|
if (!e)
|
|
498
563
|
return this.showAuthModal(), !1;
|
|
499
564
|
const t = await v(e);
|
|
500
|
-
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"),
|
|
565
|
+
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
|
|
501
566
|
code: "server_error",
|
|
502
567
|
retryable: !0,
|
|
503
568
|
message: "登录服务暂时不可用,请稍后重试"
|
|
@@ -511,7 +576,7 @@ const u = {
|
|
|
511
576
|
// options.required:本次弹窗是否强制(不可关闭),缺省沿用 init 的 config.required。
|
|
512
577
|
// 典型用法:搜索/获取等「后端 401 拦截」场景传 true,用户主动点登录则不传或传 false。
|
|
513
578
|
async showAuthModal(e) {
|
|
514
|
-
|
|
579
|
+
c.show(e?.required), this.switchMode("mp");
|
|
515
580
|
},
|
|
516
581
|
// 切换登录方式(默认模式设定)
|
|
517
582
|
// 2026-09-16:公众号验证码面板临时停用,弹窗只剩小程序面板,
|
|
@@ -520,22 +585,22 @@ const u = {
|
|
|
520
585
|
f = e;
|
|
521
586
|
const t = document.getElementById("wx-auth-modal");
|
|
522
587
|
if (!t) return;
|
|
523
|
-
t.querySelectorAll(".wx-auth-tab").forEach((
|
|
524
|
-
|
|
588
|
+
t.querySelectorAll(".wx-auth-tab").forEach((r) => {
|
|
589
|
+
r.classList.toggle("wx-auth-tab-active", r.dataset.mode === f);
|
|
525
590
|
});
|
|
526
|
-
const
|
|
527
|
-
|
|
591
|
+
const n = t.querySelector(".wx-auth-panel-code"), o = t.querySelector(".wx-auth-panel-mp");
|
|
592
|
+
n && (n.style.display = f === "code" ? "" : "none"), o && (o.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : S();
|
|
528
593
|
},
|
|
529
594
|
// 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
|
|
530
595
|
async startMpLogin() {
|
|
531
596
|
if (!i.isOpen) return;
|
|
532
597
|
const e = ++h;
|
|
533
|
-
if (
|
|
534
|
-
|
|
598
|
+
if (c.setMpExpiredVisible(!1), c.setMpStatus("", !0), i.mpSession && Date.now() < i.mpSession.expiresAt) {
|
|
599
|
+
c.setMpQr(i.mpSession.qrDataUrl), q(e);
|
|
535
600
|
return;
|
|
536
601
|
}
|
|
537
602
|
try {
|
|
538
|
-
const t = await
|
|
603
|
+
const t = await u.request(`${a.apiBase}/api/auth/mp-scan/create`, {
|
|
539
604
|
method: "POST",
|
|
540
605
|
body: { siteId: d }
|
|
541
606
|
});
|
|
@@ -545,30 +610,30 @@ const u = {
|
|
|
545
610
|
ticket: String(t.ticket),
|
|
546
611
|
qrDataUrl: String(t.qrDataUrl),
|
|
547
612
|
expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
|
|
548
|
-
},
|
|
613
|
+
}, c.setMpQr(i.mpSession.qrDataUrl), q(e);
|
|
549
614
|
} catch (t) {
|
|
550
615
|
if (e !== h || !i.isOpen) return;
|
|
551
|
-
console.warn("[WxAuth] 小程序码生成失败", t),
|
|
616
|
+
console.warn("[WxAuth] 小程序码生成失败", t), c.setMpStatus("", !1), c.showMpExpired("二维码生成失败,请点下方按钮重试"), c.showMessage("小程序扫码暂不可用,请稍后重试", "error");
|
|
552
617
|
}
|
|
553
618
|
},
|
|
554
619
|
// 主入口:需要验证时调用
|
|
555
620
|
// 凭证仅签名 Token(登录 Cookie,7 天持久 + 滑动续期,2026-09-19),不再兼容明文 openid
|
|
556
621
|
// (2026-08-26 服务端已下线 openid 通道)
|
|
557
622
|
async requireAuth(e) {
|
|
558
|
-
const t =
|
|
623
|
+
const t = u.getToken();
|
|
559
624
|
if (t) {
|
|
560
|
-
const
|
|
561
|
-
if (
|
|
562
|
-
return console.log("[WxAuth] 已认证(凭证)"),
|
|
563
|
-
if (
|
|
625
|
+
const n = await v(t);
|
|
626
|
+
if (n.kind === "ok")
|
|
627
|
+
return console.log("[WxAuth] 已认证(凭证)"), n.result.token && u.setToken(n.result.token), this.onVerified(n.result.user), !0;
|
|
628
|
+
if (n.kind === "transient")
|
|
564
629
|
return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
|
|
565
630
|
code: "server_error",
|
|
566
631
|
retryable: !0,
|
|
567
632
|
message: "登录服务暂时不可用,请稍后重试"
|
|
568
633
|
}), !1;
|
|
569
634
|
}
|
|
570
|
-
return await this.showAuthModal(e), new Promise((
|
|
571
|
-
i.resolveAuth =
|
|
635
|
+
return await this.showAuthModal(e), new Promise((n) => {
|
|
636
|
+
i.resolveAuth = n;
|
|
572
637
|
});
|
|
573
638
|
},
|
|
574
639
|
// 共享登录成功路径(验证码校验成功 / 小程序扫码确认成功均走这里)
|
|
@@ -576,8 +641,8 @@ const u = {
|
|
|
576
641
|
// 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
|
|
577
642
|
// close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
|
|
578
643
|
completeLogin(e) {
|
|
579
|
-
if (e?.token &&
|
|
580
|
-
|
|
644
|
+
if (e?.token && u.setToken(e.token), f === "mp")
|
|
645
|
+
c.setMpStatus("✅ 登录成功", !1);
|
|
581
646
|
else {
|
|
582
647
|
const t = document.querySelector(".wx-auth-btn-primary");
|
|
583
648
|
t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
|
|
@@ -590,9 +655,9 @@ const u = {
|
|
|
590
655
|
// 2026-09-16:公众号登录临时停用 → 弹窗内已无验证码输入框与登录入口,
|
|
591
656
|
// 此方法保留(老接入方直调 / 恢复时可直接复用),正常链路不会被触发。
|
|
592
657
|
async verifyCode() {
|
|
593
|
-
const e =
|
|
658
|
+
const e = c.getVerifyCode();
|
|
594
659
|
if (!e || e.length !== 6) {
|
|
595
|
-
|
|
660
|
+
c.showMessage("请输入6位验证码", "error");
|
|
596
661
|
return;
|
|
597
662
|
}
|
|
598
663
|
const t = document.querySelector(
|
|
@@ -600,16 +665,16 @@ const u = {
|
|
|
600
665
|
);
|
|
601
666
|
t && (t.disabled = !0, t.textContent = "登录中...");
|
|
602
667
|
try {
|
|
603
|
-
const
|
|
604
|
-
`${a.apiBase}/api/auth/check?authToken=${e}${
|
|
668
|
+
const n = d ? `&siteId=${encodeURIComponent(d)}` : "", o = `&deviceId=${encodeURIComponent(u.getOrCreateDeviceId())}`, r = await u.request(
|
|
669
|
+
`${a.apiBase}/api/auth/check?authToken=${e}${n}${o}`
|
|
605
670
|
);
|
|
606
|
-
|
|
607
|
-
|
|
671
|
+
r.authenticated ? this.completeLogin(r) : (c.showMessage(
|
|
672
|
+
r.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
|
|
608
673
|
"error"
|
|
609
|
-
),
|
|
610
|
-
} catch (
|
|
611
|
-
|
|
612
|
-
|
|
674
|
+
), c.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
|
|
675
|
+
} catch (n) {
|
|
676
|
+
c.showMessage(
|
|
677
|
+
b(n) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
|
|
613
678
|
"error"
|
|
614
679
|
), t && (t.disabled = !1, t.textContent = "登录");
|
|
615
680
|
}
|
|
@@ -618,12 +683,12 @@ const u = {
|
|
|
618
683
|
// skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
|
|
619
684
|
// (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
|
|
620
685
|
close(e = !1) {
|
|
621
|
-
|
|
686
|
+
c.hide(), i.resolveAuth && (i.resolveAuth(!1), i.resolveAuth = null), !e && typeof a.onClose == "function" && a.onClose();
|
|
622
687
|
},
|
|
623
688
|
// 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
|
|
624
689
|
// 用于"退出登录 / 清空认证状态"按钮。
|
|
625
690
|
clearToken() {
|
|
626
|
-
|
|
691
|
+
u.clearToken();
|
|
627
692
|
},
|
|
628
693
|
// 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
|
|
629
694
|
// 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
|
|
@@ -634,17 +699,17 @@ const u = {
|
|
|
634
699
|
// 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
|
|
635
700
|
// 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
|
|
636
701
|
async revoke() {
|
|
637
|
-
const e =
|
|
702
|
+
const e = u.getToken();
|
|
638
703
|
if (e)
|
|
639
704
|
try {
|
|
640
|
-
const t = a.apiBase && !/\/$/.test(a.apiBase) ? a.apiBase : "https://wx-auth.shenzjd.com",
|
|
705
|
+
const t = a.apiBase && !/\/$/.test(a.apiBase) ? a.apiBase : "https://wx-auth.shenzjd.com", n = await fetch(`${t}/api/auth/logout`, {
|
|
641
706
|
method: "POST",
|
|
642
707
|
headers: { "Content-Type": "application/json" },
|
|
643
708
|
// deviceId 显式携带(跨站 SameSite 下 Cookie 不可靠);设备身份不因退出而清除
|
|
644
|
-
body: JSON.stringify({ token: e, deviceId:
|
|
709
|
+
body: JSON.stringify({ token: e, deviceId: u.getOrCreateDeviceId() }),
|
|
645
710
|
credentials: "include"
|
|
646
711
|
});
|
|
647
|
-
|
|
712
|
+
n.ok || console.warn("[WxAuth] revoke 请求失败,降级本地清理", n.status);
|
|
648
713
|
} catch (t) {
|
|
649
714
|
console.warn("[WxAuth] revoke 网络异常,降级本地清理", t);
|
|
650
715
|
}
|
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-modal .wx-auth-header{position:relative;background:#07c160;color:#fff;box-sizing:border-box;min-height:56px;padding:0 16px;display:flex;align-items:center;justify-content:space-between}.wx-auth-modal .wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-modal .wx-auth-close{position:absolute;right:10px;top:50%;transform:translateY(-50%);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
|
|
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 l=r;if(l.id===e.modalId||l.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()}},I={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!1,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let s={...I},d="",v="",g=null,b=null;const q="wxauth-anon",M=10080*60*1e3;let a={isOpen:!1,resolveAuth:null,currentStep:"qr",required:!!s.required,mpSession:null},p="mp",h=0;const D=1440*60*1e3;function O(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 O(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 l=n?`;domain=${n}`:"",_=window.location.protocol==="https:"?";Secure":"",L=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=/${l}${L}${_};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,D)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}catch{}},getOrCreateDeviceId(){if(v)return v;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 v=e,e},readStoredAnonTicket(){let e=null;try{e=window.localStorage.getItem(q)}catch{}if(!e)return null;try{const t=JSON.parse(e);if(typeof t.ticket!="string"||typeof t.anonId!="string"||typeof t.expMs!="number")return null;const o=t.ticket.split(".");return o.length!==7||o[0]!=="v1"||parseInt(o[5],10)*1e3!==t.expMs?null:{ticket:t.ticket,anonId:t.anonId,expMs:t.expMs}}catch{return null}},storeAnonTicket(e,t,o){try{window.localStorage.setItem(q,JSON.stringify({ticket:e,anonId:t,expMs:o}))}catch{}},async requestAnonTicket(){const e=(s.apiBase||"").replace(/\/$/,"");if(!e||typeof window>"u")return null;const t=await c.request(`${e}/api/auth/anon`,{method:"POST",body:{aud:window.location.hostname}});return!t||typeof t.ticket!="string"||typeof t.anonId!="string"||typeof t.expiresIn!="number"?null:{ticket:t.ticket,anonId:t.anonId,expMs:Date.now()+t.expiresIn*1e3}},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}},E=[1e3,3e3];function S(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function k(e){return new Promise(t=>setTimeout(t,e))}const $=3e3,P=2e3,R=3e3;function A(){h++}async function T(e){if(await k($),!(e!==h||!a.isOpen)){for(;e===h&&a.isOpen;){const t=a.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${s.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==h)return;if(o.status==="confirmed"&&o.token){x.completeLogin(o);return}if(o.status==="expired"){a.mpSession=null;break}}catch(o){if(e!==h)return;if(!S(o))break;await k(R);continue}await k(P)}e===h&&a.isOpen&&p==="mp"&&u.showMpExpired()}}async function C(e){const t=d?`&siteId=${encodeURIComponent(d)}`:"",o=`${s.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(!S(r)||n>=E.length)return{kind:"transient"};await k(E[n])}}const u={createModal(e){const t=document.createElement("div");t.id="wx-auth-modal",t.className="wx-auth-modal",t.classList.add(e?"wx-auth-required":"wx-auth-optional");const o="",n="",r=`<div class="wx-auth-panel wx-auth-panel-mp">
|
|
3
3
|
<div class="wx-auth-qrcode-container wx-auth-mp-container">
|
|
4
4
|
<div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
|
|
5
5
|
<img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
|
|
@@ -29,4 +29,4 @@
|
|
|
29
29
|
<div class="wx-auth-message" style="display:none"></div>
|
|
30
30
|
</div>
|
|
31
31
|
</div>
|
|
32
|
-
`,document.body.appendChild(t),this.syncModalShape(t,e),this.bindInputEvents(),t},syncModalShape(e,t){e.classList.remove("wx-auth-required","wx-auth-optional"),e.classList.add(t?"wx-auth-required":"wx-auth-optional");const o=e.querySelector(".wx-auth-overlay");o&&(o.onclick=t?
|
|
32
|
+
`,document.body.appendChild(t),this.syncModalShape(t,e),this.bindInputEvents(),t},syncModalShape(e,t){e.classList.remove("wx-auth-required","wx-auth-optional"),e.classList.add(t?"wx-auth-required":"wx-auth-optional");const o=e.querySelector(".wx-auth-overlay");o&&(o.onclick=t?y=>y.preventDefault():null);const n=e.querySelector(".wx-auth-close");if(t){n?.remove();return}if(n)return;const r=e.querySelector(".wx-auth-header");if(!r)return;const l=document.createElement("button");l.type="button",l.className="wx-auth-close",l.setAttribute("aria-label","关闭"),l.textContent="×",l.addEventListener("click",()=>x.close()),r.appendChild(l)},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(()=>x.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,y)=>{e[y]&&(e[y].value=l)}),r.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(e){const t=e??!!s.required;a.required=t;let o=document.getElementById("wx-auth-modal");o?this.syncModalShape(o,t):o=this.createModal(t);const n=o.querySelector(".wx-auth-message");n&&(n.textContent="",n.className="wx-auth-message",n.style.display="none"),A(),a.mpSession=null,o.style.display="flex",a.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>a,onRestore:()=>{this.createModal(a.required),s.qrcodeUrl&&this.setQrCode(s.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&s.wechatName&&(r.textContent=`"${s.wechatName}"`),this.bindInputEvents(),p==="mp"&&x.switchMode("mp"),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",a.isOpen=!1,A(),a.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 l=o?.querySelector(".wx-auth-mp-qrcode");l&&(l.style.display="none")}},showMpExpired(e="二维码已过期"){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired-text");o&&(o.textContent=e),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()}},x={init(e={}){if(s={...I,...e},!s.apiBase&&typeof window<"u"&&(s.apiBase=window.location.origin),!s.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);const o=c.getOrCreateDeviceId();console.log("[WxAuth] deviceId:",o),this.getOrCreateAnonTicket()}console.log("[WxAuth] SDK initialized",s),typeof window<"u"&&(s.silent?this.silentCheck():this.autoCheck())},getAnonTicket(){if(g)return g.expMs-Date.now()>M?g.ticket:null;const e=c.readStoredAnonTicket();return!e||e.expMs-Date.now()<=M?null:(g=e,e.ticket)},async getOrCreateAnonTicket(){const e=this.getAnonTicket();return e||(b||(b=c.requestAnonTicket().then(t=>t?(g=t,c.storeAnonTicket(t.ticket,t.anonId,t.expMs),t.ticket):null).catch(()=>null).finally(()=>{b=null})),b)},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await C(e);return t.kind==="ok"?(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] 自动认证成功(凭证)"),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(e){u.show(e?.required),this.switchMode("mp")},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():A()},async startMpLogin(){if(!a.isOpen)return;const e=++h;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),a.mpSession&&Date.now()<a.mpSession.expiresAt){u.setMpQr(a.mpSession.qrDataUrl),T(e);return}try{const t=await c.request(`${s.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:d}});if(e!==h||!a.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");a.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(a.mpSession.qrDataUrl),T(e)}catch(t){if(e!==h||!a.isOpen)return;console.warn("[WxAuth] 小程序码生成失败",t),u.setMpStatus("",!1),u.showMpExpired("二维码生成失败,请点下方按钮重试"),u.showMessage("小程序扫码暂不可用,请稍后重试","error")}},async requireAuth(e){const t=c.getToken();if(t){const o=await C(t);if(o.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),o.result.token&&c.setToken(o.result.token),this.onVerified(o.result.user),!0;if(o.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(e),new Promise(o=>{a.resolveAuth=o})},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=d?`&siteId=${encodeURIComponent(d)}`:"",n=`&deviceId=${encodeURIComponent(c.getOrCreateDeviceId())}`,r=await c.request(`${s.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(S(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),a.resolveAuth&&(a.resolveAuth(!1),a.resolveAuth=null),!e&&typeof s.onClose=="function"&&s.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=s.apiBase&&!/\/$/.test(s.apiBase)?s.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 s.onVerified=="function"&&s.onVerified(e),a.resolveAuth&&(a.resolveAuth(!0),a.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof s.onError=="function"&&s.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),w.WxAuth=x,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
|