bjchy-udg-sdk 1.8.1 → 1.8.3

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 CHANGED
@@ -69,7 +69,7 @@ const { token, openId } = await client.login() // openId 同时写入 JWT;
69
69
 
70
70
  // ①b web-view 内的 H5:拿不到 wx.login,由宿主小程序传 code 进来(详见下方「web-view 内 H5 的登录」)
71
71
  const { token, openId } = await client.login({ code })
72
- // 目标租户关联了多个小程序时,还要带上宿主小程序的 appId(见下方「一个租户关联多个小程序」)
72
+ // 多小程序租户:SDK 会从 UA(或 URL 的 miniAppId/appid)自动带上宿主 appId;仍可显式覆盖
73
73
  const r = await client.login({ code, miniAppId: 'wx8c6e005797744382' })
74
74
 
75
75
  // ①c 公众号内打开的 H5:微信网页授权回调把 code 带回本页(详见下方「公众号 H5 的登录与 JSSDK」)
@@ -127,7 +127,7 @@ await client.login({ code: new URLSearchParams(location.search).get('c') })
127
127
  注意事项:
128
128
 
129
129
  - **不要改传 token**:URL 里的长效 JWT 在有效期内可被完全冒充,且 `init({ token })` 是 external 模式,SDK 不为它续期、过期即失效。
130
- - **`code` 由哪个小程序签发,该租户就要关联同一个小程序**:网关拿 `appid` 查到该租户关联的小程序(管理后台配置,未配置则沿用 `appid` 本身)去调微信 `jscode2session`,与 `code` 的签发方不一致会拿到 `40013 invalid appid`。租户只关联一个小程序时,SDK/客户端参数不变;关联多个时才需要 `login({ code, miniAppId })` 指明是哪一个(见下节)。
130
+ - **`code` 由哪个小程序签发,该租户就要关联同一个小程序**:网关拿 `appid` 查到该租户关联的小程序(管理后台配置,未配置则沿用 `appid` 本身)去调微信 `jscode2session`,与 `code` 的签发方不一致会拿到 `40013 invalid appid`。租户只关联一个小程序时参数不变;关联多个时 SDK 会从 UA / URL 自动带上宿主 `miniAppId`(也可显式传入,见下节)。
131
131
  - **页面刷新**:`login()` 幂等,缓存 token 未过期时直接复用,不会再用已废的 code;前提是 H5 每次 `init` 传的 `appid` 一致(token 存储键依赖它)。
132
132
  - **refreshToken 也过期时**:H5 拿不到新 code,SDK 的自动重登会返回失败并抛鉴权错误(这是预期行为)。业务兜底:`wx.miniProgram.redirectTo` 回中转页重取 code。注意 `wx.miniProgram.postMessage` **不是实时的**(小程序只在分享/复制链接/后退/组件销毁时才收到),不能用它通知小程序。
133
133
  - **CORS**:H5 域名需在 Gateway 的跨域白名单里。
