bjchy-udg-sdk 1.8.2 → 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
@@ -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` 需要的全部字段。
@@ -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.2",
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/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
  /**
@@ -266,7 +293,7 @@ class UdgClient {
266
293
  /**
267
294
  * 轮询扫码登录结果;确认后自动保存 token 并返回 { token, refreshToken, userInfo }。
268
295
  * @param {string} sessionId createScanSession 返回的 id(即二维码中的 id)
269
- * @param {object} opts { interval=2000, timeout=300000, onStatus(status), viaStreetKey? }
296
+ * @param {object} opts { interval=2000, timeout=300000, onStatus(status), viaStreetKey?, signal? }
270
297
  * viaStreetKey:跨租户借用登录(见 docs/scan-login-cross-tenant.md)——本次扫码借用的来源
271
298
  * streetKey(对应的小程序),不传 = 现状(登录来源即本 client 的 appid);跨租户时 token 归属
272
299
  * 仍然是本 client 的 appid,来源租户只是负责扫码环节
@@ -279,6 +306,7 @@ class UdgClient {
279
306
  const post = rawPost(this._ctx)
280
307
  const start = Date.now()
281
308
  for (;;) {
309
+ throwIfAborted(o.signal)
282
310
  const data = await post('/auth/scan/statuscheck', {
283
311
  appid: this._ctx.appid,
284
312
  id: sessionId,
@@ -295,7 +323,7 @@ class UdgClient {
295
323
  if (Date.now() - start > timeout) {
296
324
  throw new UdgRequestError({ errorCode: 'SCAN_TIMEOUT', errorMessage: '扫码登录等待超时' })
297
325
  }
298
- await sleep(interval)
326
+ await abortableSleep(interval, o.signal)
299
327
  }
300
328
  }
301
329
 
@@ -303,7 +331,7 @@ class UdgClient {
303
331
  * 实时扫码登录(B2 SSE,取代轮询):Gateway 推送状态变化,扫码确认后亚秒级返回。
304
332
  * SSE 不可用(小程序 / 老浏览器 / 网络设备拦截)时自动降级为 pollScanLogin 轮询。
305
333
  * @param {string} sessionId createScanSession 返回的 id
306
- * @param {object} opts { timeout=300000, onStatus(status), viaStreetKey?, noFallback? }
334
+ * @param {object} opts { timeout=300000, onStatus(status), viaStreetKey?, noFallback?, signal? }
307
335
  * @returns {Promise<{token, refreshToken, userInfo}>} 语义与 pollScanLogin 一致
308
336
  */
309
337
  async subscribeScanLogin(sessionId, opts) {
@@ -317,7 +345,12 @@ class UdgClient {
317
345
  const url = `${base}/auth/scan/subscribe?${params.toString()}`
318
346
 
319
347
  const fallback = () =>
320
- 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
+ })
321
354
 
322
355
  return new Promise((resolve, reject) => {
323
356
  let settled = false
@@ -326,6 +359,7 @@ class UdgClient {
326
359
  if (settled) return
327
360
  settled = true
328
361
  clearTimeout(timer)
362
+ if (o.signal) o.signal.removeEventListener('abort', cancel)
329
363
  if (conn) conn.close()
330
364
  fn(val)
331
365
  }
@@ -333,6 +367,7 @@ class UdgClient {
333
367
  if (settled) return
334
368
  settled = true
335
369
  clearTimeout(timer)
370
+ if (o.signal) o.signal.removeEventListener('abort', cancel)
336
371
  if (conn) conn.close()
337
372
  if (o.noFallback) {
338
373
  reject(new UdgRequestError({ errorCode: 'SSE_UNAVAILABLE', errorMessage: 'SSE 订阅不可用' }))
@@ -344,6 +379,13 @@ class UdgClient {
344
379
  settle(reject, new UdgRequestError({ errorCode: 'SCAN_TIMEOUT', errorMessage: '扫码登录等待超时' }))
345
380
  }, timeout)
346
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 })
347
389
 
348
390
  try {
349
391
  conn = connectSSE(url, {
@@ -368,6 +410,40 @@ class UdgClient {
368
410
  })
369
411
  }
370
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
+
371
447
  /**
372
448
  * 单次调用扫码状态检查(不轮询,与 pollScanLogin 不同)。
373
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 }