2026-04-01 15:18:35 +08:00
|
|
|
const auth = require('./auth')
|
2026-04-20 16:02:57 +08:00
|
|
|
const actionGuard = require('./action-guard')
|
|
|
|
|
const idleSession = require('./idle-session')
|
|
|
|
|
const { API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
|
|
|
|
|
const { getDeviceId } = require('./device')
|
|
|
|
|
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
|
|
|
|
|
|
|
|
|
|
const HEADER_TIMESTAMP = 'X-Timestamp'
|
|
|
|
|
const HEADER_NONCE = 'X-Nonce'
|
|
|
|
|
const HEADER_SIGNATURE = 'X-Signature'
|
|
|
|
|
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
|
|
|
|
|
const DEVICE_ID_HEADER = 'X-Device-Id'
|
2026-04-01 15:18:35 +08:00
|
|
|
|
|
|
|
|
let isRefreshing = false
|
|
|
|
|
let requestQueue = []
|
|
|
|
|
let redirectingToAuth = false
|
2026-04-20 16:02:57 +08:00
|
|
|
const inflightRequests = {}
|
2026-04-01 15:18:35 +08:00
|
|
|
|
|
|
|
|
function buildRequestUrl(url, params) {
|
|
|
|
|
const query = Object.keys(params || {})
|
|
|
|
|
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
|
|
|
|
|
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
|
|
|
|
.join('&')
|
|
|
|
|
|
|
|
|
|
const target = `${API_BASE_URL}${url}`
|
|
|
|
|
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function isWhitelistedPath(url) {
|
|
|
|
|
return [
|
|
|
|
|
'/user/login',
|
|
|
|
|
'/user/register',
|
|
|
|
|
'/user/check/',
|
|
|
|
|
'/user/refresh-token',
|
|
|
|
|
'/user/send-verification-code',
|
|
|
|
|
'/user/phone-login',
|
2026-04-02 13:20:28 +08:00
|
|
|
'/user/wechat-mini/',
|
2026-04-01 15:18:35 +08:00
|
|
|
'/user/reset-password-by-phone',
|
|
|
|
|
'/product/get/',
|
|
|
|
|
'/product/list/',
|
|
|
|
|
'/shop/get/',
|
|
|
|
|
'/shop/list/public',
|
|
|
|
|
'/shop/list/simple',
|
|
|
|
|
'/tag/list/all',
|
|
|
|
|
'/file/get-signed-url/'
|
|
|
|
|
].some(path => String(url || '').includes(path))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function normalizeError(message, statusCode, raw) {
|
2026-04-20 16:02:57 +08:00
|
|
|
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
|
2026-04-01 15:18:35 +08:00
|
|
|
error.statusCode = statusCode
|
|
|
|
|
error.raw = raw
|
|
|
|
|
return error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function rawRequest(options) {
|
2026-04-20 16:02:57 +08:00
|
|
|
idleSession.markActive()
|
2026-04-01 15:18:35 +08:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
wx.request({
|
|
|
|
|
...options,
|
|
|
|
|
success: resolve,
|
|
|
|
|
fail: reject
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function queueRequest(retry) {
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
requestQueue.push({
|
|
|
|
|
resolve,
|
|
|
|
|
reject,
|
|
|
|
|
retry
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function flushQueue(error) {
|
|
|
|
|
const queue = requestQueue.slice()
|
|
|
|
|
requestQueue = []
|
|
|
|
|
|
|
|
|
|
queue.forEach(item => {
|
|
|
|
|
if (error) {
|
|
|
|
|
item.reject(error)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
item.retry().then(item.resolve).catch(item.reject)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function redirectToAuth() {
|
|
|
|
|
if (redirectingToAuth) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
redirectingToAuth = true
|
|
|
|
|
const pages = getCurrentPages()
|
|
|
|
|
const current = pages[pages.length - 1]
|
|
|
|
|
const currentPath = current ? `/${current.route}` : '/pages/home/index'
|
|
|
|
|
const currentQuery = current && current.options ? current.options : {}
|
|
|
|
|
const queryString = Object.keys(currentQuery)
|
|
|
|
|
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(currentQuery[key])}`)
|
|
|
|
|
.join('&')
|
|
|
|
|
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
|
|
|
|
|
|
|
|
|
|
wx.showToast({
|
2026-04-20 16:02:57 +08:00
|
|
|
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
|
2026-04-01 15:18:35 +08:00
|
|
|
icon: 'none'
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
wx.reLaunch({
|
|
|
|
|
url: `/pages/auth/index?redirect=${encodeURIComponent(redirect)}`,
|
|
|
|
|
complete() {
|
|
|
|
|
redirectingToAuth = false
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}, 300)
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-20 16:02:57 +08:00
|
|
|
function buildSignatureHeaders(options) {
|
|
|
|
|
const headers = {
|
|
|
|
|
[DEVICE_ID_HEADER]: getDeviceId()
|
|
|
|
|
}
|
|
|
|
|
const method = String(options.method || 'GET').toUpperCase()
|
|
|
|
|
const accessToken = auth.getAccessToken()
|
|
|
|
|
if (accessToken && !isWhitelistedPath(options.url)) {
|
|
|
|
|
headers.Authorization = `Bearer ${accessToken}`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!ENABLE_REQUEST_SIGNING || !accessToken || isWhitelistedPath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) {
|
|
|
|
|
return headers
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase()
|
|
|
|
|
const payload = contentType.includes('application/json')
|
|
|
|
|
? buildJsonPayload(options.data)
|
|
|
|
|
: buildCanonicalParams(options.formData || options.data || options.params)
|
|
|
|
|
const timestamp = String(Date.now())
|
|
|
|
|
const nonce = randomNonce()
|
|
|
|
|
const canonical = [
|
|
|
|
|
method,
|
|
|
|
|
options.url,
|
|
|
|
|
timestamp,
|
|
|
|
|
nonce,
|
|
|
|
|
sha256Hex(payload)
|
|
|
|
|
].join('\n')
|
|
|
|
|
|
|
|
|
|
headers[HEADER_TIMESTAMP] = timestamp
|
|
|
|
|
headers[HEADER_NONCE] = nonce
|
|
|
|
|
headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical)
|
|
|
|
|
headers[HEADER_SIGNATURE_VERSION] = 'v1'
|
|
|
|
|
return headers
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-01 15:18:35 +08:00
|
|
|
async function refreshToken() {
|
|
|
|
|
const refreshTokenValue = auth.getRefreshToken()
|
|
|
|
|
if (!refreshTokenValue) {
|
2026-04-20 16:02:57 +08:00
|
|
|
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
|
2026-04-01 15:18:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const response = await rawRequest({
|
|
|
|
|
url: `${API_BASE_URL}/user/refresh-token`,
|
|
|
|
|
method: 'POST',
|
|
|
|
|
timeout: REQUEST_TIMEOUT,
|
|
|
|
|
header: {
|
2026-04-20 16:02:57 +08:00
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
[DEVICE_ID_HEADER]: getDeviceId()
|
2026-04-01 15:18:35 +08:00
|
|
|
},
|
|
|
|
|
data: {
|
|
|
|
|
refreshToken: refreshTokenValue
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (response.statusCode === 200 && response.data && response.data.code === 200 && response.data.data) {
|
|
|
|
|
auth.setSession(response.data.data)
|
|
|
|
|
const app = getApp()
|
|
|
|
|
if (app && typeof app.bootstrapSession === 'function') {
|
|
|
|
|
app.bootstrapSession()
|
|
|
|
|
}
|
|
|
|
|
return response.data.data
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw normalizeError(
|
2026-04-20 16:02:57 +08:00
|
|
|
(response.data && response.data.message) || '\u5237\u65b0\u767b\u5f55\u6001\u5931\u8d25',
|
2026-04-01 15:18:35 +08:00
|
|
|
response.statusCode,
|
|
|
|
|
response
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function handleUnauthorized(options) {
|
|
|
|
|
if (options._retry || isWhitelistedPath(options.url)) {
|
|
|
|
|
auth.clearSession()
|
|
|
|
|
const app = getApp()
|
|
|
|
|
if (app && typeof app.clearUserSession === 'function') {
|
|
|
|
|
app.clearUserSession()
|
|
|
|
|
}
|
|
|
|
|
redirectToAuth()
|
2026-04-20 16:02:57 +08:00
|
|
|
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
|
2026-04-01 15:18:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isRefreshing) {
|
|
|
|
|
return queueRequest(() => request({
|
|
|
|
|
...options,
|
|
|
|
|
_retry: true
|
|
|
|
|
}))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isRefreshing = true
|
|
|
|
|
try {
|
|
|
|
|
await refreshToken()
|
|
|
|
|
flushQueue(null)
|
|
|
|
|
return await request({
|
|
|
|
|
...options,
|
|
|
|
|
_retry: true
|
|
|
|
|
})
|
|
|
|
|
} catch (error) {
|
|
|
|
|
flushQueue(error)
|
|
|
|
|
auth.clearSession()
|
|
|
|
|
const app = getApp()
|
|
|
|
|
if (app && typeof app.clearUserSession === 'function') {
|
|
|
|
|
app.clearUserSession()
|
|
|
|
|
}
|
|
|
|
|
redirectToAuth()
|
|
|
|
|
throw error
|
|
|
|
|
} finally {
|
|
|
|
|
isRefreshing = false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-20 16:02:57 +08:00
|
|
|
async function unwrapResponse(res, options) {
|
|
|
|
|
idleSession.markActive()
|
|
|
|
|
|
2026-04-01 15:18:35 +08:00
|
|
|
if (res.statusCode === 401) {
|
|
|
|
|
return handleUnauthorized(options)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (res.statusCode >= 400) {
|
|
|
|
|
throw normalizeError(
|
2026-04-20 16:02:57 +08:00
|
|
|
(res.data && res.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
|
2026-04-01 15:18:35 +08:00
|
|
|
res.statusCode,
|
|
|
|
|
res
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const payload = res.data
|
|
|
|
|
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
|
|
|
|
|
if (payload.code === 200) {
|
|
|
|
|
return payload.data
|
|
|
|
|
}
|
2026-04-20 16:02:57 +08:00
|
|
|
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
|
2026-04-01 15:18:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return payload
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-20 16:02:57 +08:00
|
|
|
function buildDedupeKey(options, method) {
|
|
|
|
|
if (options.skipDedupe) {
|
|
|
|
|
return ''
|
|
|
|
|
}
|
|
|
|
|
if (options.dedupeKey) {
|
|
|
|
|
return `${method}:${options.dedupeKey}`
|
|
|
|
|
}
|
|
|
|
|
if (method === 'GET') {
|
|
|
|
|
return `${method}:${options.url}:${buildCanonicalParams(options.params)}`
|
|
|
|
|
}
|
|
|
|
|
return ''
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function isSafeMethod(method) {
|
|
|
|
|
return ['GET', 'HEAD', 'OPTIONS'].includes(method)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function buildActionFingerprint(options, method) {
|
|
|
|
|
const paramsText = buildCanonicalParams(options.params)
|
|
|
|
|
const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data)
|
|
|
|
|
return sha256Hex([
|
|
|
|
|
options.url || '',
|
|
|
|
|
paramsText,
|
|
|
|
|
payloadText
|
|
|
|
|
].join('\n'))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function resolveRepeatMessage(url) {
|
|
|
|
|
const path = String(url || '')
|
|
|
|
|
if (
|
|
|
|
|
path.includes('/user/login')
|
|
|
|
|
|| path.includes('/user/phone-login')
|
|
|
|
|
|| path.includes('/user/register')
|
|
|
|
|
|| path.includes('/user/reset-password-by-phone')
|
|
|
|
|
|| path.includes('/user/wechat-mini/')
|
|
|
|
|
) {
|
|
|
|
|
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
|
|
|
|
|
}
|
|
|
|
|
if (path.includes('/send-verification-code')) {
|
|
|
|
|
return '\u9a8c\u8bc1\u7801\u53d1\u9001\u5904\u7406\u4e2d\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5'
|
|
|
|
|
}
|
|
|
|
|
if (path.includes('/switch-shop')) {
|
|
|
|
|
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
|
|
|
|
|
}
|
|
|
|
|
if (path.includes('/order/create')) {
|
|
|
|
|
return '\u8ba2\u5355\u6b63\u5728\u63d0\u4ea4\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
|
|
|
|
|
}
|
|
|
|
|
if (path.includes('/upload')) {
|
|
|
|
|
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
|
|
|
|
|
}
|
|
|
|
|
if (path.includes('/logout')) {
|
|
|
|
|
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
|
|
|
|
|
}
|
|
|
|
|
if (path.includes('/cart/')) {
|
|
|
|
|
return '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
|
|
|
|
|
}
|
|
|
|
|
return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function buildActionGuardConfig(options, method) {
|
|
|
|
|
if (options.skipActionGuard || isSafeMethod(method)) {
|
|
|
|
|
return null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
scope: options.guardScope,
|
|
|
|
|
key: options.actionKey || `${method}:${options.url}:${buildActionFingerprint(options, method)}`,
|
|
|
|
|
message: options.repeatMessage || resolveRepeatMessage(options.url)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-01 15:18:35 +08:00
|
|
|
function request(options) {
|
2026-04-20 16:02:57 +08:00
|
|
|
const method = String(options.method || 'GET').toUpperCase()
|
|
|
|
|
const dedupeKey = buildDedupeKey(options, method)
|
|
|
|
|
if (dedupeKey && inflightRequests[dedupeKey]) {
|
|
|
|
|
return inflightRequests[dedupeKey]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const signatureHeaders = buildSignatureHeaders({
|
|
|
|
|
url: options.url,
|
|
|
|
|
method,
|
|
|
|
|
data: options.data,
|
|
|
|
|
params: options.params,
|
|
|
|
|
header: options.header
|
|
|
|
|
})
|
2026-04-01 15:18:35 +08:00
|
|
|
const header = {
|
|
|
|
|
'Content-Type': 'application/json',
|
2026-04-20 16:02:57 +08:00
|
|
|
...signatureHeaders,
|
2026-04-01 15:18:35 +08:00
|
|
|
...(options.header || {})
|
|
|
|
|
}
|
|
|
|
|
const requestOptions = {
|
|
|
|
|
...options,
|
|
|
|
|
method,
|
|
|
|
|
header
|
|
|
|
|
}
|
2026-04-20 16:02:57 +08:00
|
|
|
const actionGuardConfig = buildActionGuardConfig(options, method)
|
2026-04-01 15:18:35 +08:00
|
|
|
|
2026-04-20 16:02:57 +08:00
|
|
|
const executeRequest = () => new Promise((resolve, reject) => {
|
2026-04-01 15:18:35 +08:00
|
|
|
wx.request({
|
|
|
|
|
url: buildRequestUrl(options.url, method === 'GET' ? options.params : undefined),
|
|
|
|
|
method,
|
|
|
|
|
timeout: options.timeout || REQUEST_TIMEOUT,
|
|
|
|
|
header,
|
|
|
|
|
data: method === 'GET' ? undefined : options.data,
|
|
|
|
|
success: async res => {
|
|
|
|
|
try {
|
|
|
|
|
const data = await unwrapResponse(res, requestOptions)
|
|
|
|
|
resolve(data)
|
|
|
|
|
} catch (error) {
|
|
|
|
|
reject(error)
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
fail: error => {
|
2026-04-20 16:02:57 +08:00
|
|
|
reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error))
|
2026-04-01 15:18:35 +08:00
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
})
|
2026-04-20 16:02:57 +08:00
|
|
|
|
|
|
|
|
const task = (actionGuardConfig
|
|
|
|
|
? actionGuard.run(actionGuardConfig.scope, actionGuardConfig.key, executeRequest, {
|
|
|
|
|
message: actionGuardConfig.message
|
|
|
|
|
})
|
|
|
|
|
: executeRequest()
|
|
|
|
|
).finally(() => {
|
|
|
|
|
if (dedupeKey) {
|
|
|
|
|
delete inflightRequests[dedupeKey]
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (dedupeKey) {
|
|
|
|
|
inflightRequests[dedupeKey] = task
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return task
|
2026-04-01 15:18:35 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-20 16:02:57 +08:00
|
|
|
request.buildSignatureHeaders = buildSignatureHeaders
|
|
|
|
|
request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER
|
|
|
|
|
|
2026-04-01 15:18:35 +08:00
|
|
|
module.exports = request
|