wx-auth-sdk 1.2.40 → 1.2.42
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 +25 -4
- package/dist/index.d.ts +14 -2
- package/dist/wx-auth.css +1 -1
- package/dist/wx-auth.js +136 -104
- package/dist/wx-auth.umd.js +5 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -117,7 +117,7 @@ SDK 会自动:
|
|
|
117
117
|
```ts
|
|
118
118
|
WxAuth.init({
|
|
119
119
|
apiBase?: string, // 后端地址(可选,默认官方服务)
|
|
120
|
-
required?: boolean, //
|
|
120
|
+
required?: boolean, // 弹窗是否强制(默认 false:带 × 可关闭;true = 不可关闭)
|
|
121
121
|
silent?: boolean, // 静默初始化(默认 false),true 时不弹窗
|
|
122
122
|
onVerified?: (user) => void,
|
|
123
123
|
onError?: (err) => void,
|
|
@@ -128,10 +128,20 @@ WxAuth.init({
|
|
|
128
128
|
> `siteId` 无需配置:SDK 自动从 `document.referrer` 或当前域名获取并上报。
|
|
129
129
|
> `wechatName` / `qrcodeUrl` 随公众号验证码登录一并临时停用(SDK 不再拉取 `/api/sdk/config`);恢复后仍由后端统一下发,接入方配置无效。
|
|
130
130
|
|
|
131
|
-
### `WxAuth.requireAuth()`
|
|
131
|
+
### `WxAuth.requireAuth(options?)`
|
|
132
132
|
|
|
133
133
|
手动触发认证(用于"登录"按钮、切换账号)。返回 `Promise<boolean>`。
|
|
134
134
|
|
|
135
|
+
```ts
|
|
136
|
+
await WxAuth.requireAuth(); // 用 init 的 required
|
|
137
|
+
await WxAuth.requireAuth({ required: false }); // 本次弹窗可关闭(用户主动点登录)
|
|
138
|
+
await WxAuth.requireAuth({ required: true }); // 本次弹窗强制不可关闭(后端 401 拦截)
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
`options.required` 只作用于**本次弹出的弹窗**,不改 init 的全局配置——同一次页面会话里
|
|
142
|
+
可以先弹「用户主动登录(可关)」,再弹「后端校验强制登录(不可关)」,互不污染。
|
|
143
|
+
`showAuthModal(options?)` 同样接受该入参(两者都是「打开登录弹窗」的入口)。
|
|
144
|
+
|
|
135
145
|
### `WxAuth.close()`
|
|
136
146
|
|
|
137
147
|
关闭弹窗。`required=false` 时触发 `onClose` 回调。
|
|
@@ -199,7 +209,18 @@ interface AuthUser {
|
|
|
199
209
|
|
|
200
210
|
## 两种模式
|
|
201
211
|
|
|
202
|
-
|
|
212
|
+
**默认是「可选认证」**:用户主动点登录(头像、登录按钮)属于可反悔操作,允许关掉;
|
|
213
|
+
「必须登录才能继续」属于业务判断,由调用方显式声明 `required: true`。
|
|
214
|
+
|
|
215
|
+
| 场景 | 写法 | 形态 |
|
|
216
|
+
| --- | --- | --- |
|
|
217
|
+
| 用户主动点登录(头像 / 登录按钮) | `requireAuth({ required: false })`(或不传,走 init 默认) | 带 × 可关闭 |
|
|
218
|
+
| 后端 401 / 功能前置校验 | `requireAuth({ required: true })` 或 `showAuthModal({ required: true })` | 无 ×,遮罩不可点穿 |
|
|
219
|
+
|
|
220
|
+
> 前端传入的 `required` 只是 UI 语义,**不构成安全边界**——真正的门禁始终在后端
|
|
221
|
+
> (`requireWxAuth` 校验 Token),前端把强制窗改成可关也走不到业务。
|
|
222
|
+
|
|
223
|
+
### 强制认证 `required: true`(需显式声明)
|
|
203
224
|
|
|
204
225
|
必须完成认证才能继续,关闭按钮隐藏,点击遮罩无效。
|
|
205
226
|
|
|
@@ -215,7 +236,7 @@ interface AuthUser {
|
|
|
215
236
|
└──────────────────────────────────┘
|
|
216
237
|
```
|
|
217
238
|
|
|
218
|
-
### 可选认证 `required: false
|
|
239
|
+
### 可选认证 `required: false`(默认)
|
|
219
240
|
|
|
220
241
|
用户可主动关闭弹窗,关闭时执行 `onClose` 回调。
|
|
221
242
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
declare type LoginMode = "mp" | "code";
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* 单次登录调用的可选项(requireAuth / showAuthModal 入参)。
|
|
5
|
+
*
|
|
6
|
+
* `required` 只作用于「本次弹出的这个弹窗」,不污染 init 的全局配置:
|
|
7
|
+
* - 不传 → 用 init 时的 config.required;
|
|
8
|
+
* - false → 本次弹窗带 × 可关闭(用户主动点登录的场景,如右上角头像);
|
|
9
|
+
* - true → 本次弹窗强制不可关闭(后台校验 / 后端 401 拦截的场景)。
|
|
10
|
+
*/
|
|
11
|
+
export declare interface RequireAuthOptions {
|
|
12
|
+
required?: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
3
15
|
export declare const WxAuth: {
|
|
4
16
|
init(options?: Partial<WxAuthConfig>): void;
|
|
5
17
|
/**
|
|
@@ -13,10 +25,10 @@ export declare const WxAuth: {
|
|
|
13
25
|
*/
|
|
14
26
|
silentCheck(): Promise<boolean>;
|
|
15
27
|
autoCheck(): Promise<boolean>;
|
|
16
|
-
showAuthModal(): Promise<void>;
|
|
28
|
+
showAuthModal(options?: RequireAuthOptions): Promise<void>;
|
|
17
29
|
switchMode(mode: LoginMode): void;
|
|
18
30
|
startMpLogin(): Promise<void>;
|
|
19
|
-
requireAuth(): Promise<boolean>;
|
|
31
|
+
requireAuth(options?: RequireAuthOptions): Promise<boolean>;
|
|
20
32
|
completeLogin(result: {
|
|
21
33
|
token?: string;
|
|
22
34
|
user?: any;
|
package/dist/wx-auth.css
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
.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;padding:
|
|
1
|
+
.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}
|
package/dist/wx-auth.js
CHANGED
|
@@ -14,8 +14,8 @@ const s = {
|
|
|
14
14
|
if (r.type === "childList")
|
|
15
15
|
for (const n of r.removedNodes) {
|
|
16
16
|
if (n.nodeType !== Node.ELEMENT_NODE) continue;
|
|
17
|
-
const
|
|
18
|
-
if (
|
|
17
|
+
const l = n;
|
|
18
|
+
if (l.id === e.modalId || l.querySelector?.(`#${e.modalId}`)) {
|
|
19
19
|
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), p.safeRestore(e);
|
|
20
20
|
return;
|
|
21
21
|
}
|
|
@@ -95,8 +95,10 @@ const s = {
|
|
|
95
95
|
// 错误回调
|
|
96
96
|
onClose: null,
|
|
97
97
|
// 关闭弹窗回调(仅在 required=false 时触发)
|
|
98
|
-
|
|
99
|
-
//
|
|
98
|
+
// 是否必须认证(默认 false = 可选认证:弹窗带 × 可关闭)。
|
|
99
|
+
// 原则:用户主动点登录(头像等)默认允许反悔;强制登录(后台校验 / 后端 401 拦截)
|
|
100
|
+
// 必须由调用方显式声明 required: true(init 全局,或单次 requireAuth/showAuthModal 入参)。
|
|
101
|
+
required: !1,
|
|
100
102
|
wechatName: "神族九帝",
|
|
101
103
|
// 公众号名称(可选,会自动获取)
|
|
102
104
|
qrcodeUrl: "",
|
|
@@ -104,13 +106,14 @@ const s = {
|
|
|
104
106
|
silent: !1
|
|
105
107
|
// 默认不静默
|
|
106
108
|
};
|
|
107
|
-
let
|
|
109
|
+
let a = { ...C }, d = "", x = "", i = {
|
|
108
110
|
isOpen: !1,
|
|
109
111
|
resolveAuth: null,
|
|
110
112
|
currentStep: "qr",
|
|
113
|
+
required: !!a.required,
|
|
111
114
|
mpSession: null
|
|
112
115
|
}, f = "mp", h = 0;
|
|
113
|
-
function
|
|
116
|
+
function I(e) {
|
|
114
117
|
try {
|
|
115
118
|
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
116
119
|
return "";
|
|
@@ -120,9 +123,9 @@ function q(e) {
|
|
|
120
123
|
return "";
|
|
121
124
|
}
|
|
122
125
|
}
|
|
123
|
-
const
|
|
126
|
+
const c = {
|
|
124
127
|
getRootDomain() {
|
|
125
|
-
return
|
|
128
|
+
return I(window.location.hostname);
|
|
126
129
|
},
|
|
127
130
|
// 获取Cookie
|
|
128
131
|
getCookie(e) {
|
|
@@ -131,8 +134,8 @@ const u = {
|
|
|
131
134
|
},
|
|
132
135
|
// Cookie 写入底层(domainStr 传空串 = host-only,落在当前 host 本域)
|
|
133
136
|
writeCookieRaw(e, t, o, r, n = !1) {
|
|
134
|
-
const
|
|
135
|
-
document.cookie = `${e}=${n ? "" : t};path=/${
|
|
137
|
+
const l = r ? `;domain=${r}` : "", A = window.location.protocol === "https:" ? ";Secure" : "", q = n ? ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : o !== void 0 ? `;expires=${new Date(Date.now() + o).toUTCString()}` : "";
|
|
138
|
+
document.cookie = `${e}=${n ? "" : t};path=/${l}${q}${A};SameSite=Strict`;
|
|
136
139
|
},
|
|
137
140
|
// 设置Cookie(2026-09-04:不传 maxAgeMs 时仍是会话 Cookie —— 浏览器关闭即失效;
|
|
138
141
|
// 传入 maxAgeMs 则写持久 Cookie;自动设置根域名实现跨子域共享)
|
|
@@ -236,26 +239,26 @@ const u = {
|
|
|
236
239
|
e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
|
|
237
240
|
return e += "</div>", e;
|
|
238
241
|
}
|
|
239
|
-
},
|
|
242
|
+
}, S = [1e3, 3e3];
|
|
240
243
|
function k(e) {
|
|
241
244
|
const t = e;
|
|
242
245
|
return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
|
|
243
246
|
}
|
|
244
|
-
function
|
|
247
|
+
function y(e) {
|
|
245
248
|
return new Promise((t) => setTimeout(t, e));
|
|
246
249
|
}
|
|
247
|
-
const E = 3e3,
|
|
248
|
-
function
|
|
250
|
+
const E = 3e3, M = 2e3, T = 3e3;
|
|
251
|
+
function g() {
|
|
249
252
|
h++;
|
|
250
253
|
}
|
|
251
|
-
async function
|
|
252
|
-
if (await
|
|
253
|
-
for (; e === h &&
|
|
254
|
-
const t =
|
|
254
|
+
async function b(e) {
|
|
255
|
+
if (await y(E), !(e !== h || !i.isOpen)) {
|
|
256
|
+
for (; e === h && i.isOpen; ) {
|
|
257
|
+
const t = i.mpSession;
|
|
255
258
|
if (!t || Date.now() >= t.expiresAt) break;
|
|
256
259
|
try {
|
|
257
|
-
const o = await
|
|
258
|
-
`${
|
|
260
|
+
const o = await c.request(
|
|
261
|
+
`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
|
|
259
262
|
);
|
|
260
263
|
if (e !== h) return;
|
|
261
264
|
if (o.status === "confirmed" && o.token) {
|
|
@@ -263,40 +266,41 @@ async function S(e) {
|
|
|
263
266
|
return;
|
|
264
267
|
}
|
|
265
268
|
if (o.status === "expired") {
|
|
266
|
-
|
|
269
|
+
i.mpSession = null;
|
|
267
270
|
break;
|
|
268
271
|
}
|
|
269
272
|
} catch (o) {
|
|
270
273
|
if (e !== h) return;
|
|
271
274
|
if (!k(o)) break;
|
|
272
|
-
await
|
|
275
|
+
await y(T);
|
|
273
276
|
continue;
|
|
274
277
|
}
|
|
275
|
-
await
|
|
278
|
+
await y(M);
|
|
276
279
|
}
|
|
277
|
-
e === h &&
|
|
280
|
+
e === h && i.isOpen && f === "mp" && u.showMpExpired();
|
|
278
281
|
}
|
|
279
282
|
}
|
|
280
|
-
async function
|
|
281
|
-
const t =
|
|
283
|
+
async function v(e) {
|
|
284
|
+
const t = d ? `&siteId=${encodeURIComponent(d)}` : "", o = `${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
|
|
282
285
|
for (let r = 0; ; r++)
|
|
283
286
|
try {
|
|
284
|
-
const n = await
|
|
287
|
+
const n = await c.request(o);
|
|
285
288
|
return n.authenticated ? { kind: "ok", result: n } : n.error === "rate_limited" || n.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: n };
|
|
286
289
|
} catch (n) {
|
|
287
|
-
if (!k(n) || r >=
|
|
290
|
+
if (!k(n) || r >= S.length)
|
|
288
291
|
return { kind: "transient" };
|
|
289
|
-
await
|
|
292
|
+
await y(S[r]);
|
|
290
293
|
}
|
|
291
294
|
}
|
|
292
|
-
const
|
|
295
|
+
const u = {
|
|
293
296
|
// 创建弹窗
|
|
294
297
|
// 形态固定为双 tab(2026-08-30 去掉 mpScanEnabled 门控):形态不依赖 config,
|
|
295
|
-
// 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
298
|
+
// 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab)结构上不存在。
|
|
299
|
+
// required 由调用方逐次传入(单次调用入参 ?? init 配置),决定本次弹窗能否关闭。
|
|
300
|
+
createModal(e) {
|
|
301
|
+
const t = document.createElement("div");
|
|
302
|
+
t.id = "wx-auth-modal", t.className = "wx-auth-modal", t.classList.add(e ? "wx-auth-required" : "wx-auth-optional");
|
|
303
|
+
const o = "", r = "", n = `<div class="wx-auth-panel wx-auth-panel-mp">
|
|
300
304
|
<div class="wx-auth-qrcode-container wx-auth-mp-container">
|
|
301
305
|
<div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
|
|
302
306
|
<img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
|
|
@@ -308,12 +312,11 @@ const l = {
|
|
|
308
312
|
<div class="wx-auth-desc wx-auth-mp-hint">微信扫描二维码,打开小程序确认登录</div>
|
|
309
313
|
<div class="wx-auth-mp-status"></div>
|
|
310
314
|
</div>`;
|
|
311
|
-
return
|
|
312
|
-
<div class="wx-auth-overlay"
|
|
315
|
+
return t.innerHTML = `
|
|
316
|
+
<div class="wx-auth-overlay"></div>
|
|
313
317
|
<div class="wx-auth-content">
|
|
314
318
|
<div class="wx-auth-header">
|
|
315
319
|
<div class="wx-auth-title">微信登录</div>
|
|
316
|
-
${t}
|
|
317
320
|
</div>
|
|
318
321
|
<div class="wx-auth-body">
|
|
319
322
|
${o}
|
|
@@ -328,7 +331,29 @@ const l = {
|
|
|
328
331
|
<div class="wx-auth-message" style="display:none"></div>
|
|
329
332
|
</div>
|
|
330
333
|
</div>
|
|
331
|
-
`, document.body.appendChild(e), this.bindInputEvents(),
|
|
334
|
+
`, document.body.appendChild(t), this.syncModalShape(t, e), this.bindInputEvents(), t;
|
|
335
|
+
},
|
|
336
|
+
/**
|
|
337
|
+
* 同步弹窗形态(打开前 / 重建后都要调):
|
|
338
|
+
* - 类名 wx-auth-required / wx-auth-optional(CSS 决定遮罩行为与按钮显隐)
|
|
339
|
+
* - 关闭按钮:可选认证必须有(弹窗 DOM 常驻只 hide,上一次强制打开的
|
|
340
|
+
* 弹窗里没有按钮,这里要按需补回);强制认证则直接摘掉,避免被样式覆盖后复活
|
|
341
|
+
* - 遮罩:强制认证拦截点击(点遮罩不关闭也不穿透)
|
|
342
|
+
*/
|
|
343
|
+
syncModalShape(e, t) {
|
|
344
|
+
e.classList.remove("wx-auth-required", "wx-auth-optional"), e.classList.add(t ? "wx-auth-required" : "wx-auth-optional");
|
|
345
|
+
const o = e.querySelector(".wx-auth-overlay");
|
|
346
|
+
o && (o.onclick = t ? (w) => w.preventDefault() : null);
|
|
347
|
+
const r = e.querySelector(".wx-auth-close");
|
|
348
|
+
if (t) {
|
|
349
|
+
r?.remove();
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (r) return;
|
|
353
|
+
const n = e.querySelector(".wx-auth-header");
|
|
354
|
+
if (!n) return;
|
|
355
|
+
const l = document.createElement("button");
|
|
356
|
+
l.type = "button", l.className = "wx-auth-close", l.setAttribute("aria-label", "关闭"), l.textContent = "×", l.addEventListener("click", () => m.close()), n.appendChild(l);
|
|
332
357
|
},
|
|
333
358
|
// 绑定输入事件
|
|
334
359
|
bindInputEvents() {
|
|
@@ -344,27 +369,32 @@ const l = {
|
|
|
344
369
|
}), t.addEventListener("paste", (r) => {
|
|
345
370
|
r.preventDefault();
|
|
346
371
|
const n = r.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
347
|
-
n && (n.split("").forEach((
|
|
348
|
-
e[
|
|
372
|
+
n && (n.split("").forEach((l, w) => {
|
|
373
|
+
e[w] && (e[w].value = l);
|
|
349
374
|
}), n.length === 6 && setTimeout(() => m.verifyCode(), 300));
|
|
350
375
|
});
|
|
351
376
|
});
|
|
352
377
|
}, 100);
|
|
353
378
|
},
|
|
354
379
|
// 显示弹窗
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
380
|
+
// requiredOverride:单次调用传入的强制语义(缺省用 init 的 config.required)。
|
|
381
|
+
// 每次打开都重新求值——同一次页面会话里可能先弹「用户主动登录(可关)」、
|
|
382
|
+
// 再弹「后台 401 强制登录(不可关)」,弹窗 DOM 是复用的,形态必须逐次同步。
|
|
383
|
+
show(e) {
|
|
384
|
+
const t = e ?? !!a.required;
|
|
385
|
+
i.required = t;
|
|
386
|
+
let o = document.getElementById("wx-auth-modal");
|
|
387
|
+
o ? this.syncModalShape(o, t) : o = this.createModal(t);
|
|
388
|
+
const r = o.querySelector(".wx-auth-message");
|
|
389
|
+
r && (r.textContent = "", r.className = "wx-auth-message", r.style.display = "none"), g(), i.mpSession = null, o.style.display = "flex", i.isOpen = !0, p.enable({
|
|
360
390
|
modalId: "wx-auth-modal",
|
|
361
|
-
getState: () =>
|
|
391
|
+
getState: () => i,
|
|
362
392
|
onRestore: () => {
|
|
363
|
-
this.createModal(),
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
const
|
|
367
|
-
|
|
393
|
+
this.createModal(i.required), a.qrcodeUrl && this.setQrCode(a.qrcodeUrl);
|
|
394
|
+
const n = document.querySelector(".wx-auth-wechat-name");
|
|
395
|
+
n && a.wechatName && (n.textContent = `"${a.wechatName}"`), this.bindInputEvents(), f === "mp" && m.switchMode("mp"), setTimeout(() => {
|
|
396
|
+
const l = document.querySelector(".wx-auth-input");
|
|
397
|
+
l && l.focus();
|
|
368
398
|
}, 100);
|
|
369
399
|
}
|
|
370
400
|
});
|
|
@@ -372,7 +402,7 @@ const l = {
|
|
|
372
402
|
// 隐藏弹窗
|
|
373
403
|
hide() {
|
|
374
404
|
const e = document.getElementById("wx-auth-modal");
|
|
375
|
-
e && (e.style.display = "none",
|
|
405
|
+
e && (e.style.display = "none", i.isOpen = !1, g(), i.mpSession = null, p.disable());
|
|
376
406
|
},
|
|
377
407
|
// 设置二维码
|
|
378
408
|
setQrCode(e) {
|
|
@@ -397,8 +427,8 @@ const l = {
|
|
|
397
427
|
r && (r.textContent = e, r.style.display = e ? "block" : "none");
|
|
398
428
|
const n = o?.querySelector(".wx-auth-mp-loading");
|
|
399
429
|
if (n && (n.style.display = t ? "flex" : "none"), t) {
|
|
400
|
-
const
|
|
401
|
-
|
|
430
|
+
const l = o?.querySelector(".wx-auth-mp-qrcode");
|
|
431
|
+
l && (l.style.display = "none");
|
|
402
432
|
}
|
|
403
433
|
},
|
|
404
434
|
// 二维码过期/失效:遮罩盖住旧码,用户点「刷新二维码」重新出码
|
|
@@ -427,7 +457,7 @@ const l = {
|
|
|
427
457
|
}, m = {
|
|
428
458
|
// 初始化
|
|
429
459
|
init(e = {}) {
|
|
430
|
-
if (
|
|
460
|
+
if (a = { ...C, ...e }, !a.apiBase && typeof window < "u" && (a.apiBase = window.location.origin), !a.apiBase) {
|
|
431
461
|
console.error("[WxAuth] apiBase is required");
|
|
432
462
|
return;
|
|
433
463
|
}
|
|
@@ -435,14 +465,14 @@ const l = {
|
|
|
435
465
|
const t = document.referrer;
|
|
436
466
|
if (t)
|
|
437
467
|
try {
|
|
438
|
-
|
|
468
|
+
d = new URL(t).hostname;
|
|
439
469
|
} catch {
|
|
440
470
|
}
|
|
441
|
-
!
|
|
442
|
-
const o =
|
|
471
|
+
!d && window.location.hostname && (d = window.location.hostname), d || (d = "default"), console.log("[WxAuth] 自动获取 siteId:", d);
|
|
472
|
+
const o = c.getOrCreateDeviceId();
|
|
443
473
|
console.log("[WxAuth] deviceId:", o);
|
|
444
474
|
}
|
|
445
|
-
console.log("[WxAuth] SDK initialized",
|
|
475
|
+
console.log("[WxAuth] SDK initialized", a), typeof window < "u" && (a.silent ? this.silentCheck() : this.autoCheck());
|
|
446
476
|
},
|
|
447
477
|
/**
|
|
448
478
|
* 静默验证(silent 模式专用)
|
|
@@ -454,18 +484,18 @@ const l = {
|
|
|
454
484
|
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
455
485
|
*/
|
|
456
486
|
async silentCheck() {
|
|
457
|
-
const e =
|
|
487
|
+
const e = c.getToken();
|
|
458
488
|
if (!e) return !1;
|
|
459
|
-
const t = await
|
|
460
|
-
return t.kind === "ok" ? (t.result.token &&
|
|
489
|
+
const t = await v(e);
|
|
490
|
+
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);
|
|
461
491
|
},
|
|
462
492
|
// 自动检测凭证并验证(内部使用)
|
|
463
493
|
async autoCheck() {
|
|
464
|
-
const e =
|
|
494
|
+
const e = c.getToken();
|
|
465
495
|
if (!e)
|
|
466
496
|
return this.showAuthModal(), !1;
|
|
467
|
-
const t = await
|
|
468
|
-
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token &&
|
|
497
|
+
const t = await v(e);
|
|
498
|
+
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({
|
|
469
499
|
code: "server_error",
|
|
470
500
|
retryable: !0,
|
|
471
501
|
message: "登录服务暂时不可用,请稍后重试"
|
|
@@ -476,8 +506,10 @@ const l = {
|
|
|
476
506
|
// 全程只有一种形态,无中间态。
|
|
477
507
|
// 2026-09-16:公众号验证码面板临时停用 → 只保留小程序扫码面板,
|
|
478
508
|
// 也不再拉取 /api/sdk/config(原用于填充公众号名称 / 关注二维码)。
|
|
479
|
-
|
|
480
|
-
|
|
509
|
+
// options.required:本次弹窗是否强制(不可关闭),缺省沿用 init 的 config.required。
|
|
510
|
+
// 典型用法:搜索/获取等「后端 401 拦截」场景传 true,用户主动点登录则不传或传 false。
|
|
511
|
+
async showAuthModal(e) {
|
|
512
|
+
u.show(e?.required), this.switchMode("mp");
|
|
481
513
|
},
|
|
482
514
|
// 切换登录方式(默认模式设定)
|
|
483
515
|
// 2026-09-16:公众号验证码面板临时停用,弹窗只剩小程序面板,
|
|
@@ -490,51 +522,51 @@ const l = {
|
|
|
490
522
|
n.classList.toggle("wx-auth-tab-active", n.dataset.mode === f);
|
|
491
523
|
});
|
|
492
524
|
const o = t.querySelector(".wx-auth-panel-code"), r = t.querySelector(".wx-auth-panel-mp");
|
|
493
|
-
o && (o.style.display = f === "code" ? "" : "none"), r && (r.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() :
|
|
525
|
+
o && (o.style.display = f === "code" ? "" : "none"), r && (r.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : g();
|
|
494
526
|
},
|
|
495
527
|
// 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
|
|
496
528
|
async startMpLogin() {
|
|
497
|
-
if (!
|
|
529
|
+
if (!i.isOpen) return;
|
|
498
530
|
const e = ++h;
|
|
499
|
-
if (
|
|
500
|
-
|
|
531
|
+
if (u.setMpExpiredVisible(!1), u.setMpStatus("", !0), i.mpSession && Date.now() < i.mpSession.expiresAt) {
|
|
532
|
+
u.setMpQr(i.mpSession.qrDataUrl), b(e);
|
|
501
533
|
return;
|
|
502
534
|
}
|
|
503
535
|
try {
|
|
504
|
-
const t = await
|
|
536
|
+
const t = await c.request(`${a.apiBase}/api/auth/mp-scan/create`, {
|
|
505
537
|
method: "POST",
|
|
506
|
-
body: { siteId:
|
|
538
|
+
body: { siteId: d }
|
|
507
539
|
});
|
|
508
|
-
if (e !== h || !
|
|
540
|
+
if (e !== h || !i.isOpen) return;
|
|
509
541
|
if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
|
|
510
|
-
|
|
542
|
+
i.mpSession = {
|
|
511
543
|
ticket: String(t.ticket),
|
|
512
544
|
qrDataUrl: String(t.qrDataUrl),
|
|
513
545
|
expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
|
|
514
|
-
},
|
|
546
|
+
}, u.setMpQr(i.mpSession.qrDataUrl), b(e);
|
|
515
547
|
} catch (t) {
|
|
516
|
-
if (e !== h || !
|
|
517
|
-
console.warn("[WxAuth] 小程序码生成失败", t),
|
|
548
|
+
if (e !== h || !i.isOpen) return;
|
|
549
|
+
console.warn("[WxAuth] 小程序码生成失败", t), u.setMpStatus("", !1), u.showMpExpired("二维码生成失败,请点下方按钮重试"), u.showMessage("小程序扫码暂不可用,请稍后重试", "error");
|
|
518
550
|
}
|
|
519
551
|
},
|
|
520
552
|
// 主入口:需要验证时调用
|
|
521
553
|
// 凭证仅签名 Token(登录 Cookie,会话级,2026-09-05),不再兼容明文 openid
|
|
522
554
|
// (2026-08-26 服务端已下线 openid 通道)
|
|
523
|
-
async requireAuth() {
|
|
524
|
-
const
|
|
525
|
-
if (
|
|
526
|
-
const
|
|
527
|
-
if (
|
|
528
|
-
return console.log("[WxAuth] 已认证(凭证)"),
|
|
529
|
-
if (
|
|
555
|
+
async requireAuth(e) {
|
|
556
|
+
const t = c.getToken();
|
|
557
|
+
if (t) {
|
|
558
|
+
const o = await v(t);
|
|
559
|
+
if (o.kind === "ok")
|
|
560
|
+
return console.log("[WxAuth] 已认证(凭证)"), o.result.token && c.setToken(o.result.token), this.onVerified(o.result.user), !0;
|
|
561
|
+
if (o.kind === "transient")
|
|
530
562
|
return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
|
|
531
563
|
code: "server_error",
|
|
532
564
|
retryable: !0,
|
|
533
565
|
message: "登录服务暂时不可用,请稍后重试"
|
|
534
566
|
}), !1;
|
|
535
567
|
}
|
|
536
|
-
return await this.showAuthModal(), new Promise((
|
|
537
|
-
|
|
568
|
+
return await this.showAuthModal(e), new Promise((o) => {
|
|
569
|
+
i.resolveAuth = o;
|
|
538
570
|
});
|
|
539
571
|
},
|
|
540
572
|
// 共享登录成功路径(验证码校验成功 / 小程序扫码确认成功均走这里)
|
|
@@ -542,8 +574,8 @@ const l = {
|
|
|
542
574
|
// 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
|
|
543
575
|
// close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
|
|
544
576
|
completeLogin(e) {
|
|
545
|
-
if (e?.token &&
|
|
546
|
-
|
|
577
|
+
if (e?.token && c.setToken(e.token), f === "mp")
|
|
578
|
+
u.setMpStatus("✅ 登录成功", !1);
|
|
547
579
|
else {
|
|
548
580
|
const t = document.querySelector(".wx-auth-btn-primary");
|
|
549
581
|
t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
|
|
@@ -556,9 +588,9 @@ const l = {
|
|
|
556
588
|
// 2026-09-16:公众号登录临时停用 → 弹窗内已无验证码输入框与登录入口,
|
|
557
589
|
// 此方法保留(老接入方直调 / 恢复时可直接复用),正常链路不会被触发。
|
|
558
590
|
async verifyCode() {
|
|
559
|
-
const e =
|
|
591
|
+
const e = u.getVerifyCode();
|
|
560
592
|
if (!e || e.length !== 6) {
|
|
561
|
-
|
|
593
|
+
u.showMessage("请输入6位验证码", "error");
|
|
562
594
|
return;
|
|
563
595
|
}
|
|
564
596
|
const t = document.querySelector(
|
|
@@ -566,15 +598,15 @@ const l = {
|
|
|
566
598
|
);
|
|
567
599
|
t && (t.disabled = !0, t.textContent = "登录中...");
|
|
568
600
|
try {
|
|
569
|
-
const o =
|
|
570
|
-
`${
|
|
601
|
+
const o = d ? `&siteId=${encodeURIComponent(d)}` : "", r = `&deviceId=${encodeURIComponent(c.getOrCreateDeviceId())}`, n = await c.request(
|
|
602
|
+
`${a.apiBase}/api/auth/check?authToken=${e}${o}${r}`
|
|
571
603
|
);
|
|
572
|
-
n.authenticated ? this.completeLogin(n) : (
|
|
604
|
+
n.authenticated ? this.completeLogin(n) : (u.showMessage(
|
|
573
605
|
n.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
|
|
574
606
|
"error"
|
|
575
|
-
),
|
|
607
|
+
), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
|
|
576
608
|
} catch (o) {
|
|
577
|
-
|
|
609
|
+
u.showMessage(
|
|
578
610
|
k(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
|
|
579
611
|
"error"
|
|
580
612
|
), t && (t.disabled = !1, t.textContent = "登录");
|
|
@@ -584,12 +616,12 @@ const l = {
|
|
|
584
616
|
// skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
|
|
585
617
|
// (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
|
|
586
618
|
close(e = !1) {
|
|
587
|
-
|
|
619
|
+
u.hide(), i.resolveAuth && (i.resolveAuth(!1), i.resolveAuth = null), !e && typeof a.onClose == "function" && a.onClose();
|
|
588
620
|
},
|
|
589
621
|
// 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
|
|
590
622
|
// 用于"退出登录 / 清空认证状态"按钮。
|
|
591
623
|
clearToken() {
|
|
592
|
-
|
|
624
|
+
c.clearToken();
|
|
593
625
|
},
|
|
594
626
|
// 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
|
|
595
627
|
// 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
|
|
@@ -600,14 +632,14 @@ const l = {
|
|
|
600
632
|
// 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
|
|
601
633
|
// 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
|
|
602
634
|
async revoke() {
|
|
603
|
-
const e =
|
|
635
|
+
const e = c.getToken();
|
|
604
636
|
if (e)
|
|
605
637
|
try {
|
|
606
|
-
const t =
|
|
638
|
+
const t = a.apiBase && !/\/$/.test(a.apiBase) ? a.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
|
|
607
639
|
method: "POST",
|
|
608
640
|
headers: { "Content-Type": "application/json" },
|
|
609
641
|
// deviceId 显式携带(跨站 SameSite 下 Cookie 不可靠);设备身份不因退出而清除
|
|
610
|
-
body: JSON.stringify({ token: e, deviceId:
|
|
642
|
+
body: JSON.stringify({ token: e, deviceId: c.getOrCreateDeviceId() }),
|
|
611
643
|
credentials: "include"
|
|
612
644
|
});
|
|
613
645
|
o.ok || console.warn("[WxAuth] revoke 请求失败,降级本地清理", o.status);
|
|
@@ -618,11 +650,11 @@ const l = {
|
|
|
618
650
|
},
|
|
619
651
|
// 验证成功回调
|
|
620
652
|
onVerified(e) {
|
|
621
|
-
console.log("[WxAuth] 验证成功", e), typeof
|
|
653
|
+
console.log("[WxAuth] 验证成功", e), typeof a.onVerified == "function" && a.onVerified(e), i.resolveAuth && (i.resolveAuth(!0), i.resolveAuth = null);
|
|
622
654
|
},
|
|
623
655
|
// 错误回调
|
|
624
656
|
onError(e) {
|
|
625
|
-
console.error("[WxAuth] 错误", e), typeof
|
|
657
|
+
console.error("[WxAuth] 错误", e), typeof a.onError == "function" && a.onError(e);
|
|
626
658
|
}
|
|
627
659
|
};
|
|
628
660
|
typeof window < "u" && (window.WxAuth = Object.freeze(m));
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(
|
|
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 a={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={enable(e){if(a.isProtected||typeof window>"u")return;a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!0,a.restorePending=!1,a.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}}}),a.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!a.isProtected)return;const{getState:o}=e;if(!o().isOpen){a.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)),a.isProtected&&(a.rafId=requestAnimationFrame(t))};a.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!1,a.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!a.restorePending){a.restorePending=!0;try{f.restoreFn(e)}finally{requestAnimationFrame(()=>{a.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()}},C={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!1,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let s={...C},d="",b="",i={isOpen:!1,resolveAuth:null,currentStep:"qr",required:!!s.required,mpSession:null},p="mp",h=0;function I(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 u={getRootDomain(){return I(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}`:"",D=window.location.protocol==="https:"?";Secure":"",P=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}${P}${D};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,T=3e3;function v(){h++}async function q(e){if(await y(E),!(e!==h||!i.isOpen)){for(;e===h&&i.isOpen;){const t=i.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await u.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"){i.mpSession=null;break}}catch(o){if(e!==h)return;if(!k(o))break;await y(T);continue}await y(M)}e===h&&i.isOpen&&p==="mp"&&c.showMpExpired()}}async function S(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 u.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 c={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" />
|
|
@@ -10,12 +10,11 @@
|
|
|
10
10
|
</div>
|
|
11
11
|
<div class="wx-auth-desc wx-auth-mp-hint">微信扫描二维码,打开小程序确认登录</div>
|
|
12
12
|
<div class="wx-auth-mp-status"></div>
|
|
13
|
-
</div>`;return
|
|
14
|
-
<div class="wx-auth-overlay"
|
|
13
|
+
</div>`;return t.innerHTML=`
|
|
14
|
+
<div class="wx-auth-overlay"></div>
|
|
15
15
|
<div class="wx-auth-content">
|
|
16
16
|
<div class="wx-auth-header">
|
|
17
17
|
<div class="wx-auth-title">微信登录</div>
|
|
18
|
-
${t}
|
|
19
18
|
</div>
|
|
20
19
|
<div class="wx-auth-body">
|
|
21
20
|
${o}
|
|
@@ -30,4 +29,4 @@
|
|
|
30
29
|
<div class="wx-auth-message" style="display:none"></div>
|
|
31
30
|
</div>
|
|
32
31
|
</div>
|
|
33
|
-
`,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(()=>
|
|
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?g=>g.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,g)=>{e[g]&&(e[g].value=l)}),r.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(e){const t=e??!!s.required;i.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"),v(),i.mpSession=null,o.style.display="flex",i.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>i,onRestore:()=>{this.createModal(i.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",i.isOpen=!1,v(),i.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={...C,...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=u.getOrCreateDeviceId();console.log("[WxAuth] deviceId:",o)}console.log("[WxAuth] SDK initialized",s),typeof window<"u"&&(s.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=u.getToken();if(!e)return!1;const t=await S(e);return t.kind==="ok"?(t.result.token&&u.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=u.getToken();if(!e)return this.showAuthModal(),!1;const t=await S(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&u.setToken(t.result.token),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(e){c.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():v()},async startMpLogin(){if(!i.isOpen)return;const e=++h;if(c.setMpExpiredVisible(!1),c.setMpStatus("",!0),i.mpSession&&Date.now()<i.mpSession.expiresAt){c.setMpQr(i.mpSession.qrDataUrl),q(e);return}try{const t=await u.request(`${s.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:d}});if(e!==h||!i.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");i.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},c.setMpQr(i.mpSession.qrDataUrl),q(e)}catch(t){if(e!==h||!i.isOpen)return;console.warn("[WxAuth] 小程序码生成失败",t),c.setMpStatus("",!1),c.showMpExpired("二维码生成失败,请点下方按钮重试"),c.showMessage("小程序扫码暂不可用,请稍后重试","error")}},async requireAuth(e){const t=u.getToken();if(t){const o=await S(t);if(o.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),o.result.token&&u.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=>{i.resolveAuth=o})},completeLogin(e){if(e?.token&&u.setToken(e.token),p==="mp")c.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=c.getVerifyCode();if(!e||e.length!==6){c.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(u.getOrCreateDeviceId())}`,r=await u.request(`${s.apiBase}/api/auth/check?authToken=${e}${o}${n}`);r.authenticated?this.completeLogin(r):(c.showMessage(r.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),c.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){c.showMessage(k(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){c.hide(),i.resolveAuth&&(i.resolveAuth(!1),i.resolveAuth=null),!e&&typeof s.onClose=="function"&&s.onClose()},clearToken(){u.clearToken()},async revoke(){const e=u.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:u.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),i.resolveAuth&&(i.resolveAuth(!0),i.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"})}));
|