request.js 12 KB

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