@@ -183,28 +183,51 @@ await client.wx.sendSubscribeMessage({
183
183
  微信公众号(服务号)里打开的 H5,用**网页授权**拿 openid,再用 code 换 UDG token。公众号凭据配在 Gateway 的 `.env`(全网关一份),**目标租户需在管理后台打开「公众号登录」开关**(默认关闭)。
184
184
 
185
185
  ```js
186
- // ① 页面加载时:URL 上没有 code 就跳去微信授权,微信会带着 code 回到本页
187
- const appId = 'wx37701988c77d4ca7' // 也可从 GET /auth/mp/config 取,避免硬编码
188
- const code = new URLSearchParams(location.search).get('code')
189
- if (!code) {
190
- const back = encodeURIComponent(location.href.split('#')[0])
191
- // scope: snsapi_base 只拿 openid(静默);snsapi_userinfo 才能拿昵称头像(用户可见授权页)
192
- location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}`
193
- + `&redirect_uri=${back}&response_type=code&scope=snsapi_base&state=1#wechat_redirect`
186
+ const client = udg.init({ endpoint, appid })
187
+
188
+ // OAuth 回调阶段:SDK 校验并一次性消费 state,再用 mpCode 登录;context 是授权前保存的业务参数
189
+ const callback = await client.mp.loginFromCallback({ withUserInfo: true, cleanUrl: true })
190
+ if (callback.handled) {
191
+ console.log(callback.openId, callback.userInfo, callback.context)
194
192
  } else {
195
- const client = udg.init({ endpoint, appid }) // appid 是 UDG 租户主键,不是公众号 appid
196
- const { openId } = await client.login({ mpCode: code })
197
- // 需要昵称头像:await client.login({ mpCode: code, withUserInfo: true }) → 返回值含 userInfo
193
+ // 首次进入:SDK 自动获取公众号 AppID、生成随机 state,并保存业务上下文
194
+ await client.mp.redirectToAuthorization({
195
+ redirectUri: location.href.split('#')[0],
196
+ scope: 'snsapi_userinfo', // 只要 openid 时改用 snsapi_base
197
+ context: { scanSession, redirect: '/home' }
198
+ })
198
199
  }
199
-
200
200
  ```
201
201
 
202
+ `client.mp.getConfig()` / `createAuthorization()` / `redirectToAuthorization()` / `loginFromCallback()` 均为无 UI API。`state` 默认 10 分钟有效、校验后立即删除,可阻止伪造回调与重放。老项目继续使用 `login({ mpCode })` 完全兼容,但须自行安全管理 state 和授权前上下文。
203
+
202
204
  注意事项:
203
205
 
204
206
  - **`mpCode` 与 `code` 不可混用**:`code` 是小程序 `wx.login` 的 code(走 `/auth/wxlogin`),`mpCode` 是公众号网页授权的 code(走 `/auth/mp/login`),两者的 openid 体系也不同。
205
207
  - ⚠️ **公众号 openid ≠ 小程序 openid**(本项目未启用 unionid)。写入时注入的 `_openid` 因此分两套,同一张表两端都写时请用 JWT 里的 `authType`(`wechat` / `wechat-mp`)区分来源,**不要假设两端能按 `_openid` 关联到同一个人**。
206
208
  - **token 过期**:refreshToken 也失效后 SDK 无法自动重登(拿新 code 必须重走授权跳转),业务在捕获鉴权错误时按上面 ① 重新跳一次即可。
207
209
 
210
+ ### 公众号扫码登录电脑 Web(无需小程序)
211
+
212
+ 电脑二维码指向项目自己的公众号 H5 确认页;公众号证明手机用户身份,UDG 扫码会话把确认结果交给电脑。用户集合名称和结构由业务决定,不强制存在 `userinfo`。
213
+
214
+ ```js
215
+ // 电脑端:一次创建 sessionId、确认 URL、等待任务和 cancel()
216
+ const scan = client.createScanLogin({
217
+ confirmUrl: 'https://app.example.cn/user/wxauth',
218
+ timeout: 5 * 60 * 1000,
219
+ onStatus: (status) => console.log(status)
220
+ })
221
+ renderQrCode(scan.qrContent)
222
+ const { userInfo } = await scan.result // SDK 已保存电脑 token
223
+ // 页面销毁或重新生成二维码:scan.cancel() → SCAN_CANCELLED
224
+
225
+ // 手机确认页:先用 client.mp.* 完成公众号登录并取得/创建业务用户
226
+ await client.approveScanLogin({ id: callback.context.scanSession, admininfo: businessUser })
227
+ ```
228
+
229
+ 完整可复制模板与数据流见管理后台「公众号扫码登录」操作指引页。
230
+
208
231
  ### 用 JSSDK(wx.config):完整步骤
209
232
 
210
233
  `client.jsapiSign()` **无需登录**即可调用,返回 `wx.config` 需要的全部字段。
@@ -279,7 +302,7 @@ await client.login() // SDK 自动带上当前小程序的真实 appId,网
279
302
  ```
280
303
 
281
304
  - **小程序内**:`login()` 自动从 `wx.getAccountInfoSync()` 取当前 appId 上报,业务代码不用改,也不能自己传。
282
- - **web-view 内的 H5**:拿不到 `wx.getAccountInfoSync`,要显式传 `login({ code, miniAppId })`(宿主小程序的 appId)。不传则网关只能用租户的默认小程序,与 code 签发方不一致时报 `40013`。
305
+ - **web-view 内的 H5**:拿不到 `wx.getAccountInfoSync`,`login({ code })` 会从 UA(`miniProgram/wx…`)或 URL 的 `miniAppId` / `appid` 自动探测宿主并上报;仍可显式传 `miniAppId` 覆盖。探测不到时网关只能用默认小程序(与 code 签发方不一致时报 `40013`)。
283
306
  - 上报的 `miniAppId` **只能在该租户已关联的集合内选择**;传了没关联的会直接报 `appid=… 未关联小程序 …`,**不会**悄悄回落到默认小程序(这样"后台漏勾了一个"能一眼看出来,而不是表现成微信的 40013)。
284
307
  - ⚠️ **这 N 个小程序之间 openid 不互通**(openid 按 `miniAppId` 划分)。同一自然人在各小程序里 `_openid` 不同,**不要**按 `_openid` 跨小程序关联到同一个人。需要跨端对人请用手机号等业务标识。
285
308
  - 租户只关联一个小程序时,以上全部无感知,行为与之前完全一致。
@@ -508,7 +531,7 @@ watcher.close() // 退出页面时关闭
508
531
 
509
532
  运行环境:浏览器 EventSource / Node ≥ 18;微信小程序不支持(抛 `ENV_NOT_SUPPORTED`,请用轮询 / 定时 get 代替)。
510
533
 
511
- 扫码登录专用:`client.subscribeScanLogin(sessionId)`——SSE 推送确认结果(亚秒级),SSE 不可用时自动降级为 `pollScanLogin` 轮询,返回值语义一致。
534
+ 扫码登录专用:`client.subscribeScanLogin(sessionId)`——SSE 推送确认结果(亚秒级),SSE 不可用时自动降级为 `pollScanLogin` 轮询,返回值语义一致;两者均支持 `opts.signal` 取消。新项目可直接使用组合 API `createScanLogin()`,返回 `{ sessionId, qrContent, result, cancel }`。
512
535
 
513
536
  ## 运行时自查表结构
514
537
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bjchy-udg-sdk",
3
- "version": "1.8.1",
3
+ "version": "1.8.3",
4
4
  "description": "Universal Data Gateway SDK - 跨端统一数据访问(微信小程序 / Web / Node.js),API 兼容微信云开发",
5
5
  "main": "src/index.js",
6
6
  "type": "commonjs",
package/src/auth.js CHANGED
@@ -78,6 +78,47 @@ function currentMiniAppId() {
78
78
  }
79
79
  }
80
80
 
81
+ /** 形如微信小程序 appId:wx + 十六进制(通常 16 位) */
82
+ const WX_MINI_APPID_RE = /^wx[0-9a-f]+$/i
83
+
84
+ /**
85
+ * web-view 内 H5 探测宿主小程序 appId(对齐小程序内 currentMiniAppId)。
86
+ * 优先级:UA(真实宿主)> URL 查询参数 miniAppId / appid(仅当形如 wx…)。
87
+ * 允许 miniProgram 与 / 之间空白;要求 wx+十六进制,避免误匹配 MiniProgramEnv/android、port/…
88
+ * @param {{ ua?: string, search?: string }} [env] 可注入 UA/search(单测用);缺省读 navigator / location
89
+ */
90
+ function detectHostMiniAppId(env) {
91
+ const e = env || {}
92
+ const ua =
93
+ e.ua != null
94
+ ? String(e.ua)
95
+ : typeof navigator !== 'undefined'
96
+ ? navigator.userAgent || ''
97
+ : ''
98
+ const uaMatch = ua.match(/miniprogram\s*\/\s*(wx[0-9a-f]+)/i)
99
+ const fromUa = uaMatch ? uaMatch[1].toLowerCase() : ''
100
+ if (fromUa) return fromUa
101
+
102
+ const search =
103
+ e.search != null
104
+ ? String(e.search)
105
+ : typeof location !== 'undefined'
106
+ ? location.search || ''
107
+ : ''
108
+ const qs = new URLSearchParams(search.startsWith('?') || search === '' ? search : '?' + search)
109
+ const fromQs = (qs.get('miniAppId') || qs.get('appid') || '').trim().toLowerCase()
110
+ return WX_MINI_APPID_RE.test(fromQs) ? fromQs : ''
111
+ }
112
+
113
+ /**
114
+ * login({ code }) 用的宿主 miniAppId:显式参数优先,否则自动从 UA/QS 探测。
115
+ */
116
+ function resolveCodeLoginMiniAppId(explicit) {
117
+ const fromOpt = explicit != null ? String(explicit).trim().toLowerCase() : ''
118
+ if (fromOpt && WX_MINI_APPID_RE.test(fromOpt)) return fromOpt
119
+ return detectHostMiniAppId()
120
+ }
121
+
81
122
  class AuthManager {
82
123
  /**
83
124
  * @param {object} ctx SDK 上下文 { endpoint, appid, ... }
@@ -155,7 +196,8 @@ class AuthManager {
155
196
  * 登录(幂等:缓存 token 未过期时直接复用,force 可强制重登)。
156
197
  * - login():小程序环境自动 wx.login(并自动上报当前小程序 appId 供网关选凭据)
157
198
  * - login({ code, miniAppId? }):用外部拿到的微信登录 code 换 token(web-view 内 H5:由宿主小程序 wx.login 后经 URL 传入);
158
- * 若目标租户关联了多个小程序,需一并传 miniAppId(宿主小程序的 appId),否则网关只能用默认项
199
+ * miniAppId 可省略:SDK 会从 UA(miniprogram/wx…)或 URL 的 miniAppId/appid 自动探测宿主;
200
+ * 仍可显式传入覆盖。探测不到且租户关联多个小程序时,网关只能用默认项
159
201
  * - login({ mpCode }):公众号网页授权 code 换 token(公众号内打开的 H5,见 client.login 文档)
160
202
  * - login({ apiKey }):密钥登录
161
203
  */
@@ -181,9 +223,10 @@ class AuthManager {
181
223
  // 换回的是完整 token + refreshToken,因此后续可自动续期,不同于 external token 直入。
182
224
  if (o.code) {
183
225
  const body = { appid: this.ctx.appid, code: o.code }
184
- // web-view 内的 H5 拿不到 wx.getAccountInfoSync,租户关联多个小程序时
185
- // 必须由业务把宿主小程序的 appId 显式传进来,否则网关只能用默认项(与 code 签发方不符会 40013)
186
- if (o.miniAppId) body.miniAppId = o.miniAppId
226
+ // 对齐小程序内 currentMiniAppId():web-view 无 getAccountInfoSync,改从 UA/QS 探测宿主;
227
+ // 显式 miniAppId 仍可覆盖。老网关忽略该字段,可安全始终携带。
228
+ const mini = resolveCodeLoginMiniAppId(o.miniAppId)
229
+ if (mini) body.miniAppId = mini
187
230
  const data = await this.rawPost('/auth/wxlogin', body)
188
231
  this.openId = data.openId
189
232
  this.setTokens(data.token, data.refreshToken, 'wechat')
@@ -243,4 +286,4 @@ class AuthManager {
243
286
  }
244
287
  }
245
288
 
246
- module.exports = { AuthManager, decodeJwtPayload, isMiniProgram }
289
+ module.exports = { AuthManager, decodeJwtPayload, isMiniProgram, detectHostMiniAppId }
package/src/index.js CHANGED
@@ -27,6 +27,7 @@ const { rawPost, postAuthed, fetchServerTime, UdgRequestError } = require('./req
27
27
  const { AuthManager } = require('./auth')
28
28
  const { AiNamespace } = require('./ai')
29
29
  const { WxNamespace } = require('./wx')
30
+ const { MpNamespace } = require('./mp')
30
31
  const storage = require('./storage')
31
32
 
32
33
  /**
@@ -65,6 +66,30 @@ function sleep(ms) {
65
66
  return new Promise((resolve) => setTimeout(resolve, ms))
66
67
  }
67
68
 
69
+ function scanCancelledError() {
70
+ return new UdgRequestError({ errorCode: 'SCAN_CANCELLED', errorMessage: '已取消扫码登录' })
71
+ }
72
+
73
+ function throwIfAborted(signal) {
74
+ if (signal && signal.aborted) throw scanCancelledError()
75
+ }
76
+
77
+ function abortableSleep(ms, signal) {
78
+ if (!signal) return sleep(ms)
79
+ throwIfAborted(signal)
80
+ return new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => {
82
+ signal.removeEventListener('abort', onAbort)
83
+ resolve()
84
+ }, ms)
85
+ const onAbort = () => {
86
+ clearTimeout(timer)
87
+ reject(scanCancelledError())
88
+ }
89
+ signal.addEventListener('abort', onAbort, { once: true })
90
+ })
91
+ }
92
+
68
93
  /**
69
94
  * appid / streetKey 二选一场景下,懒解析出 appid(仅 streetKey 时调用 /tenant/resolve)。
70
95
  * 解析结果按 endpoint+streetKey 缓存(跨端持久化,见 storage.js),同一浏览器 tab/进程内不重复请求。
@@ -123,6 +148,8 @@ class UdgClient {
123
148
  this.ai = new AiNamespace(this._ctx)
124
149
  // 微信小程序服务端 API:client.wx.*(需 login;见 docs/wechat-mini-integration.md)
125
150
  this.wx = new WxNamespace(this._ctx)
151
+ // 微信公众号 H5:OAuth URL、一次性 state 和回调登录(无 UI)。
152
+ this.mp = new MpNamespace(this._ctx, (opts) => this.login(opts), () => ensureAppid(this._ctx))
126
153
  }
127
154
 
128
155
  /**
@@ -140,7 +167,8 @@ class UdgClient {
140
167
  *
141
168
  * `{ code }`:web-view 内的 H5 拿不到 `wx.login`,由宿主小程序中转页 `wx.login()` 取 code 后
142
169
  * 经 web-view URL 传进来(code 5 分钟一次性,泄露风险远低于传 token),换回的是完整
143
- * token + refreshToken,可自动续期。
170
+ * token + refreshToken,可自动续期。多小程序租户时 SDK 从 UA / URL 自动带上宿主
171
+ * `miniAppId`(也可显式传入覆盖)。
144
172
  *
145
173
  * `{ mpCode }`:公众号内打开的 H5,由微信网页授权回调把 code 带回本页 URL。
146
174
  * 可选 `{ withUserInfo: true }` 顺带取昵称/头像(要求授权时 scope 用 snsapi_userinfo),
@@ -265,7 +293,7 @@ class UdgClient {
265
293
  /**
266
294
  * 轮询扫码登录结果;确认后自动保存 token 并返回 { token, refreshToken, userInfo }。
267
295
  * @param {string} sessionId createScanSession 返回的 id(即二维码中的 id)
268
- * @param {object} opts { interval=2000, timeout=300000, onStatus(status), viaStreetKey? }
296
+ * @param {object} opts { interval=2000, timeout=300000, onStatus(status), viaStreetKey?, signal? }
269
297
  * viaStreetKey:跨租户借用登录(见 docs/scan-login-cross-tenant.md)——本次扫码借用的来源
270
298
  * streetKey(对应的小程序),不传 = 现状(登录来源即本 client 的 appid);跨租户时 token 归属
271
299
  * 仍然是本 client 的 appid,来源租户只是负责扫码环节
@@ -278,6 +306,7 @@ class UdgClient {
278
306
  const post = rawPost(this._ctx)
279
307
  const start = Date.now()
280
308
  for (;;) {
309
+ throwIfAborted(o.signal)
281
310
  const data = await post('/auth/scan/statuscheck', {
282
311
  appid: this._ctx.appid,
283
312
  id: sessionId,
@@ -294,7 +323,7 @@ class UdgClient {
294
323
  if (Date.now() - start > timeout) {
295
324
  throw new UdgRequestError({ errorCode: 'SCAN_TIMEOUT', errorMessage: '扫码登录等待超时' })
296
325
  }
297
- await sleep(interval)
326
+ await abortableSleep(interval, o.signal)
298
327
  }
299
328
  }
300
329
 
@@ -302,7 +331,7 @@ class UdgClient {
302
331
  * 实时扫码登录(B2 SSE,取代轮询):Gateway 推送状态变化,扫码确认后亚秒级返回。
303
332
  * SSE 不可用(小程序 / 老浏览器 / 网络设备拦截)时自动降级为 pollScanLogin 轮询。
304
333
  * @param {string} sessionId createScanSession 返回的 id
305
- * @param {object} opts { timeout=300000, onStatus(status), viaStreetKey?, noFallback? }
334
+ * @param {object} opts { timeout=300000, onStatus(status), viaStreetKey?, noFallback?, signal? }
306
335
  * @returns {Promise<{token, refreshToken, userInfo}>} 语义与 pollScanLogin 一致
307
336
  */
308
337
  async subscribeScanLogin(sessionId, opts) {
@@ -316,7 +345,12 @@ class UdgClient {
316
345
  const url = `${base}/auth/scan/subscribe?${params.toString()}`
317
346
 
318
347
  const fallback = () =>
319
- this.pollScanLogin(sessionId, { timeout, onStatus: o.onStatus, viaStreetKey: o.viaStreetKey })
348
+ this.pollScanLogin(sessionId, {
349
+ timeout,
350
+ onStatus: o.onStatus,
351
+ viaStreetKey: o.viaStreetKey,
352
+ signal: o.signal
353
+ })
320
354
 
321
355
  return new Promise((resolve, reject) => {
322
356
  let settled = false
@@ -325,6 +359,7 @@ class UdgClient {
325
359
  if (settled) return
326
360
  settled = true
327
361
  clearTimeout(timer)
362
+ if (o.signal) o.signal.removeEventListener('abort', cancel)
328
363
  if (conn) conn.close()
329
364
  fn(val)
330
365
  }
@@ -332,6 +367,7 @@ class UdgClient {
332
367
  if (settled) return
333
368
  settled = true
334
369
  clearTimeout(timer)
370
+ if (o.signal) o.signal.removeEventListener('abort', cancel)
335
371
  if (conn) conn.close()
336
372
  if (o.noFallback) {
337
373
  reject(new UdgRequestError({ errorCode: 'SSE_UNAVAILABLE', errorMessage: 'SSE 订阅不可用' }))
@@ -343,6 +379,13 @@ class UdgClient {
343
379
  settle(reject, new UdgRequestError({ errorCode: 'SCAN_TIMEOUT', errorMessage: '扫码登录等待超时' }))
344
380
  }, timeout)
345
381
  if (timer.unref) timer.unref()
382
+ const cancel = () => settle(reject, scanCancelledError())
383
+
384
+ if (o.signal && o.signal.aborted) {
385
+ cancel()
386
+ return
387
+ }
388
+ if (o.signal) o.signal.addEventListener('abort', cancel, { once: true })
346
389
 
347
390
  try {
348
391
  conn = connectSSE(url, {
@@ -367,6 +410,40 @@ class UdgClient {
367
410
  })
368
411
  }
369
412
 
413
+ /**
414
+ * 一次创建可取消的扫码登录任务。项目仍负责把 qrContent 渲染成二维码。
415
+ * @param {object} opts { confirmUrl?, paramName='scanSession', timeout?, onStatus?, viaStreetKey? }
416
+ * @returns {{sessionId:string,qrContent:string,result:Promise,cancel:function}}
417
+ */
418
+ createScanLogin(opts) {
419
+ const o = opts || {}
420
+ const { sessionId } = this.createScanSession()
421
+ let qrContent = ''
422
+ if (o.confirmUrl) {
423
+ const url = new URL(o.confirmUrl)
424
+ url.searchParams.set(o.paramName || 'scanSession', sessionId)
425
+ qrContent = url.toString()
426
+ } else {
427
+ qrContent = this.buildScanQrContent(sessionId, o.qrOptions)
428
+ }
429
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null
430
+ const result = this.subscribeScanLogin(sessionId, {
431
+ timeout: o.timeout,
432
+ onStatus: o.onStatus,
433
+ viaStreetKey: o.viaStreetKey,
434
+ noFallback: o.noFallback,
435
+ signal: controller ? controller.signal : undefined
436
+ })
437
+ return {
438
+ sessionId,
439
+ qrContent,
440
+ result,
441
+ cancel: () => {
442
+ if (controller) controller.abort()
443
+ }
444
+ }
445
+ }
446
+
370
447
  /**
371
448
  * 单次调用扫码状态检查(不轮询,与 pollScanLogin 不同)。
372
449
  * confirmed 时与 pollScanLogin 一致,自动保存 token。
package/src/mp.js ADDED
@@ -0,0 +1,127 @@
1
+ /** 微信公众号 H5 OAuth 无 UI 编排。 */
2
+ const { rawGet, UdgRequestError } = require('./request')
3
+ const storage = require('./storage')
4
+
5
+ const MP_STATE_TTL = 10 * 60 * 1000
6
+ const MP_SCOPES = new Set(['snsapi_base', 'snsapi_userinfo'])
7
+
8
+ function randomState() {
9
+ try {
10
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
11
+ return crypto.randomUUID().replace(/-/g, '')
12
+ }
13
+ } catch (e) { /* fall through */ }
14
+ let value = ''
15
+ for (let i = 0; i < 32; i++) value += Math.floor(Math.random() * 16).toString(16)
16
+ return value
17
+ }
18
+
19
+ function currentSearch(explicit) {
20
+ if (explicit !== undefined) return explicit || ''
21
+ try {
22
+ if (typeof location !== 'undefined' && location) return location.search || ''
23
+ } catch (e) { /* non-browser */ }
24
+ return ''
25
+ }
26
+
27
+ class MpNamespace {
28
+ constructor(ctx, login, ensureAppid) {
29
+ this._ctx = ctx
30
+ this._login = login
31
+ this._ensureAppid = ensureAppid
32
+ }
33
+
34
+ _stateKey(state) {
35
+ return `udg_mp_state_${this._ctx.appid || this._ctx.streetKey || ''}_${state}`
36
+ }
37
+
38
+ /** 获取公众号公开配置;AppSecret 永不返回客户端。 */
39
+ async getConfig() {
40
+ await this._ensureAppid()
41
+ const query = new URLSearchParams({ appid: this._ctx.appid })
42
+ return rawGet(this._ctx, `/auth/mp/config?${query.toString()}`)
43
+ }
44
+
45
+ /** 创建 OAuth URL,同时保存一次性 state 和业务上下文。 */
46
+ async createAuthorization(opts) {
47
+ const o = opts || {}
48
+ if (!o.redirectUri) {
49
+ throw new UdgRequestError({ errorCode: 'INVALID_PARAM', errorMessage: 'createAuthorization 需要 redirectUri' })
50
+ }
51
+ const scope = o.scope || 'snsapi_base'
52
+ if (!MP_SCOPES.has(scope)) {
53
+ throw new UdgRequestError({ errorCode: 'INVALID_PARAM', errorMessage: 'scope 只能是 snsapi_base 或 snsapi_userinfo' })
54
+ }
55
+ const config = await this.getConfig()
56
+ if (!config.appId) {
57
+ throw new UdgRequestError({ errorCode: 'MP_NOT_CONFIGURED', errorMessage: 'Gateway 未配置微信公众号' })
58
+ }
59
+ const state = o.state || randomState()
60
+ storage.set(this._stateKey(state), {
61
+ state,
62
+ context: o.context === undefined ? null : o.context,
63
+ createdAt: Date.now()
64
+ })
65
+ const params = new URLSearchParams({
66
+ appid: config.appId,
67
+ redirect_uri: o.redirectUri,
68
+ response_type: 'code',
69
+ scope,
70
+ state
71
+ })
72
+ return {
73
+ url: `https://open.weixin.qq.com/connect/oauth2/authorize?${params.toString()}#wechat_redirect`,
74
+ state,
75
+ appId: config.appId,
76
+ scope
77
+ }
78
+ }
79
+
80
+ /** 创建授权 URL 后立即 location.replace。 */
81
+ async redirectToAuthorization(opts) {
82
+ const result = await this.createAuthorization(opts)
83
+ if (typeof location === 'undefined' || typeof location.replace !== 'function') {
84
+ throw new UdgRequestError({ errorCode: 'ENV_NOT_SUPPORTED', errorMessage: '当前环境无法跳转公众号授权' })
85
+ }
86
+ location.replace(result.url)
87
+ return result
88
+ }
89
+
90
+ /** 解析 OAuth 回调、校验并消费 state,再用 mpCode 登录。 */
91
+ async loginFromCallback(opts) {
92
+ const o = opts || {}
93
+ const params = new URLSearchParams(currentSearch(o.search))
94
+ const code = params.get(o.codeParam || 'code') || ''
95
+ if (!code) return { handled: false, reason: 'no_code' }
96
+
97
+ const state = params.get(o.stateParam || 'state') || ''
98
+ if (!state) {
99
+ throw new UdgRequestError({ errorCode: 'MP_STATE_INVALID', errorMessage: '公众号授权回调缺少 state' })
100
+ }
101
+ const key = this._stateKey(state)
102
+ const saved = storage.get(key)
103
+ storage.remove(key)
104
+ if (!saved || saved.state !== state) {
105
+ throw new UdgRequestError({ errorCode: 'MP_STATE_INVALID', errorMessage: '公众号授权 state 无效或已使用' })
106
+ }
107
+ const maxAge = o.maxAge || MP_STATE_TTL
108
+ if (!saved.createdAt || Date.now() - saved.createdAt > maxAge) {
109
+ throw new UdgRequestError({ errorCode: 'MP_STATE_EXPIRED', errorMessage: '公众号授权 state 已过期,请重新授权' })
110
+ }
111
+
112
+ const result = await this._login({
113
+ mpCode: code,
114
+ withUserInfo: !!o.withUserInfo,
115
+ force: o.force !== false
116
+ })
117
+ if (o.cleanUrl && typeof history !== 'undefined' && typeof location !== 'undefined') {
118
+ const url = new URL(location.href)
119
+ url.searchParams.delete(o.codeParam || 'code')
120
+ url.searchParams.delete(o.stateParam || 'state')
121
+ history.replaceState(null, '', url.toString())
122
+ }
123
+ return Object.assign({ handled: true, context: saved.context }, result)
124
+ }
125
+ }
126
+
127
+ module.exports = { MpNamespace, MP_STATE_TTL }
package/src/request.js CHANGED
@@ -137,6 +137,21 @@ async function fetchServerTime(ctx) {
137
137
  return ctx._timeOffset || 0
138
138
  }
139
139
 
140
+ /** 无鉴权 GET 请求(公众号公开配置等 auth 接口使用) */
141
+ async function rawGet(ctx, path) {
142
+ const url = ctx.endpoint.replace(/\/+$/, '') + path
143
+ const timeout = ctx.timeout || 15000
144
+ const t0 = Date.now()
145
+ const json = isMiniProgram() ? await getViaWx(url, timeout) : await getViaFetch(url, timeout)
146
+ captureServerTime(ctx, json, t0, Date.now())
147
+ if (!json || json.success !== true) {
148
+ throw new UdgRequestError(
149
+ json || { errorCode: 'NETWORK_ERROR', errorMessage: 'Gateway 返回异常' }
150
+ )
151
+ }
152
+ return decode(json.data)
153
+ }
154
+
140
155
  /** 单次原始请求(不含自动续期逻辑) */
141
156
  async function rawRequest(ctx, path, body, token) {
142
157
  const url = ctx.endpoint.replace(/\/+$/, '') + path
@@ -222,4 +237,4 @@ async function postAuthed(ctx, path, payload) {
222
237
  }
223
238
  }
224
239
 
225
- module.exports = { post, postAuthed, rawPost, rawRequest, fetchServerTime, UdgRequestError }
240
+ module.exports = { post, postAuthed, rawGet, rawPost, rawRequest, fetchServerTime, UdgRequestError }