request.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import { API_BASE, TOKEN_KEY, REFRESH_TOKEN_KEY, USER_INFO_KEY } from '@/config/api'
  2. let clearingAuth = false
  3. // TODO(config-hardcoded): 以下加密参数为临时写死,后续应迁移至构建期注入或安全配置下发。
  4. // 写死配置:不从环境变量读取,避免小程序端注入差异导致行为不一致。
  5. let API_ENCRYPT_ENABLED = true
  6. const API_ENCRYPT_FAIL_OPEN = false
  7. const API_ENCRYPT_FIXED_SECRET = 'sqxp-web-api-crypto-fixed-secret'
  8. // TODO(config-hardcoded): 排除路径清单后续改为集中配置,避免多端重复维护。
  9. const API_ENCRYPT_EXCLUDE_PATHS = String(
  10. '/mini/auth/login-rsa-public-key,/mini/auth/login,/mini/auth/sms-login,/mini/auth/wechat-login,/mini/auth/code-openid,/mini/common/china-region-tree'
  11. )
  12. .split(',')
  13. .map((item) => item.trim())
  14. .filter(Boolean)
  15. // #ifdef MP-WEIXIN
  16. // 微信小程序运行时不保证 WebCrypto(getRandomValues/subtle),关闭前端加密避免全链路请求失败。
  17. API_ENCRYPT_ENABLED = false
  18. // #endif
  19. function appendTimestampQuery(url) {
  20. const base = String(url || '')
  21. const ts = Date.now()
  22. if (!base) return `${base}?_t=${ts}`
  23. // 已有 _t 时覆盖为最新值,避免 query 反复堆叠
  24. if (/[?&]_t=/.test(base)) {
  25. return base.replace(/([?&]_t=)\d+/, `$1${ts}`)
  26. }
  27. return `${base}${base.includes('?') ? '&' : '?'}_t=${ts}`
  28. }
  29. function createUnauthorizedError(rawUrl = '') {
  30. const loginApiPattern = /\/mini\/auth\/login(?:$|\?)/
  31. const message = loginApiPattern.test(String(rawUrl))
  32. ? '用户名或密码错误,请重新输入'
  33. : '登录状态已失效,请重新登录'
  34. const error = new Error(message)
  35. error.name = 'UnauthorizedError'
  36. return error
  37. }
  38. async function onHttpUnauthorized() {
  39. if (clearingAuth) return
  40. clearingAuth = true
  41. // 先同步清理本地登录态,避免 store 动态导入失败时仍被识别为已登录
  42. uni.removeStorageSync(TOKEN_KEY)
  43. uni.removeStorageSync(REFRESH_TOKEN_KEY)
  44. uni.removeStorageSync(USER_INFO_KEY)
  45. try {
  46. const { useUserStore } = await import('@/stores/user')
  47. useUserStore().clearLoginInfo()
  48. } catch (error) {
  49. // ignore
  50. }
  51. const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
  52. const currentRoute = pages.length ? pages[pages.length - 1].route : ''
  53. if (currentRoute === 'pages/login/login') {
  54. clearingAuth = false
  55. return
  56. }
  57. uni.showToast({ title: '登录已失效,请重新登录', icon: 'none' })
  58. uni.reLaunch({
  59. url: '/pages/login/login',
  60. fail: () => {
  61. // 某些端在请求回调中 reLaunch 可能失败,使用 redirectTo 兜底
  62. uni.redirectTo({ url: '/pages/login/login' })
  63. },
  64. complete: () => {
  65. setTimeout(() => {
  66. clearingAuth = false
  67. }, 800)
  68. }
  69. })
  70. }
  71. function isBizUnauthorized(data) {
  72. if (!data || typeof data !== 'object') return false
  73. return data.code === 401
  74. }
  75. function randomNonce() {
  76. const bytes = new Uint8Array(12)
  77. const c = globalThis.crypto
  78. if (!c || typeof c.getRandomValues !== 'function') {
  79. throw new Error('当前环境不支持随机数生成')
  80. }
  81. c.getRandomValues(bytes)
  82. return Array.from(bytes)
  83. .map((b) => b.toString(16).padStart(2, '0'))
  84. .join('')
  85. }
  86. function hexToBytes(hex) {
  87. const out = new Uint8Array(hex.length / 2)
  88. for (let i = 0; i < out.length; i += 1) {
  89. out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
  90. }
  91. return out
  92. }
  93. function bytesToHex(bytes) {
  94. return Array.from(bytes)
  95. .map((b) => b.toString(16).padStart(2, '0'))
  96. .join('')
  97. }
  98. function bytesToBase64(bytes) {
  99. let binary = ''
  100. bytes.forEach((b) => {
  101. binary += String.fromCharCode(b)
  102. })
  103. return btoa(binary)
  104. }
  105. function base64ToBytes(base64) {
  106. const binary = atob(base64)
  107. const out = new Uint8Array(binary.length)
  108. for (let i = 0; i < binary.length; i += 1) {
  109. out[i] = binary.charCodeAt(i)
  110. }
  111. return out
  112. }
  113. function toBase64Url(bytes) {
  114. return bytesToBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
  115. }
  116. function fromBase64Url(base64url) {
  117. const base64 = String(base64url || '').replace(/-/g, '+').replace(/_/g, '/')
  118. const padding = '='.repeat((4 - (base64.length % 4)) % 4)
  119. return base64ToBytes(base64 + padding)
  120. }
  121. async function sha256Hex(text) {
  122. const c = globalThis.crypto
  123. if (!c || !c.subtle || typeof c.subtle.digest !== 'function') {
  124. throw new Error('当前环境不支持摘要算法')
  125. }
  126. const data = new TextEncoder().encode(String(text || ''))
  127. const digest = await c.subtle.digest('SHA-256', data)
  128. return bytesToHex(new Uint8Array(digest))
  129. }
  130. async function deriveKey(fixed, userId, ts, nonce) {
  131. return sha256Hex(`${fixed}:${userId}:${ts}:${nonce}`)
  132. }
  133. async function encryptJson(payload, keyHex) {
  134. const c = globalThis.crypto
  135. if (!c || !c.subtle || typeof c.subtle.importKey !== 'function') {
  136. throw new Error('当前环境不支持加密算法')
  137. }
  138. const iv = c.getRandomValues(new Uint8Array(12))
  139. const key = await c.subtle.importKey('raw', hexToBytes(keyHex), 'AES-GCM', false, ['encrypt'])
  140. const plain = new TextEncoder().encode(JSON.stringify(payload || {}))
  141. const encrypted = await c.subtle.encrypt({ name: 'AES-GCM', iv }, key, plain)
  142. const merged = new Uint8Array(iv.length + encrypted.byteLength)
  143. merged.set(iv, 0)
  144. merged.set(new Uint8Array(encrypted), iv.length)
  145. return toBase64Url(merged)
  146. }
  147. async function decryptJson(edata, keyHex) {
  148. const c = globalThis.crypto
  149. if (!c || !c.subtle || typeof c.subtle.decrypt !== 'function') {
  150. throw new Error('当前环境不支持解密算法')
  151. }
  152. const raw = fromBase64Url(edata)
  153. if (raw.length < 13) {
  154. throw new Error('响应密文非法')
  155. }
  156. const iv = raw.slice(0, 12)
  157. const cipher = raw.slice(12)
  158. const key = await c.subtle.importKey('raw', hexToBytes(keyHex), 'AES-GCM', false, ['decrypt'])
  159. const decrypted = await c.subtle.decrypt({ name: 'AES-GCM', iv }, key, cipher)
  160. const text = new TextDecoder().decode(new Uint8Array(decrypted))
  161. return JSON.parse(text)
  162. }
  163. function parseUserIdFromToken(token) {
  164. const raw = String(token || '')
  165. const parts = raw.split('.')
  166. if (parts.length < 2) return ''
  167. try {
  168. const b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/')
  169. const pad = '='.repeat((4 - (b64.length % 4)) % 4)
  170. const json = atob(b64 + pad)
  171. const obj = JSON.parse(json)
  172. return String(obj?.sub || '')
  173. } catch (error) {
  174. return ''
  175. }
  176. }
  177. function normalizeRequestData(data) {
  178. if (!data) return {}
  179. if (typeof data === 'string') {
  180. try {
  181. const parsed = JSON.parse(data)
  182. return parsed && typeof parsed === 'object' ? parsed : {}
  183. } catch (error) {
  184. return {}
  185. }
  186. }
  187. return typeof data === 'object' ? data : {}
  188. }
  189. function isNativeFormData(data) {
  190. // 微信小程序等运行时可能不存在全局 FormData,直接 instanceof 会抛错
  191. return typeof FormData !== 'undefined' && data instanceof FormData
  192. }
  193. function shouldEncryptRequest(rawUrl, userId, data) {
  194. if (!API_ENCRYPT_ENABLED || !API_ENCRYPT_FIXED_SECRET) return false
  195. if (!rawUrl || !String(rawUrl).includes('/mini/')) return false
  196. if (!userId) return false
  197. if (isNativeFormData(data)) return false
  198. return !API_ENCRYPT_EXCLUDE_PATHS.some((prefix) => String(rawUrl).startsWith(prefix))
  199. }
  200. function getEncryptSkipReason(rawUrl, userId, data) {
  201. if (!API_ENCRYPT_ENABLED) return 'encrypt-disabled'
  202. if (!API_ENCRYPT_FIXED_SECRET) return 'missing-fixed-secret'
  203. if (!rawUrl || !String(rawUrl).includes('/mini/')) return 'non-mini-path'
  204. if (!userId) return 'missing-user-id'
  205. if (isNativeFormData(data)) return 'form-data'
  206. if (API_ENCRYPT_EXCLUDE_PATHS.some((prefix) => String(rawUrl).startsWith(prefix))) return 'exclude-path'
  207. return ''
  208. }
  209. export function request(options) {
  210. if (clearingAuth) {
  211. return Promise.reject(createUnauthorizedError(options?.url))
  212. }
  213. const rawToken = uni.getStorageSync(TOKEN_KEY)
  214. const token = typeof rawToken === 'string' ? rawToken.trim() : ''
  215. const rawUrl = options.url || ''
  216. const method = String(options.method || 'GET').toUpperCase()
  217. const userIdFromStorage = (() => {
  218. const rawUserInfo = uni.getStorageSync(USER_INFO_KEY)
  219. if (rawUserInfo && typeof rawUserInfo === 'object') {
  220. return String(rawUserInfo.id || rawUserInfo.userId || '')
  221. }
  222. if (typeof rawUserInfo === 'string') {
  223. try {
  224. const parsed = JSON.parse(rawUserInfo)
  225. return String(parsed?.id || parsed?.userId || '')
  226. } catch (error) {
  227. return ''
  228. }
  229. }
  230. return ''
  231. })()
  232. const userId = userIdFromStorage || parseUserIdFromToken(token)
  233. const normalizedUrl = rawUrl.startsWith('http')
  234. ? rawUrl
  235. : `${API_BASE}${rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`}`
  236. const url = appendTimestampQuery(normalizedUrl)
  237. const shouldEncrypt = shouldEncryptRequest(rawUrl, userId, options.data)
  238. const skipReason = shouldEncrypt ? '' : getEncryptSkipReason(rawUrl, userId, options.data)
  239. return new Promise(async (resolve, reject) => {
  240. const originalMethod = method
  241. const originalData = options.data
  242. const originalParams = options.params
  243. let reqMethod = method
  244. let reqData = options.data
  245. const reqHeader = {
  246. 'Content-Type': 'application/json',
  247. ...(token ? { Authorization: `Bearer ${token}` } : {}),
  248. ...(options.header || {})
  249. }
  250. // 便于在 HBuilderX/H5 的 Network 面板直接判断是否走了密文
  251. reqHeader['X-Api-Crypto'] = shouldEncrypt ? 'on' : `off:${skipReason || 'unknown'}`
  252. try {
  253. if (shouldEncrypt) {
  254. if (reqMethod === 'GET') {
  255. reqHeader['X-HTTP-Method-Override'] = 'GET'
  256. reqMethod = 'POST'
  257. reqData = options.data || options.params || {}
  258. }
  259. const ts = Date.now()
  260. const nonce = randomNonce()
  261. const keyHex = await deriveKey(API_ENCRYPT_FIXED_SECRET, userId, ts, nonce)
  262. const plainData = normalizeRequestData(reqData)
  263. const edata = await encryptJson({ data: plainData }, keyHex)
  264. reqData = {
  265. enc: 1,
  266. ts,
  267. nonce,
  268. edata
  269. }
  270. }
  271. } catch (error) {
  272. if (!API_ENCRYPT_FAIL_OPEN) {
  273. reject(error)
  274. return
  275. }
  276. }
  277. uni.request({
  278. ...options,
  279. method: reqMethod,
  280. data: reqData,
  281. url,
  282. header: reqHeader,
  283. success: async (res) => {
  284. // 后端未启用密文中间件(或未支持 method override)时,GET->POST 传输会触发 405;
  285. // 这里仅对“原始 GET + override”场景做一次降级回 GET,保证 H5 本地联调可用。
  286. if (
  287. res.statusCode === 405 &&
  288. originalMethod === 'GET' &&
  289. String(reqHeader['X-HTTP-Method-Override'] || '').toUpperCase() === 'GET'
  290. ) {
  291. const fallbackHeader = {
  292. ...reqHeader
  293. }
  294. delete fallbackHeader['X-HTTP-Method-Override']
  295. fallbackHeader['X-Api-Crypto'] = 'off:405-fallback'
  296. uni.request({
  297. ...options,
  298. method: 'GET',
  299. data: originalData || originalParams,
  300. url,
  301. header: fallbackHeader,
  302. success: (res2) => resolve(res2),
  303. fail: (err2) => reject(err2)
  304. })
  305. return
  306. }
  307. let payload = res.data
  308. if (shouldEncrypt && payload && payload.encrypted && payload.edata) {
  309. try {
  310. const respKeyHex = await deriveKey(
  311. API_ENCRYPT_FIXED_SECRET,
  312. userId,
  313. Number(payload.ts),
  314. String(payload.nonce || '')
  315. )
  316. payload = await decryptJson(payload.edata, respKeyHex)
  317. res.data = payload
  318. } catch (error) {
  319. if (!API_ENCRYPT_FAIL_OPEN) {
  320. reject(error)
  321. return
  322. }
  323. }
  324. }
  325. if (res.statusCode === 401 || isBizUnauthorized(payload)) {
  326. onHttpUnauthorized()
  327. reject(createUnauthorizedError(rawUrl))
  328. return
  329. }
  330. resolve(res)
  331. },
  332. fail: (err) => reject(err)
  333. })
  334. })
  335. }
  336. export function parseResponseJson(res) {
  337. const d = res.data
  338. if (d == null) return d
  339. if (typeof d === 'string') {
  340. try {
  341. return JSON.parse(d)
  342. } catch (error) {
  343. return d
  344. }
  345. }
  346. return d
  347. }