request.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { TOKEN_KEY, REFRESH_TOKEN_KEY, USER_INFO_KEY, resolveApiBase } from '@/config/api'
  2. let clearingAuth = false
  3. // TODO(config-hardcoded): 以下加密参数为临时写死,后续应迁移至构建期注入或安全配置下发。
  4. // 写死配置:不从环境变量读取,避免小程序端注入差异导致行为不一致。
  5. // 移动端(H5 + 微信小程序)统一走明文 JSON,便于联调排查入参;Web 管理端仍可单独开加密。
  6. const API_ENCRYPT_ENABLED = false
  7. const API_ENCRYPT_FAIL_OPEN = false
  8. const API_ENCRYPT_FIXED_SECRET = 'shanxia-web-api-crypto-fixed-secret'
  9. // TODO(config-hardcoded): 排除路径清单后续改为集中配置,避免多端重复维护。
  10. const API_ENCRYPT_EXCLUDE_PATHS = String(
  11. '/web/auth/login-rsa-public-key,/web/auth/login,/web/auth/refresh-token,/mini/auth/wechat-login,/mini/auth/web-qr-scanned,/mini/auth/web-qr-confirm'
  12. )
  13. .split(',')
  14. .map((item) => item.trim())
  15. .filter(Boolean)
  16. function appendTimestampQuery(url) {
  17. const base = String(url || '')
  18. const ts = Date.now()
  19. if (!base) return `${base}?_t=${ts}`
  20. // 已有 _t 时覆盖为最新值,避免 query 反复堆叠
  21. if (/[?&]_t=/.test(base)) {
  22. return base.replace(/([?&]_t=)\d+/, `$1${ts}`)
  23. }
  24. return `${base}${base.includes('?') ? '&' : '?'}_t=${ts}`
  25. }
  26. function createUnauthorizedError(rawUrl = '') {
  27. const loginApiPattern = /\/web\/auth\/login(?:$|\?)/
  28. const message = loginApiPattern.test(String(rawUrl))
  29. ? '用户名或密码错误,请重新输入'
  30. : '登录状态已失效,请重新登录'
  31. const error = new Error(message)
  32. error.name = 'UnauthorizedError'
  33. return error
  34. }
  35. function getStoredToken() {
  36. const token = uni.getStorageSync(TOKEN_KEY)
  37. return typeof token === 'string' ? token.trim() : ''
  38. }
  39. async function onHttpUnauthorized(requestToken) {
  40. // 旧请求的失效响应不能清理用户随后登录的新会话。
  41. if (clearingAuth || getStoredToken() !== requestToken) return
  42. clearingAuth = true
  43. // 先同步清理本地登录态,避免 store 动态导入失败时仍被识别为已登录
  44. uni.removeStorageSync(TOKEN_KEY)
  45. uni.removeStorageSync(REFRESH_TOKEN_KEY)
  46. uni.removeStorageSync(USER_INFO_KEY)
  47. try {
  48. const { useUserStore } = await import('@/stores/user')
  49. if (getStoredToken()) {
  50. clearingAuth = false
  51. return
  52. }
  53. useUserStore().clearLoginInfo()
  54. } catch (error) {
  55. // ignore
  56. }
  57. if (getStoredToken()) {
  58. clearingAuth = false
  59. return
  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. if (!getStoredToken()) 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 isNativeFormData(data) {
  200. // 微信小程序等运行时可能不存在全局 FormData,直接 instanceof 会抛错
  201. return typeof FormData !== 'undefined' && data instanceof FormData
  202. }
  203. function shouldEncryptRequest(rawUrl, userId, data) {
  204. if (!API_ENCRYPT_ENABLED || !API_ENCRYPT_FIXED_SECRET) return false
  205. if (!rawUrl || !(/\/web\//.test(String(rawUrl)) || /\/mini\//.test(String(rawUrl)))) return false
  206. if (!userId) return false
  207. if (isNativeFormData(data)) return false
  208. return !API_ENCRYPT_EXCLUDE_PATHS.some((prefix) => String(rawUrl).startsWith(prefix))
  209. }
  210. function getEncryptSkipReason(rawUrl, userId, data) {
  211. if (!API_ENCRYPT_ENABLED) return 'encrypt-disabled'
  212. if (!API_ENCRYPT_FIXED_SECRET) return 'missing-fixed-secret'
  213. if (!rawUrl || !(/\/web\//.test(String(rawUrl)) || /\/mini\//.test(String(rawUrl)))) return 'non-api-path'
  214. if (!userId) return 'missing-user-id'
  215. if (isNativeFormData(data)) return 'form-data'
  216. if (API_ENCRYPT_EXCLUDE_PATHS.some((prefix) => String(rawUrl).startsWith(prefix))) return 'exclude-path'
  217. return ''
  218. }
  219. export function request(options) {
  220. if (clearingAuth) {
  221. return Promise.reject(createUnauthorizedError(options?.url))
  222. }
  223. const token = getStoredToken()
  224. const rawUrl = options.url || ''
  225. const method = String(options.method || 'GET').toUpperCase()
  226. const userIdFromStorage = (() => {
  227. const rawUserInfo = uni.getStorageSync(USER_INFO_KEY)
  228. if (rawUserInfo && typeof rawUserInfo === 'object') {
  229. return String(rawUserInfo.id || rawUserInfo.userId || '')
  230. }
  231. if (typeof rawUserInfo === 'string') {
  232. try {
  233. const parsed = JSON.parse(rawUserInfo)
  234. return String(parsed?.id || parsed?.userId || '')
  235. } catch (error) {
  236. return ''
  237. }
  238. }
  239. return ''
  240. })()
  241. const userId = userIdFromStorage || parseUserIdFromToken(token)
  242. const normalizedUrl = rawUrl.startsWith('http')
  243. ? rawUrl
  244. : `${resolveApiBase()}${rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`}`
  245. const url = appendTimestampQuery(normalizedUrl)
  246. const shouldEncrypt = shouldEncryptRequest(rawUrl, userId, options.data)
  247. const skipReason = shouldEncrypt ? '' : getEncryptSkipReason(rawUrl, userId, options.data)
  248. return new Promise(async (resolve, reject) => {
  249. const originalMethod = method
  250. const originalData = options.data
  251. const originalParams = options.params
  252. let reqMethod = method
  253. let reqData = options.data
  254. const reqHeader = {
  255. 'Content-Type': 'application/json',
  256. ...(token ? { Authorization: `Bearer ${token}` } : {}),
  257. ...(options.header || {})
  258. }
  259. // 便于在 HBuilderX/H5 的 Network 面板直接判断是否走了密文
  260. reqHeader['X-Api-Crypto'] = shouldEncrypt ? 'on' : `off:${skipReason || 'unknown'}`
  261. try {
  262. if (shouldEncrypt) {
  263. if (reqMethod === 'GET') {
  264. reqHeader['X-HTTP-Method-Override'] = 'GET'
  265. reqMethod = 'POST'
  266. reqData = options.data || options.params || {}
  267. }
  268. const ts = Date.now()
  269. const nonce = randomNonce()
  270. const keyHex = await deriveKey(API_ENCRYPT_FIXED_SECRET, userId, ts, nonce)
  271. const plainData = normalizeRequestData(reqData)
  272. const edata = await encryptJson({ data: plainData }, keyHex)
  273. reqData = {
  274. enc: 1,
  275. ts,
  276. nonce,
  277. edata
  278. }
  279. }
  280. } catch (error) {
  281. if (!API_ENCRYPT_FAIL_OPEN) {
  282. reject(error)
  283. return
  284. }
  285. }
  286. uni.request({
  287. ...options,
  288. method: reqMethod,
  289. data: reqData,
  290. url,
  291. header: reqHeader,
  292. success: async (res) => {
  293. // 后端未启用密文中间件(或未支持 method override)时,GET->POST 传输会触发 405;
  294. // 这里仅对“原始 GET + override”场景做一次降级回 GET,保证 H5 本地联调可用。
  295. if (
  296. res.statusCode === 405 &&
  297. originalMethod === 'GET' &&
  298. String(reqHeader['X-HTTP-Method-Override'] || '').toUpperCase() === 'GET'
  299. ) {
  300. const fallbackHeader = {
  301. ...reqHeader
  302. }
  303. delete fallbackHeader['X-HTTP-Method-Override']
  304. fallbackHeader['X-Api-Crypto'] = 'off:405-fallback'
  305. uni.request({
  306. ...options,
  307. method: 'GET',
  308. data: originalData || originalParams,
  309. url,
  310. header: fallbackHeader,
  311. success: (res2) => resolve(res2),
  312. fail: (err2) => reject(err2)
  313. })
  314. return
  315. }
  316. let payload = res.data
  317. if (shouldEncrypt && payload && payload.encrypted && payload.edata) {
  318. try {
  319. const respKeyHex = await deriveKey(
  320. API_ENCRYPT_FIXED_SECRET,
  321. userId,
  322. Number(payload.ts),
  323. String(payload.nonce || '')
  324. )
  325. payload = await decryptJson(payload.edata, respKeyHex)
  326. res.data = payload
  327. } catch (error) {
  328. if (!API_ENCRYPT_FAIL_OPEN) {
  329. reject(error)
  330. return
  331. }
  332. }
  333. }
  334. if (res.statusCode === 401 || isBizUnauthorized(payload)) {
  335. onHttpUnauthorized(token)
  336. reject(createUnauthorizedError(rawUrl))
  337. return
  338. }
  339. resolve(res)
  340. },
  341. fail: (err) => reject(err)
  342. })
  343. })
  344. }
  345. export function parseResponseJson(res) {
  346. const d = res.data
  347. if (d == null) return d
  348. if (typeof d === 'string') {
  349. try {
  350. return JSON.parse(d)
  351. } catch (error) {
  352. return d
  353. }
  354. }
  355. return d
  356. }