功能:收口小程序前后台安全与防重复提交
This commit is contained in:
+168
-21
@@ -1,9 +1,20 @@
|
||||
const auth = require('./auth')
|
||||
const { API_BASE_URL, REQUEST_TIMEOUT } = require('./config')
|
||||
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'
|
||||
|
||||
let isRefreshing = false
|
||||
let requestQueue = []
|
||||
let redirectingToAuth = false
|
||||
const inflightRequests = {}
|
||||
|
||||
function buildRequestUrl(url, params) {
|
||||
const query = Object.keys(params || {})
|
||||
@@ -36,13 +47,14 @@ function isWhitelistedPath(url) {
|
||||
}
|
||||
|
||||
function normalizeError(message, statusCode, raw) {
|
||||
const error = new Error(message || '请求失败')
|
||||
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
|
||||
error.statusCode = statusCode
|
||||
error.raw = raw
|
||||
return error
|
||||
}
|
||||
|
||||
function rawRequest(options) {
|
||||
idleSession.markActive()
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.request({
|
||||
...options,
|
||||
@@ -71,7 +83,6 @@ function flushQueue(error) {
|
||||
item.reject(error)
|
||||
return
|
||||
}
|
||||
|
||||
item.retry().then(item.resolve).catch(item.reject)
|
||||
})
|
||||
}
|
||||
@@ -92,7 +103,7 @@ function redirectToAuth() {
|
||||
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
|
||||
|
||||
wx.showToast({
|
||||
title: '登录已过期,请重新登录',
|
||||
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
|
||||
icon: 'none'
|
||||
})
|
||||
|
||||
@@ -106,10 +117,45 @@ function redirectToAuth() {
|
||||
}, 300)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
async function refreshToken() {
|
||||
const refreshTokenValue = auth.getRefreshToken()
|
||||
if (!refreshTokenValue) {
|
||||
throw normalizeError('缺少刷新令牌', 401)
|
||||
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
|
||||
}
|
||||
|
||||
const response = await rawRequest({
|
||||
@@ -117,7 +163,8 @@ async function refreshToken() {
|
||||
method: 'POST',
|
||||
timeout: REQUEST_TIMEOUT,
|
||||
header: {
|
||||
'Content-Type': 'application/json'
|
||||
'Content-Type': 'application/json',
|
||||
[DEVICE_ID_HEADER]: getDeviceId()
|
||||
},
|
||||
data: {
|
||||
refreshToken: refreshTokenValue
|
||||
@@ -134,7 +181,7 @@ async function refreshToken() {
|
||||
}
|
||||
|
||||
throw normalizeError(
|
||||
(response.data && response.data.message) || '刷新登录态失败',
|
||||
(response.data && response.data.message) || '\u5237\u65b0\u767b\u5f55\u6001\u5931\u8d25',
|
||||
response.statusCode,
|
||||
response
|
||||
)
|
||||
@@ -148,7 +195,7 @@ async function handleUnauthorized(options) {
|
||||
app.clearUserSession()
|
||||
}
|
||||
redirectToAuth()
|
||||
throw normalizeError('登录已过期,请重新登录', 401)
|
||||
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
|
||||
}
|
||||
|
||||
if (isRefreshing) {
|
||||
@@ -180,14 +227,16 @@ async function handleUnauthorized(options) {
|
||||
}
|
||||
}
|
||||
|
||||
function unwrapResponse(res, options) {
|
||||
async function unwrapResponse(res, options) {
|
||||
idleSession.markActive()
|
||||
|
||||
if (res.statusCode === 401) {
|
||||
return handleUnauthorized(options)
|
||||
}
|
||||
|
||||
if (res.statusCode >= 400) {
|
||||
throw normalizeError(
|
||||
(res.data && res.data.message) || '网络请求失败',
|
||||
(res.data && res.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
|
||||
res.statusCode,
|
||||
res
|
||||
)
|
||||
@@ -198,32 +247,110 @@ function unwrapResponse(res, options) {
|
||||
if (payload.code === 200) {
|
||||
return payload.data
|
||||
}
|
||||
|
||||
throw normalizeError(payload.message || '请求失败', payload.code, payload)
|
||||
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
function request(options) {
|
||||
const method = (options.method || 'GET').toUpperCase()
|
||||
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
|
||||
})
|
||||
const header = {
|
||||
'Content-Type': 'application/json',
|
||||
...signatureHeaders,
|
||||
...(options.header || {})
|
||||
}
|
||||
|
||||
const accessToken = auth.getAccessToken()
|
||||
if (accessToken) {
|
||||
header.Authorization = `Bearer ${accessToken}`
|
||||
}
|
||||
|
||||
const requestOptions = {
|
||||
...options,
|
||||
method,
|
||||
header
|
||||
}
|
||||
const actionGuardConfig = buildActionGuardConfig(options, method)
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const executeRequest = () => new Promise((resolve, reject) => {
|
||||
wx.request({
|
||||
url: buildRequestUrl(options.url, method === 'GET' ? options.params : undefined),
|
||||
method,
|
||||
@@ -239,10 +366,30 @@ function request(options) {
|
||||
}
|
||||
},
|
||||
fail: error => {
|
||||
reject(normalizeError(error.errMsg || '网络异常,请稍后重试', 0, error))
|
||||
reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
request.buildSignatureHeaders = buildSignatureHeaders
|
||||
request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER
|
||||
|
||||
module.exports = request
|
||||
|
||||
Reference in New Issue
Block a user