wx-auth-sdk 1.2.38 → 1.2.40
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 +44 -46
- package/dist/wx-auth.css +1 -1
- package/dist/wx-auth.js +153 -203
- package/dist/wx-auth.umd.js +7 -29
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
# 微信登录 SDK
|
|
2
2
|
|
|
3
|
-
轻量级前端认证 SDK —
|
|
3
|
+
轻量级前端认证 SDK — 弹窗内置小程序扫码登录:
|
|
4
4
|
|
|
5
|
-
-
|
|
6
|
-
|
|
5
|
+
- **小程序扫码**:网页展示小程序码 → 微信扫码 → 小程序内点「确认登录」→ 网页自动登录,全程无需输入验证码
|
|
6
|
+
|
|
7
|
+
> **⚠️ 公众号验证码登录已临时停用(2026-09-16)**
|
|
8
|
+
> 弹窗不再展示「公众号登录」Tab 与 6 位验证码输入面板,也不再向后端拉取公众号名称 / 关注二维码(`/api/sdk/config`)。
|
|
9
|
+
> SDK 保留 `WxAuth.verifyCode()` 与 `switchMode()` 等方法及原面板实现(源码中以「公众号验证码登录临时停用」注释块标注),
|
|
10
|
+
> 恢复时按注释还原即可。后端 `GET /api/auth/check?authToken=` 验证码通道未改动。
|
|
11
|
+
> 停用期间的降级行为:出码失败不再切到验证码 Tab,而是在扫码面板内给出「刷新二维码」重试入口。
|
|
7
12
|
|
|
8
13
|
基于 Vite 构建,**零依赖,gzip 后 < 10 KB**。
|
|
9
14
|
|
|
@@ -33,26 +38,24 @@ WxAuth.init({
|
|
|
33
38
|
SDK 会自动:
|
|
34
39
|
|
|
35
40
|
- 从 `document.referrer` 或当前域名自动获取站点标识(`siteId`,无需配置)
|
|
36
|
-
- 从后端拉取公众号名称和二维码
|
|
37
41
|
- 使用内置 API 地址
|
|
38
42
|
|
|
39
43
|
---
|
|
40
44
|
|
|
41
|
-
##
|
|
45
|
+
## 登录方式:小程序扫码(唯一)
|
|
42
46
|
|
|
43
|
-
|
|
47
|
+
> **⚠️ 2026-09-16 起公众号验证码登录临时停用**:弹窗不再有「小程序登录 / 公众号登录」Tab 切换,
|
|
48
|
+
> 打开即渲染小程序扫码面板并立即出码。
|
|
44
49
|
|
|
45
50
|
```
|
|
46
51
|
┌──────────────────────────────────┐
|
|
47
52
|
│ 微信登录 [×] │
|
|
48
|
-
│
|
|
49
|
-
│ │
|
|
50
|
-
│ └──────────┴──────────┘ │
|
|
51
|
-
│ (内容区随 Tab 切换) │
|
|
53
|
+
│ │
|
|
54
|
+
│ (小程序码,打开弹窗即出码) │
|
|
52
55
|
└──────────────────────────────────┘
|
|
53
56
|
```
|
|
54
57
|
|
|
55
|
-
### Tab
|
|
58
|
+
### 小程序扫码(原「Tab 一」)
|
|
56
59
|
|
|
57
60
|
网页出码 → 用户微信扫码打开小程序确认页 → 点「确认登录」→ 网页每 2 秒轮询,确认后自动完成登录。
|
|
58
61
|
|
|
@@ -73,13 +76,16 @@ SDK 会自动:
|
|
|
73
76
|
|
|
74
77
|
- **无需输入验证码**,也不用关注公众号(小程序用户与公众号用户是两条独立身份记录,见下方 `user.type`)
|
|
75
78
|
- 二维码 **5 分钟有效**,过期后画面盖「二维码已过期」遮罩,点「刷新二维码」重新出码
|
|
76
|
-
-
|
|
77
|
-
- 出码失败(后端未配置小程序 /
|
|
79
|
+
- **主要面向桌面端浏览器**——手机屏幕上的二维码无法用同一部微信长按识别;手机端可截图后用微信「扫一扫 → 相册」识别,或在微信内打开页面时长按识别
|
|
80
|
+
- 出码失败(后端未配置小程序 / 微信接口异常)**不再回落公众号验证码 Tab**(该面板已临时停用),而是停留在扫码面板:收起 loading、盖「二维码生成失败,请点下方按钮重试」遮罩 + 提示,并提供「刷新二维码」重试入口
|
|
78
81
|
|
|
79
|
-
###
|
|
82
|
+
### (已临时停用)公众号验证码
|
|
80
83
|
|
|
81
84
|
传统方式:微信扫码关注公众号 → 向公众号发送"验证码" → 输入收到的 6 位数字 → 认证成功。
|
|
82
85
|
|
|
86
|
+
> ⚠️ 2026-09-16 起该面板不再渲染。源码中对应实现(`tabsHtml` / `codePanelHtml`、验证码输入框与登录按钮重置、
|
|
87
|
+
> `/api/sdk/config` 配置拉取、出码失败回落)均以「公众号验证码登录临时停用」注释块保留,恢复时按注释还原。
|
|
88
|
+
|
|
83
89
|
---
|
|
84
90
|
|
|
85
91
|
## 登录态与 Cookie 域
|
|
@@ -97,7 +103,7 @@ SDK 会自动:
|
|
|
97
103
|
- **同一注册域内一个认证,全域自动登录**:`sub1.mysite.com` 认证后,`sub2.mysite.com`、根域 `mysite.com` 都能静默通过(凭根域 Cookie)。
|
|
98
104
|
- **跨注册域不共享**:`mysite.com` 与 `other.com` 是相互独立的登录态,需各自认证一次(浏览器安全机制,无法绕过)。
|
|
99
105
|
- **主站已登录 → 子站有登录态**:`panhub.shenzjd.com` 认证后,访问 `parse.shenzjd.com` 等其他子站同样静默通过。
|
|
100
|
-
- **登录态统一会话级(2026-09-05)**:Cookie 不设 `expires`,浏览器进程关闭即失效、重新打开需重新扫码(2026-09-04 曾临时改为 3
|
|
106
|
+
- **登录态统一会话级(2026-09-05)**:Cookie 不设 `expires`,浏览器进程关闭即失效、重新打开需重新扫码(2026-09-04 曾临时改为 3 天持久,随激励解锁下线回退);同一浏览器会话内刷新/开新标签不丢(策略沿革见主仓库 AGENTS.md「登录态有效期」)。
|
|
101
107
|
- **⚠️ 多级公共后缀**:若页面域名属于 `.com.cn` / `.co.uk` 等多级后缀(如 `site.mysite.com.cn`),"取最后两段"会推导出 `.com.cn`,浏览器会拒绝写入。此类接入需确认域名后再接入。
|
|
102
108
|
|
|
103
109
|
> **为什么 cookie 不跟 apiBase 走?** 早期版本 SDK 曾按 apiBase 域名写 Cookie,导致部署在第三方域名(`apiBase` 指向微信认证后端、页面域名不同)时 Cookie 落错域、后端起总不到凭证、前端反复弹窗(死循环)。SDK 已改为始终按「页面所在域」写 Cookie,与后端地址无关。
|
|
@@ -106,7 +112,7 @@ SDK 会自动:
|
|
|
106
112
|
|
|
107
113
|
### `WxAuth.init(options)`
|
|
108
114
|
|
|
109
|
-
初始化 SDK。自动检测 Cookie
|
|
115
|
+
初始化 SDK。自动检测 Cookie,已登录静默通过,未登录弹出认证窗(小程序扫码)。
|
|
110
116
|
|
|
111
117
|
```ts
|
|
112
118
|
WxAuth.init({
|
|
@@ -120,7 +126,7 @@ WxAuth.init({
|
|
|
120
126
|
```
|
|
121
127
|
|
|
122
128
|
> `siteId` 无需配置:SDK 自动从 `document.referrer` 或当前域名获取并上报。
|
|
123
|
-
> `wechatName` / `qrcodeUrl`
|
|
129
|
+
> `wechatName` / `qrcodeUrl` 随公众号验证码登录一并临时停用(SDK 不再拉取 `/api/sdk/config`);恢复后仍由后端统一下发,接入方配置无效。
|
|
124
130
|
|
|
125
131
|
### `WxAuth.requireAuth()`
|
|
126
132
|
|
|
@@ -153,31 +159,27 @@ WxAuth.init({
|
|
|
153
159
|
│
|
|
154
160
|
├── 有效 ──────────── onVerified() ✅ 静默通过
|
|
155
161
|
│
|
|
156
|
-
└── 无效 ──→
|
|
162
|
+
└── 无效 ──→ 显示弹窗(小程序扫码,立即出码)
|
|
163
|
+
│
|
|
164
|
+
▼
|
|
165
|
+
微信扫码打开小程序
|
|
166
|
+
│
|
|
167
|
+
小程序内「确认登录」
|
|
168
|
+
│
|
|
169
|
+
网页轮询自动领取 Token
|
|
157
170
|
│
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
│ │
|
|
162
|
-
微信扫码打开小程序 扫码关注公众号
|
|
163
|
-
│ │
|
|
164
|
-
小程序内「确认登录」 发送"验证码"获取 6 位数字
|
|
165
|
-
│ │
|
|
166
|
-
网页轮询自动领取 Token 用户输入验证码 → 后端校验
|
|
167
|
-
│ │
|
|
168
|
-
└───────┬─────────────────┘
|
|
169
|
-
▼
|
|
170
|
-
保存 Cookie
|
|
171
|
-
onVerified()
|
|
171
|
+
▼
|
|
172
|
+
保存 Cookie
|
|
173
|
+
onVerified()
|
|
172
174
|
```
|
|
173
175
|
|
|
174
|
-
>
|
|
176
|
+
> 出码失败时停留在扫码面板,提供「刷新二维码」重试入口(原「自动切换到公众号验证码 Tab」降级路径已随该面板临时停用)。
|
|
175
177
|
|
|
176
178
|
---
|
|
177
179
|
|
|
178
180
|
## `onVerified(user)` 回调数据
|
|
179
181
|
|
|
180
|
-
|
|
182
|
+
登录成功后回调结构(对齐 `/api/auth/check`):
|
|
181
183
|
|
|
182
184
|
```ts
|
|
183
185
|
interface AuthUser {
|
|
@@ -205,10 +207,9 @@ interface AuthUser {
|
|
|
205
207
|
弹窗
|
|
206
208
|
┌──────────────────────────────────┐
|
|
207
209
|
│ 微信登录 │
|
|
208
|
-
│ [ 小程序登录 ] [ 公众号登录 ] │
|
|
209
210
|
│ │
|
|
210
211
|
│ ┌──────────┐ │
|
|
211
|
-
│ │ 小程序码 │ ←
|
|
212
|
+
│ │ 小程序码 │ ← 打开即出码 │
|
|
212
213
|
│ └──────────┘ │
|
|
213
214
|
│ 微信扫描二维码,打开小程序确认登录 │
|
|
214
215
|
└──────────────────────────────────┘
|
|
@@ -236,23 +237,20 @@ interface AuthUser {
|
|
|
236
237
|
|
|
237
238
|
| 功能 | 支持 |
|
|
238
239
|
|------|------|
|
|
239
|
-
|
|
|
240
|
-
| 默认小程序扫码、打开弹窗立即出码 | ✅ |
|
|
240
|
+
| 小程序扫码登录(打开弹窗立即出码) | ✅ |
|
|
241
241
|
| 小程序扫码无需输验证码(扫码 → 小程序内确认 → 网页自动登录) | ✅ |
|
|
242
|
-
| 出码失败自动回落公众号验证码 Tab | ✅ |
|
|
243
242
|
| 小程序码 5 分钟过期 + 一键刷新 | ✅ |
|
|
244
|
-
|
|
|
245
|
-
| 输入一位自动跳到下一格 | ✅ |
|
|
246
|
-
| 粘贴 6 位数字自动识别 | ✅ |
|
|
247
|
-
| 键盘左右/退格导航 | ✅ |
|
|
248
|
-
| 输入完成自动提交 | ✅ |
|
|
243
|
+
| 出码失败可在面板内「刷新二维码」重试 | ✅ |
|
|
249
244
|
| 有 Cookie 静默认证 | ✅ |
|
|
250
245
|
| Cookie 按页面根域写入(跨子域共享) | ✅ |
|
|
251
246
|
| 会话 Cookie 登录态(浏览器进程内共享,关闭即失效) | ✅ |
|
|
252
247
|
| 服务抖动/限流重试,不误清凭证、不误弹码框 | ✅ |
|
|
253
248
|
| F12 删弹窗自动恢复 | ✅ |
|
|
249
|
+
| ~~双 Tab 登录方式(小程序扫码 / 公众号验证码)~~ | ⛔ 2026-09-16 临时停用 |
|
|
250
|
+
| ~~出码失败自动回落公众号验证码 Tab~~ | ⛔ 改为面板内重试 |
|
|
251
|
+
| ~~验证码输入框(自动跳格 / 粘贴识别 / 键盘导航 / 自动提交)~~ | ⛔ 随公众号登录临时停用 |
|
|
254
252
|
|
|
255
|
-
> **登录态有效期(2026-09-05)**:web 登录态为**会话级**——Cookie 不设 `expires
|
|
253
|
+
> **登录态有效期(2026-09-05)**:web 登录态为**会话级**——Cookie 不设 `expires`,浏览器进程关闭即失效,重新打开浏览器需重新扫码。同一浏览器会话内刷新/开新标签页不丢登录态;不写 localStorage 备份。2026-09-04 曾短暂改为 3 天持久,随激励解锁下线回退(详见主仓库 AGENTS.md)。
|
|
256
254
|
|
|
257
255
|
---
|
|
258
256
|
|
|
@@ -264,7 +262,7 @@ wx-auth 不止是登录后端,还是**账号系统 + GitHub 能力平台**:
|
|
|
264
262
|
- 开通能力:`POST /api/github/setup`(建仓 + 挂仓,幂等)
|
|
265
263
|
- 领 token:`POST /api/github/token`(8 小时有效,浏览器直传 GitHub 用)
|
|
266
264
|
|
|
267
|
-
接入三步(引导 / 开通 / 领 token 直传)的完整话术见主仓库
|
|
265
|
+
接入三步(引导 / 开通 / 领 token 直传)的完整话术见主仓库 README「第三方接入话术」章节,或接入方案开环时直接联系我们获取接入说明。
|
|
268
266
|
|
|
269
267
|
---
|
|
270
268
|
|
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-header{background:#07c160;color:#fff;padding:16px
|
|
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:10px 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:8px;top:6px;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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const s = {
|
|
2
2
|
observer: null,
|
|
3
3
|
rafId: null,
|
|
4
4
|
isProtected: !1,
|
|
@@ -8,54 +8,54 @@ const i = {
|
|
|
8
8
|
* 启用弹窗保护
|
|
9
9
|
*/
|
|
10
10
|
enable(e) {
|
|
11
|
-
if (
|
|
12
|
-
|
|
13
|
-
for (const
|
|
14
|
-
if (
|
|
15
|
-
for (const
|
|
16
|
-
if (
|
|
17
|
-
const d =
|
|
11
|
+
if (s.isProtected || typeof window > "u") return;
|
|
12
|
+
s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !0, s.restorePending = !1, s.observer = new MutationObserver((o) => {
|
|
13
|
+
for (const r of o)
|
|
14
|
+
if (r.type === "childList")
|
|
15
|
+
for (const n of r.removedNodes) {
|
|
16
|
+
if (n.nodeType !== Node.ELEMENT_NODE) continue;
|
|
17
|
+
const d = n;
|
|
18
18
|
if (d.id === e.modalId || d.querySelector?.(`#${e.modalId}`)) {
|
|
19
19
|
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), p.safeRestore(e);
|
|
20
20
|
return;
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
-
}),
|
|
23
|
+
}), s.observer.observe(document.body, {
|
|
24
24
|
childList: !0,
|
|
25
25
|
subtree: !0
|
|
26
26
|
});
|
|
27
27
|
const t = () => {
|
|
28
|
-
if (!
|
|
28
|
+
if (!s.isProtected) return;
|
|
29
29
|
const { getState: o } = e;
|
|
30
30
|
if (!o().isOpen) {
|
|
31
|
-
|
|
31
|
+
s.rafId = null;
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
34
|
-
const
|
|
35
|
-
(!
|
|
34
|
+
const r = document.getElementById(e.modalId);
|
|
35
|
+
(!r || !r.isConnected || p.isHidden(r)) && (console.warn(
|
|
36
36
|
"[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
|
|
37
|
-
{ has: !!
|
|
38
|
-
), p.safeRestore(e)),
|
|
37
|
+
{ has: !!r, connected: r?.isConnected, hidden: r ? p.isHidden(r) : null }
|
|
38
|
+
), p.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
|
|
39
39
|
};
|
|
40
|
-
|
|
40
|
+
s.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
|
|
41
41
|
},
|
|
42
42
|
/**
|
|
43
43
|
* 禁用弹窗保护
|
|
44
44
|
*/
|
|
45
45
|
disable() {
|
|
46
|
-
|
|
46
|
+
s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !1, s.restorePending = !1, console.log("[WxAuth] 弹窗保护已禁用");
|
|
47
47
|
},
|
|
48
48
|
/**
|
|
49
49
|
* 同一帧内避免重复恢复
|
|
50
50
|
*/
|
|
51
51
|
safeRestore(e) {
|
|
52
|
-
if (!
|
|
53
|
-
|
|
52
|
+
if (!s.restorePending) {
|
|
53
|
+
s.restorePending = !0;
|
|
54
54
|
try {
|
|
55
55
|
p.restoreFn(e);
|
|
56
56
|
} finally {
|
|
57
57
|
requestAnimationFrame(() => {
|
|
58
|
-
|
|
58
|
+
s.restorePending = !1;
|
|
59
59
|
});
|
|
60
60
|
}
|
|
61
61
|
}
|
|
@@ -77,16 +77,16 @@ const i = {
|
|
|
77
77
|
* 恢复弹窗
|
|
78
78
|
*/
|
|
79
79
|
restoreFn(e) {
|
|
80
|
-
const { modalId: t, getState: o, onRestore:
|
|
80
|
+
const { modalId: t, getState: o, onRestore: r } = e;
|
|
81
81
|
if (!o().isOpen) return;
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
84
|
-
|
|
82
|
+
const n = document.getElementById(t);
|
|
83
|
+
if (n) {
|
|
84
|
+
n.style.display = "flex", n.style.visibility = "visible", n.style.opacity = "1";
|
|
85
85
|
return;
|
|
86
86
|
}
|
|
87
|
-
|
|
87
|
+
r();
|
|
88
88
|
}
|
|
89
|
-
},
|
|
89
|
+
}, C = {
|
|
90
90
|
apiBase: "https://wx-auth.shenzjd.com",
|
|
91
91
|
// 后端API地址(默认值)
|
|
92
92
|
onVerified: null,
|
|
@@ -104,13 +104,13 @@ const i = {
|
|
|
104
104
|
silent: !1
|
|
105
105
|
// 默认不静默
|
|
106
106
|
};
|
|
107
|
-
let
|
|
107
|
+
let i = { ...C }, c = "", x = "", a = {
|
|
108
108
|
isOpen: !1,
|
|
109
109
|
resolveAuth: null,
|
|
110
110
|
currentStep: "qr",
|
|
111
111
|
mpSession: null
|
|
112
|
-
}, f = "
|
|
113
|
-
function
|
|
112
|
+
}, f = "mp", h = 0;
|
|
113
|
+
function q(e) {
|
|
114
114
|
try {
|
|
115
115
|
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
116
116
|
return "";
|
|
@@ -120,9 +120,9 @@ function E(e) {
|
|
|
120
120
|
return "";
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
-
const
|
|
123
|
+
const u = {
|
|
124
124
|
getRootDomain() {
|
|
125
|
-
return
|
|
125
|
+
return q(window.location.hostname);
|
|
126
126
|
},
|
|
127
127
|
// 获取Cookie
|
|
128
128
|
getCookie(e) {
|
|
@@ -130,9 +130,9 @@ const l = {
|
|
|
130
130
|
return o.length === 2 && o.pop()?.split(";").shift() || null;
|
|
131
131
|
},
|
|
132
132
|
// Cookie 写入底层(domainStr 传空串 = host-only,落在当前 host 本域)
|
|
133
|
-
writeCookieRaw(e, t, o,
|
|
134
|
-
const d =
|
|
135
|
-
document.cookie = `${e}=${
|
|
133
|
+
writeCookieRaw(e, t, o, r, n = !1) {
|
|
134
|
+
const d = r ? `;domain=${r}` : "", A = window.location.protocol === "https:" ? ";Secure" : "", I = n ? ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : o !== void 0 ? `;expires=${new Date(Date.now() + o).toUTCString()}` : "";
|
|
135
|
+
document.cookie = `${e}=${n ? "" : t};path=/${d}${I}${A};SameSite=Strict`;
|
|
136
136
|
},
|
|
137
137
|
// 设置Cookie(2026-09-04:不传 maxAgeMs 时仍是会话 Cookie —— 浏览器关闭即失效;
|
|
138
138
|
// 传入 maxAgeMs 则写持久 Cookie;自动设置根域名实现跨子域共享)
|
|
@@ -140,8 +140,8 @@ const l = {
|
|
|
140
140
|
// pages.dev 等共享托管域,均在 Public Suffix List)禁止写 domain Cookie,
|
|
141
141
|
// 浏览器会静默丢弃导致登录态存不下来;此时降级为 host-only(落当前 host 本域)
|
|
142
142
|
setCookie(e, t, o) {
|
|
143
|
-
const
|
|
144
|
-
this.writeCookieRaw(e, t, o,
|
|
143
|
+
const r = this.getRootDomain();
|
|
144
|
+
this.writeCookieRaw(e, t, o, r), r && !this.getCookie(e) && this.writeCookieRaw(e, t, o, "");
|
|
145
145
|
},
|
|
146
146
|
// 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
|
|
147
147
|
// 2026-09-06:公共后缀域名降级场景下 cookie 可能是 host-only 写入的,
|
|
@@ -182,7 +182,7 @@ const l = {
|
|
|
182
182
|
// (Cookie 被清理/写入失败时从镜像恢复,避免设备身份漂移)。
|
|
183
183
|
// 注意:这是设备身份不是凭证——退出登录(clearToken/revoke)不清除它。
|
|
184
184
|
getOrCreateDeviceId() {
|
|
185
|
-
if (
|
|
185
|
+
if (x) return x;
|
|
186
186
|
let e = this.getCookie("wxauth-device");
|
|
187
187
|
if (!e)
|
|
188
188
|
try {
|
|
@@ -202,7 +202,7 @@ const l = {
|
|
|
202
202
|
window.localStorage.setItem("wxauth-device", e);
|
|
203
203
|
} catch {
|
|
204
204
|
}
|
|
205
|
-
return
|
|
205
|
+
return x = e, e;
|
|
206
206
|
},
|
|
207
207
|
// 发送请求
|
|
208
208
|
// 抛错带 status(HTTP 错误码)或 isNetworkError(断网/DNS/响应解析失败),
|
|
@@ -220,13 +220,13 @@ const l = {
|
|
|
220
220
|
credentials: "include"
|
|
221
221
|
});
|
|
222
222
|
if (!o.ok) {
|
|
223
|
-
const
|
|
224
|
-
throw
|
|
223
|
+
const r = new Error(`HTTP ${o.status}`);
|
|
224
|
+
throw r.status = o.status, r;
|
|
225
225
|
}
|
|
226
226
|
return await o.json();
|
|
227
227
|
} catch (o) {
|
|
228
|
-
const
|
|
229
|
-
throw
|
|
228
|
+
const r = o;
|
|
229
|
+
throw r.status === void 0 && (r.isNetworkError = !0), console.error("[WxAuth] Request error:", o), r;
|
|
230
230
|
}
|
|
231
231
|
},
|
|
232
232
|
// 生成6位验证码输入框HTML
|
|
@@ -236,30 +236,30 @@ const l = {
|
|
|
236
236
|
e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
|
|
237
237
|
return e += "</div>", e;
|
|
238
238
|
}
|
|
239
|
-
},
|
|
240
|
-
function
|
|
239
|
+
}, b = [1e3, 3e3];
|
|
240
|
+
function k(e) {
|
|
241
241
|
const t = e;
|
|
242
242
|
return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
|
|
243
243
|
}
|
|
244
|
-
function
|
|
244
|
+
function w(e) {
|
|
245
245
|
return new Promise((t) => setTimeout(t, e));
|
|
246
246
|
}
|
|
247
|
-
const
|
|
248
|
-
function
|
|
247
|
+
const E = 3e3, T = 2e3, M = 3e3;
|
|
248
|
+
function v() {
|
|
249
249
|
h++;
|
|
250
250
|
}
|
|
251
251
|
async function S(e) {
|
|
252
|
-
if (await
|
|
252
|
+
if (await w(E), !(e !== h || !a.isOpen)) {
|
|
253
253
|
for (; e === h && a.isOpen; ) {
|
|
254
254
|
const t = a.mpSession;
|
|
255
255
|
if (!t || Date.now() >= t.expiresAt) break;
|
|
256
256
|
try {
|
|
257
|
-
const o = await
|
|
258
|
-
`${
|
|
257
|
+
const o = await u.request(
|
|
258
|
+
`${i.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
|
|
259
259
|
);
|
|
260
260
|
if (e !== h) return;
|
|
261
261
|
if (o.status === "confirmed" && o.token) {
|
|
262
|
-
|
|
262
|
+
m.completeLogin(o);
|
|
263
263
|
return;
|
|
264
264
|
}
|
|
265
265
|
if (o.status === "expired") {
|
|
@@ -268,58 +268,35 @@ async function S(e) {
|
|
|
268
268
|
}
|
|
269
269
|
} catch (o) {
|
|
270
270
|
if (e !== h) return;
|
|
271
|
-
if (!
|
|
272
|
-
await
|
|
271
|
+
if (!k(o)) break;
|
|
272
|
+
await w(M);
|
|
273
273
|
continue;
|
|
274
274
|
}
|
|
275
|
-
await
|
|
275
|
+
await w(T);
|
|
276
276
|
}
|
|
277
|
-
e === h && a.isOpen && f === "mp" &&
|
|
277
|
+
e === h && a.isOpen && f === "mp" && l.showMpExpired();
|
|
278
278
|
}
|
|
279
279
|
}
|
|
280
280
|
async function g(e) {
|
|
281
|
-
const t =
|
|
282
|
-
for (let
|
|
281
|
+
const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `${i.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
|
|
282
|
+
for (let r = 0; ; r++)
|
|
283
283
|
try {
|
|
284
|
-
const
|
|
285
|
-
return
|
|
286
|
-
} catch (
|
|
287
|
-
if (!
|
|
284
|
+
const n = await u.request(o);
|
|
285
|
+
return n.authenticated ? { kind: "ok", result: n } : n.error === "rate_limited" || n.error === "server_error" ? { kind: "transient" } : { kind: "invalid", result: n };
|
|
286
|
+
} catch (n) {
|
|
287
|
+
if (!k(n) || r >= b.length)
|
|
288
288
|
return { kind: "transient" };
|
|
289
|
-
await
|
|
289
|
+
await w(b[r]);
|
|
290
290
|
}
|
|
291
291
|
}
|
|
292
|
-
const
|
|
293
|
-
let m = null;
|
|
294
|
-
function L() {
|
|
295
|
-
return !m || Date.now() >= m.expiresAt ? (m = null, null) : {
|
|
296
|
-
wechatName: m.wechatName,
|
|
297
|
-
qrcodeUrl: m.qrcodeUrl
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
async function P() {
|
|
301
|
-
const e = u ? `?siteId=${encodeURIComponent(u)}` : "", t = await l.request(
|
|
302
|
-
`${s.apiBase}/api/sdk/config${e}`
|
|
303
|
-
), o = {
|
|
304
|
-
wechatName: t.wechatName,
|
|
305
|
-
qrcodeUrl: t.qrcodeUrl
|
|
306
|
-
};
|
|
307
|
-
return m = { ...o, expiresAt: Date.now() + D }, o;
|
|
308
|
-
}
|
|
309
|
-
function R(e) {
|
|
310
|
-
e.wechatName && !s.wechatName && (s.wechatName = e.wechatName), e.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = e.qrcodeUrl);
|
|
311
|
-
}
|
|
312
|
-
const c = {
|
|
292
|
+
const l = {
|
|
313
293
|
// 创建弹窗
|
|
314
294
|
// 形态固定为双 tab(2026-08-30 去掉 mpScanEnabled 门控):形态不依赖 config,
|
|
315
295
|
// 弹窗从头到尾只有一种形态——「闪两次」(先公众号形态后双 tab)结构上不存在
|
|
316
296
|
createModal() {
|
|
317
297
|
const e = document.createElement("div");
|
|
318
|
-
e.id = "wx-auth-modal", e.className = "wx-auth-modal",
|
|
319
|
-
const t =
|
|
320
|
-
<button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
|
|
321
|
-
<button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
|
|
322
|
-
</div>`, n = `<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
|
|
298
|
+
e.id = "wx-auth-modal", e.className = "wx-auth-modal", i.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
|
|
299
|
+
const t = i.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>', o = "", r = "", n = `<div class="wx-auth-panel wx-auth-panel-mp">
|
|
323
300
|
<div class="wx-auth-qrcode-container wx-auth-mp-container">
|
|
324
301
|
<div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
|
|
325
302
|
<img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
|
|
@@ -332,7 +309,7 @@ const c = {
|
|
|
332
309
|
<div class="wx-auth-mp-status"></div>
|
|
333
310
|
</div>`;
|
|
334
311
|
return e.innerHTML = `
|
|
335
|
-
<div class="wx-auth-overlay" ${
|
|
312
|
+
<div class="wx-auth-overlay" ${i.required ? 'onclick="event.preventDefault()"' : ""}></div>
|
|
336
313
|
<div class="wx-auth-content">
|
|
337
314
|
<div class="wx-auth-header">
|
|
338
315
|
<div class="wx-auth-title">微信登录</div>
|
|
@@ -341,29 +318,10 @@ const c = {
|
|
|
341
318
|
<div class="wx-auth-body">
|
|
342
319
|
${o}
|
|
343
320
|
|
|
344
|
-
<!--
|
|
345
|
-
|
|
346
|
-
<!-- 二维码区域 -->
|
|
347
|
-
<div>
|
|
348
|
-
<div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
|
|
349
|
-
<div class="wx-auth-qrcode-container">
|
|
350
|
-
<img class="wx-auth-qrcode" src="" alt="扫码关注" />
|
|
351
|
-
</div>
|
|
352
|
-
</div>
|
|
353
|
-
|
|
354
|
-
<!-- 验证码输入区域 -->
|
|
355
|
-
<div>
|
|
356
|
-
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
357
|
-
${l.generateCodeInputs()}
|
|
358
|
-
</div>
|
|
359
|
-
|
|
360
|
-
<!-- 按钮 -->
|
|
361
|
-
<div class="wx-auth-actions">
|
|
362
|
-
<button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
|
|
363
|
-
</div>
|
|
364
|
-
</div>
|
|
321
|
+
<!-- 面板一:公众号验证码(临时停用 2026-09-16,内容见上方 codePanelHtml 注释) -->
|
|
322
|
+
${r}
|
|
365
323
|
|
|
366
|
-
<!--
|
|
324
|
+
<!-- 面板二:小程序扫码(当前唯一登录方式) -->
|
|
367
325
|
${n}
|
|
368
326
|
|
|
369
327
|
<!-- 消息提示 -->
|
|
@@ -377,18 +335,18 @@ const c = {
|
|
|
377
335
|
setTimeout(() => {
|
|
378
336
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
379
337
|
e.length && e.forEach((t, o) => {
|
|
380
|
-
t.addEventListener("input", (
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
}), t.addEventListener("keydown", (
|
|
384
|
-
const
|
|
385
|
-
|
|
386
|
-
}), t.addEventListener("paste", (
|
|
387
|
-
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
e[
|
|
391
|
-
}),
|
|
338
|
+
t.addEventListener("input", (r) => {
|
|
339
|
+
const n = r.target.value.replace(/\D/g, "");
|
|
340
|
+
r.target.value = n, n && o < 5 && e[o + 1].focus(), o === 5 && n && setTimeout(() => m.verifyCode(), 300);
|
|
341
|
+
}), t.addEventListener("keydown", (r) => {
|
|
342
|
+
const n = r.target;
|
|
343
|
+
r.key === "Backspace" && !n.value && o > 0 ? e[o - 1].focus() : r.key === "ArrowLeft" && o > 0 ? (r.preventDefault(), e[o - 1].focus()) : r.key === "ArrowRight" && o < 5 && (r.preventDefault(), e[o + 1].focus());
|
|
344
|
+
}), t.addEventListener("paste", (r) => {
|
|
345
|
+
r.preventDefault();
|
|
346
|
+
const n = r.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
347
|
+
n && (n.split("").forEach((d, y) => {
|
|
348
|
+
e[y] && (e[y].value = d);
|
|
349
|
+
}), n.length === 6 && setTimeout(() => m.verifyCode(), 300));
|
|
392
350
|
});
|
|
393
351
|
});
|
|
394
352
|
}, 100);
|
|
@@ -396,19 +354,17 @@ const c = {
|
|
|
396
354
|
// 显示弹窗
|
|
397
355
|
show() {
|
|
398
356
|
let e = document.getElementById("wx-auth-modal");
|
|
399
|
-
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"),
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
const n = e.querySelector(".wx-auth-btn-primary");
|
|
403
|
-
n && (n.disabled = !1, n.textContent = "登录", n.style.background = ""), k(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, p.enable({
|
|
357
|
+
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), i.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal();
|
|
358
|
+
const t = e.querySelector(".wx-auth-message");
|
|
359
|
+
t && (t.textContent = "", t.className = "wx-auth-message", t.style.display = "none"), v(), a.mpSession = null, e.style.display = "flex", a.isOpen = !0, p.enable({
|
|
404
360
|
modalId: "wx-auth-modal",
|
|
405
361
|
getState: () => a,
|
|
406
362
|
onRestore: () => {
|
|
407
|
-
this.createModal(),
|
|
408
|
-
const
|
|
409
|
-
|
|
410
|
-
const
|
|
411
|
-
|
|
363
|
+
this.createModal(), i.qrcodeUrl && this.setQrCode(i.qrcodeUrl);
|
|
364
|
+
const o = document.querySelector(".wx-auth-wechat-name");
|
|
365
|
+
o && i.wechatName && (o.textContent = `"${i.wechatName}"`), this.bindInputEvents(), f === "mp" && m.switchMode("mp"), setTimeout(() => {
|
|
366
|
+
const r = document.querySelector(".wx-auth-input");
|
|
367
|
+
r && r.focus();
|
|
412
368
|
}, 100);
|
|
413
369
|
}
|
|
414
370
|
});
|
|
@@ -416,7 +372,7 @@ const c = {
|
|
|
416
372
|
// 隐藏弹窗
|
|
417
373
|
hide() {
|
|
418
374
|
const e = document.getElementById("wx-auth-modal");
|
|
419
|
-
e && (e.style.display = "none", a.isOpen = !1,
|
|
375
|
+
e && (e.style.display = "none", a.isOpen = !1, v(), a.mpSession = null, p.disable());
|
|
420
376
|
},
|
|
421
377
|
// 设置二维码
|
|
422
378
|
setQrCode(e) {
|
|
@@ -427,8 +383,8 @@ const c = {
|
|
|
427
383
|
// ===== 小程序扫码面板(2026-08-29)=====
|
|
428
384
|
// 展示小程序码(隐藏 loading 与过期遮罩,保持画面干净)
|
|
429
385
|
setMpQr(e) {
|
|
430
|
-
const t = document.getElementById("wx-auth-modal"), o = t?.querySelector(".wx-auth-mp-qrcode"),
|
|
431
|
-
o && (o.src = e, o.style.display = "block",
|
|
386
|
+
const t = document.getElementById("wx-auth-modal"), o = t?.querySelector(".wx-auth-mp-qrcode"), r = t?.querySelector(".wx-auth-mp-loading");
|
|
387
|
+
o && (o.src = e, o.style.display = "block", r && (r.style.display = "none"), this.setMpExpiredVisible(!1), this.setMpStatus("", !1));
|
|
432
388
|
},
|
|
433
389
|
// 过期遮罩显示/隐藏:盖在二维码上(「二维码已过期」+ 绿色刷新按钮)
|
|
434
390
|
setMpExpiredVisible(e) {
|
|
@@ -437,17 +393,19 @@ const c = {
|
|
|
437
393
|
},
|
|
438
394
|
// 更新扫码面板状态文案;text 为空 = 隐藏状态行;spinner=true 时回列出码 loading
|
|
439
395
|
setMpStatus(e, t) {
|
|
440
|
-
const o = document.getElementById("wx-auth-modal"),
|
|
441
|
-
|
|
442
|
-
const
|
|
443
|
-
if (
|
|
396
|
+
const o = document.getElementById("wx-auth-modal"), r = o?.querySelector(".wx-auth-mp-status");
|
|
397
|
+
r && (r.textContent = e, r.style.display = e ? "block" : "none");
|
|
398
|
+
const n = o?.querySelector(".wx-auth-mp-loading");
|
|
399
|
+
if (n && (n.style.display = t ? "flex" : "none"), t) {
|
|
444
400
|
const d = o?.querySelector(".wx-auth-mp-qrcode");
|
|
445
401
|
d && (d.style.display = "none");
|
|
446
402
|
}
|
|
447
403
|
},
|
|
448
404
|
// 二维码过期/失效:遮罩盖住旧码,用户点「刷新二维码」重新出码
|
|
449
|
-
|
|
450
|
-
|
|
405
|
+
// text:遮罩文案(出码失败时复用同一遮罩,让用户有重试入口)
|
|
406
|
+
showMpExpired(e = "二维码已过期") {
|
|
407
|
+
const o = document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired-text");
|
|
408
|
+
o && (o.textContent = e), this.setMpExpiredVisible(!0);
|
|
451
409
|
},
|
|
452
410
|
// 显示消息
|
|
453
411
|
showMessage(e, t = "info") {
|
|
@@ -466,10 +424,10 @@ const c = {
|
|
|
466
424
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
467
425
|
e.forEach((t) => t.value = ""), e[0] && e[0].focus();
|
|
468
426
|
}
|
|
469
|
-
},
|
|
427
|
+
}, m = {
|
|
470
428
|
// 初始化
|
|
471
429
|
init(e = {}) {
|
|
472
|
-
if (
|
|
430
|
+
if (i = { ...C, ...e }, !i.apiBase && typeof window < "u" && (i.apiBase = window.location.origin), !i.apiBase) {
|
|
473
431
|
console.error("[WxAuth] apiBase is required");
|
|
474
432
|
return;
|
|
475
433
|
}
|
|
@@ -477,14 +435,14 @@ const c = {
|
|
|
477
435
|
const t = document.referrer;
|
|
478
436
|
if (t)
|
|
479
437
|
try {
|
|
480
|
-
|
|
438
|
+
c = new URL(t).hostname;
|
|
481
439
|
} catch {
|
|
482
440
|
}
|
|
483
|
-
!
|
|
484
|
-
const o =
|
|
441
|
+
!c && window.location.hostname && (c = window.location.hostname), c || (c = "default"), console.log("[WxAuth] 自动获取 siteId:", c);
|
|
442
|
+
const o = u.getOrCreateDeviceId();
|
|
485
443
|
console.log("[WxAuth] deviceId:", o);
|
|
486
444
|
}
|
|
487
|
-
console.log("[WxAuth] SDK initialized",
|
|
445
|
+
console.log("[WxAuth] SDK initialized", i), typeof window < "u" && (i.silent ? this.silentCheck() : this.autoCheck());
|
|
488
446
|
},
|
|
489
447
|
/**
|
|
490
448
|
* 静默验证(silent 模式专用)
|
|
@@ -496,66 +454,56 @@ const c = {
|
|
|
496
454
|
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
497
455
|
*/
|
|
498
456
|
async silentCheck() {
|
|
499
|
-
const e =
|
|
457
|
+
const e = u.getToken();
|
|
500
458
|
if (!e) return !1;
|
|
501
459
|
const t = await g(e);
|
|
502
|
-
return t.kind === "ok" ? (t.result.token &&
|
|
460
|
+
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);
|
|
503
461
|
},
|
|
504
462
|
// 自动检测凭证并验证(内部使用)
|
|
505
463
|
async autoCheck() {
|
|
506
|
-
const e =
|
|
464
|
+
const e = u.getToken();
|
|
507
465
|
if (!e)
|
|
508
466
|
return this.showAuthModal(), !1;
|
|
509
467
|
const t = await g(e);
|
|
510
|
-
return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token &&
|
|
468
|
+
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({
|
|
511
469
|
code: "server_error",
|
|
512
470
|
retryable: !0,
|
|
513
471
|
message: "登录服务暂时不可用,请稍后重试"
|
|
514
472
|
}), !1) : (this.showAuthModal(), !1);
|
|
515
473
|
},
|
|
516
474
|
// 显示认证弹窗(内部使用)
|
|
517
|
-
// 2026-08-30
|
|
518
|
-
//
|
|
519
|
-
//
|
|
475
|
+
// 2026-08-30 修复「弹窗闪两次」:UI.show() 同步渲染 + 小程序扫码立即出码,
|
|
476
|
+
// 全程只有一种形态,无中间态。
|
|
477
|
+
// 2026-09-16:公众号验证码面板临时停用 → 只保留小程序扫码面板,
|
|
478
|
+
// 也不再拉取 /api/sdk/config(原用于填充公众号名称 / 关注二维码)。
|
|
520
479
|
async showAuthModal() {
|
|
521
|
-
|
|
522
|
-
let e = L();
|
|
523
|
-
if (!e)
|
|
524
|
-
try {
|
|
525
|
-
e = await P();
|
|
526
|
-
} catch (o) {
|
|
527
|
-
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", o);
|
|
528
|
-
}
|
|
529
|
-
e && R(e), s.qrcodeUrl && c.setQrCode(s.qrcodeUrl);
|
|
530
|
-
const t = document.querySelector(".wx-auth-wechat-name");
|
|
531
|
-
t && s.wechatName && (t.textContent = `"${s.wechatName}"`), setTimeout(() => {
|
|
532
|
-
const o = document.querySelector(".wx-auth-input");
|
|
533
|
-
o && o.focus();
|
|
534
|
-
}, 100);
|
|
480
|
+
l.show(), this.switchMode("mp");
|
|
535
481
|
},
|
|
536
|
-
//
|
|
482
|
+
// 切换登录方式(默认模式设定)
|
|
483
|
+
// 2026-09-16:公众号验证码面板临时停用,弹窗只剩小程序面板,
|
|
484
|
+
// 内部只以 "mp" 调用;"code" 分支保留,便于恢复及老接入方调用。
|
|
537
485
|
switchMode(e) {
|
|
538
486
|
f = e;
|
|
539
487
|
const t = document.getElementById("wx-auth-modal");
|
|
540
488
|
if (!t) return;
|
|
541
|
-
t.querySelectorAll(".wx-auth-tab").forEach((
|
|
542
|
-
|
|
489
|
+
t.querySelectorAll(".wx-auth-tab").forEach((n) => {
|
|
490
|
+
n.classList.toggle("wx-auth-tab-active", n.dataset.mode === f);
|
|
543
491
|
});
|
|
544
|
-
const o = t.querySelector(".wx-auth-panel-code"),
|
|
545
|
-
o && (o.style.display = f === "code" ? "" : "none"),
|
|
492
|
+
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() : v();
|
|
546
494
|
},
|
|
547
495
|
// 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
|
|
548
496
|
async startMpLogin() {
|
|
549
497
|
if (!a.isOpen) return;
|
|
550
498
|
const e = ++h;
|
|
551
|
-
if (
|
|
552
|
-
|
|
499
|
+
if (l.setMpExpiredVisible(!1), l.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
|
|
500
|
+
l.setMpQr(a.mpSession.qrDataUrl), S(e);
|
|
553
501
|
return;
|
|
554
502
|
}
|
|
555
503
|
try {
|
|
556
|
-
const t = await
|
|
504
|
+
const t = await u.request(`${i.apiBase}/api/auth/mp-scan/create`, {
|
|
557
505
|
method: "POST",
|
|
558
|
-
body: { siteId:
|
|
506
|
+
body: { siteId: c }
|
|
559
507
|
});
|
|
560
508
|
if (e !== h || !a.isOpen) return;
|
|
561
509
|
if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
|
|
@@ -563,21 +511,21 @@ const c = {
|
|
|
563
511
|
ticket: String(t.ticket),
|
|
564
512
|
qrDataUrl: String(t.qrDataUrl),
|
|
565
513
|
expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
|
|
566
|
-
},
|
|
514
|
+
}, l.setMpQr(a.mpSession.qrDataUrl), S(e);
|
|
567
515
|
} catch (t) {
|
|
568
516
|
if (e !== h || !a.isOpen) return;
|
|
569
|
-
console.warn("[WxAuth]
|
|
517
|
+
console.warn("[WxAuth] 小程序码生成失败", t), l.setMpStatus("", !1), l.showMpExpired("二维码生成失败,请点下方按钮重试"), l.showMessage("小程序扫码暂不可用,请稍后重试", "error");
|
|
570
518
|
}
|
|
571
519
|
},
|
|
572
520
|
// 主入口:需要验证时调用
|
|
573
521
|
// 凭证仅签名 Token(登录 Cookie,会话级,2026-09-05),不再兼容明文 openid
|
|
574
522
|
// (2026-08-26 服务端已下线 openid 通道)
|
|
575
523
|
async requireAuth() {
|
|
576
|
-
const e =
|
|
524
|
+
const e = u.getToken();
|
|
577
525
|
if (e) {
|
|
578
526
|
const t = await g(e);
|
|
579
527
|
if (t.kind === "ok")
|
|
580
|
-
return console.log("[WxAuth] 已认证(凭证)"), t.result.token &&
|
|
528
|
+
return console.log("[WxAuth] 已认证(凭证)"), t.result.token && u.setToken(t.result.token), this.onVerified(t.result.user), !0;
|
|
581
529
|
if (t.kind === "transient")
|
|
582
530
|
return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"), this.onError({
|
|
583
531
|
code: "server_error",
|
|
@@ -594,8 +542,8 @@ const c = {
|
|
|
594
542
|
// 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
|
|
595
543
|
// close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
|
|
596
544
|
completeLogin(e) {
|
|
597
|
-
if (e?.token &&
|
|
598
|
-
|
|
545
|
+
if (e?.token && u.setToken(e.token), f === "mp")
|
|
546
|
+
l.setMpStatus("✅ 登录成功", !1);
|
|
599
547
|
else {
|
|
600
548
|
const t = document.querySelector(".wx-auth-btn-primary");
|
|
601
549
|
t && (t.textContent = "✅ 已登录", t.style.background = "#07C160");
|
|
@@ -604,11 +552,13 @@ const c = {
|
|
|
604
552
|
this.onVerified(e?.user), this.close(!0);
|
|
605
553
|
}, 500);
|
|
606
554
|
},
|
|
607
|
-
//
|
|
555
|
+
// 验证验证码(公众号验证码登录专用)
|
|
556
|
+
// 2026-09-16:公众号登录临时停用 → 弹窗内已无验证码输入框与登录入口,
|
|
557
|
+
// 此方法保留(老接入方直调 / 恢复时可直接复用),正常链路不会被触发。
|
|
608
558
|
async verifyCode() {
|
|
609
|
-
const e =
|
|
559
|
+
const e = l.getVerifyCode();
|
|
610
560
|
if (!e || e.length !== 6) {
|
|
611
|
-
|
|
561
|
+
l.showMessage("请输入6位验证码", "error");
|
|
612
562
|
return;
|
|
613
563
|
}
|
|
614
564
|
const t = document.querySelector(
|
|
@@ -616,16 +566,16 @@ const c = {
|
|
|
616
566
|
);
|
|
617
567
|
t && (t.disabled = !0, t.textContent = "登录中...");
|
|
618
568
|
try {
|
|
619
|
-
const o =
|
|
620
|
-
`${
|
|
569
|
+
const o = c ? `&siteId=${encodeURIComponent(c)}` : "", r = `&deviceId=${encodeURIComponent(u.getOrCreateDeviceId())}`, n = await u.request(
|
|
570
|
+
`${i.apiBase}/api/auth/check?authToken=${e}${o}${r}`
|
|
621
571
|
);
|
|
622
|
-
|
|
623
|
-
|
|
572
|
+
n.authenticated ? this.completeLogin(n) : (l.showMessage(
|
|
573
|
+
n.error === "rate_limited" ? "尝试过于频繁,请稍后再试" : "验证码错误或已过期",
|
|
624
574
|
"error"
|
|
625
|
-
),
|
|
575
|
+
), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
|
|
626
576
|
} catch (o) {
|
|
627
|
-
|
|
628
|
-
|
|
577
|
+
l.showMessage(
|
|
578
|
+
k(o) ? "服务暂时不可用,请稍后重试" : "登录失败,请重试",
|
|
629
579
|
"error"
|
|
630
580
|
), t && (t.disabled = !1, t.textContent = "登录");
|
|
631
581
|
}
|
|
@@ -634,12 +584,12 @@ const c = {
|
|
|
634
584
|
// skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
|
|
635
585
|
// (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
|
|
636
586
|
close(e = !1) {
|
|
637
|
-
|
|
587
|
+
l.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), !e && typeof i.onClose == "function" && i.onClose();
|
|
638
588
|
},
|
|
639
589
|
// 清空本地认证凭证(Cookie + 旧版本 localStorage 备份的防御性清理)
|
|
640
590
|
// 用于"退出登录 / 清空认证状态"按钮。
|
|
641
591
|
clearToken() {
|
|
642
|
-
|
|
592
|
+
u.clearToken();
|
|
643
593
|
},
|
|
644
594
|
// 服务端注销(2026-08-26 方案 C):吊销当前 token + 清本地
|
|
645
595
|
// 调用 POST {apiBase}/api/auth/logout(body.token),后端把 token 加入
|
|
@@ -650,14 +600,14 @@ const c = {
|
|
|
650
600
|
// 已知取舍(2026-08-29):海外 fork 站(非 *.shenzjd.com)Origin 会被后端 403,
|
|
651
601
|
// 本地清理照常生效,但服务端 token 仍有效(换取吊销入口不被第三方页面滥用)。
|
|
652
602
|
async revoke() {
|
|
653
|
-
const e =
|
|
603
|
+
const e = u.getToken();
|
|
654
604
|
if (e)
|
|
655
605
|
try {
|
|
656
|
-
const t =
|
|
606
|
+
const t = i.apiBase && !/\/$/.test(i.apiBase) ? i.apiBase : "https://wx-auth.shenzjd.com", o = await fetch(`${t}/api/auth/logout`, {
|
|
657
607
|
method: "POST",
|
|
658
608
|
headers: { "Content-Type": "application/json" },
|
|
659
609
|
// deviceId 显式携带(跨站 SameSite 下 Cookie 不可靠);设备身份不因退出而清除
|
|
660
|
-
body: JSON.stringify({ token: e, deviceId:
|
|
610
|
+
body: JSON.stringify({ token: e, deviceId: u.getOrCreateDeviceId() }),
|
|
661
611
|
credentials: "include"
|
|
662
612
|
});
|
|
663
613
|
o.ok || console.warn("[WxAuth] revoke 请求失败,降级本地清理", o.status);
|
|
@@ -668,14 +618,14 @@ const c = {
|
|
|
668
618
|
},
|
|
669
619
|
// 验证成功回调
|
|
670
620
|
onVerified(e) {
|
|
671
|
-
console.log("[WxAuth] 验证成功", e), typeof
|
|
621
|
+
console.log("[WxAuth] 验证成功", e), typeof i.onVerified == "function" && i.onVerified(e), a.resolveAuth && (a.resolveAuth(!0), a.resolveAuth = null);
|
|
672
622
|
},
|
|
673
623
|
// 错误回调
|
|
674
624
|
onError(e) {
|
|
675
|
-
console.error("[WxAuth] 错误", e), typeof
|
|
625
|
+
console.error("[WxAuth] 错误", e), typeof i.onError == "function" && i.onError(e);
|
|
676
626
|
}
|
|
677
627
|
};
|
|
678
|
-
typeof window < "u" && (window.WxAuth = Object.freeze(
|
|
628
|
+
typeof window < "u" && (window.WxAuth = Object.freeze(m));
|
|
679
629
|
export {
|
|
680
|
-
|
|
630
|
+
m as WxAuth
|
|
681
631
|
};
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
(function(w
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(
|
|
3
|
-
<button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
|
|
4
|
-
<button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
|
|
5
|
-
</div>`,n=`<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
|
|
1
|
+
(function(x,w){typeof exports=="object"&&typeof module<"u"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(x=typeof globalThis<"u"?globalThis:x||self,w(x.WxAuthSDK={}))})(this,(function(x){"use strict";var w=document.createElement("style");w.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;padding:10px 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:8px;top:6px;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(w);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 h=r;if(h.id===e.modalId||h.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()}},C={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...C},c="",y="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},p="mp",d=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 l={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 h=n?`;domain=${n}`:"",D=window.location.protocol==="https:"?";Secure":"",$=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=/${h}${$}${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(y)return y;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 y=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 b(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function g(e){return new Promise(t=>setTimeout(t,e))}const E=3e3,T=2e3,M=3e3;function k(){d++}async function q(e){if(await g(E),!(e!==d||!s.isOpen)){for(;e===d&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await l.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==d)return;if(o.status==="confirmed"&&o.token){m.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==d)return;if(!b(o))break;await g(M);continue}await g(T)}e===d&&s.isOpen&&p==="mp"&&u.showMpExpired()}}async function v(e){const t=c?`&siteId=${encodeURIComponent(c)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await l.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!b(r)||n>=A.length)return{kind:"transient"};await g(A[n])}}const u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>',o="",n="",r=`<div class="wx-auth-panel wx-auth-panel-mp">
|
|
6
3
|
<div class="wx-auth-qrcode-container wx-auth-mp-container">
|
|
7
4
|
<div class="wx-auth-mp-loading"><span class="wx-auth-spinner"></span></div>
|
|
8
5
|
<img class="wx-auth-mp-qrcode" src="" alt="小程序码" style="display:none" />
|
|
@@ -23,33 +20,14 @@
|
|
|
23
20
|
<div class="wx-auth-body">
|
|
24
21
|
${o}
|
|
25
22
|
|
|
26
|
-
<!--
|
|
27
|
-
<div class="wx-auth-panel wx-auth-panel-code">
|
|
28
|
-
<!-- 二维码区域 -->
|
|
29
|
-
<div>
|
|
30
|
-
<div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
|
|
31
|
-
<div class="wx-auth-qrcode-container">
|
|
32
|
-
<img class="wx-auth-qrcode" src="" alt="扫码关注" />
|
|
33
|
-
</div>
|
|
34
|
-
</div>
|
|
35
|
-
|
|
36
|
-
<!-- 验证码输入区域 -->
|
|
37
|
-
<div>
|
|
38
|
-
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
39
|
-
${c.generateCodeInputs()}
|
|
40
|
-
</div>
|
|
41
|
-
|
|
42
|
-
<!-- 按钮 -->
|
|
43
|
-
<div class="wx-auth-actions">
|
|
44
|
-
<button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">登录</button>
|
|
45
|
-
</div>
|
|
46
|
-
</div>
|
|
47
|
-
|
|
48
|
-
<!-- 面板二:小程序扫码 -->
|
|
23
|
+
<!-- 面板一:公众号验证码(临时停用 2026-09-16,内容见上方 codePanelHtml 注释) -->
|
|
49
24
|
${n}
|
|
50
25
|
|
|
26
|
+
<!-- 面板二:小程序扫码(当前唯一登录方式) -->
|
|
27
|
+
${r}
|
|
28
|
+
|
|
51
29
|
<!-- 消息提示 -->
|
|
52
30
|
<div class="wx-auth-message" style="display:none"></div>
|
|
53
31
|
</div>
|
|
54
32
|
</div>
|
|
55
|
-
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>
|
|
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(()=>m.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((h,S)=>{e[S]&&(e[S].value=h)}),r.length===6&&setTimeout(()=>m.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal();const t=e.querySelector(".wx-auth-message");t&&(t.textContent="",t.className="wx-auth-message",t.style.display="none"),k(),s.mpSession=null,e.style.display="flex",s.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const o=document.querySelector(".wx-auth-wechat-name");o&&a.wechatName&&(o.textContent=`"${a.wechatName}"`),this.bindInputEvents(),p==="mp"&&m.switchMode("mp"),setTimeout(()=>{const n=document.querySelector(".wx-auth-input");n&&n.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",s.isOpen=!1,k(),s.mpSession=null,f.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},setMpQr(e){const t=document.getElementById("wx-auth-modal"),o=t?.querySelector(".wx-auth-mp-qrcode"),n=t?.querySelector(".wx-auth-mp-loading");o&&(o.src=e,o.style.display="block",n&&(n.style.display="none"),this.setMpExpiredVisible(!1),this.setMpStatus("",!1))},setMpExpiredVisible(e){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");o&&(o.style.display=e?"flex":"none")},setMpStatus(e,t){const o=document.getElementById("wx-auth-modal"),n=o?.querySelector(".wx-auth-mp-status");n&&(n.textContent=e,n.style.display=e?"block":"none");const r=o?.querySelector(".wx-auth-mp-loading");if(r&&(r.style.display=t?"flex":"none"),t){const h=o?.querySelector(".wx-auth-mp-qrcode");h&&(h.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()}},m={init(e={}){if(a={...C,...e},!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{c=new URL(t).hostname}catch{}!c&&window.location.hostname&&(c=window.location.hostname),c||(c="default"),console.log("[WxAuth] 自动获取 siteId:",c);const o=l.getOrCreateDeviceId();console.log("[WxAuth] deviceId:",o)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=l.getToken();if(!e)return!1;const t=await v(e);return t.kind==="ok"?(t.result.token&&l.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=l.getToken();if(!e)return this.showAuthModal(),!1;const t=await v(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&l.setToken(t.result.token),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(){u.show(),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():k()},async startMpLogin(){if(!s.isOpen)return;const e=++d;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){u.setMpQr(s.mpSession.qrDataUrl),q(e);return}try{const t=await l.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:c}});if(e!==d||!s.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");s.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(s.mpSession.qrDataUrl),q(e)}catch(t){if(e!==d||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败",t),u.setMpStatus("",!1),u.showMpExpired("二维码生成失败,请点下方按钮重试"),u.showMessage("小程序扫码暂不可用,请稍后重试","error")}},async requireAuth(){const e=l.getToken();if(e){const t=await v(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&l.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{s.resolveAuth=t})},completeLogin(e){if(e?.token&&l.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=c?`&siteId=${encodeURIComponent(c)}`:"",n=`&deviceId=${encodeURIComponent(l.getOrCreateDeviceId())}`,r=await l.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}${n}`);r.authenticated?this.completeLogin(r):(u.showMessage(r.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(b(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){l.clearToken()},async revoke(){const e=l.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceId:l.getOrCreateDeviceId()}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof a.onVerified=="function"&&a.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(m)),x.WxAuth=m,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})}));
|