Files

561 lines
20 KiB
JavaScript
Raw Permalink Normal View History

2026-05-23 18:45:41 +08:00
/**
* Purpose: auth supports request.js by holding or executing the auth page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const auth = require('./auth')
2026-05-23 18:45:41 +08:00
/**
* Purpose: actionGuard supports request.js by holding or executing the action guard page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const actionGuard = require('./action-guard')
2026-05-23 18:45:41 +08:00
/**
* Purpose: idleSession supports request.js by holding or executing the idle session page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const idleSession = require('./idle-session')
const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
2026-05-23 18:45:41 +08:00
/**
* Purpose: DEVICE_ID_HEADER supports request.js by holding or executing the device id header page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEVICE_ID_HEADER = 'X-Device-Id'
2026-05-23 18:45:41 +08:00
/**
* Purpose: HEADER_TIMESTAMP supports request.js by holding or executing the header timestamp page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_TIMESTAMP = 'X-Timestamp'
2026-05-23 18:45:41 +08:00
/**
* Purpose: HEADER_NONCE supports request.js by holding or executing the header nonce page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_NONCE = 'X-Nonce'
2026-05-23 18:45:41 +08:00
/**
* Purpose: HEADER_SIGNATURE supports request.js by holding or executing the header signature page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_SIGNATURE = 'X-Signature'
2026-05-23 18:45:41 +08:00
/**
* Purpose: HEADER_SIGNATURE_VERSION supports request.js by holding or executing the header signature version page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
2026-05-23 18:45:41 +08:00
/**
* Purpose: isRefreshing supports request.js by holding or executing the is refreshing page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let isRefreshing = false
2026-05-23 18:45:41 +08:00
/**
* Purpose: requestQueue supports request.js by holding or executing the request queue page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let requestQueue = []
2026-05-23 18:45:41 +08:00
/**
* Purpose: redirectingToLogin supports request.js by holding or executing the redirecting to login page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let redirectingToLogin = false
2026-05-23 18:45:41 +08:00
/**
* Purpose: inflightRequests supports request.js by holding or executing the inflight requests page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const inflightRequests = {}
2026-05-23 18:45:41 +08:00
/**
* Purpose: buildRequestUrl supports request.js by holding or executing the build request url page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
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 = `${ADMIN_API_BASE_URL}${url}`
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: extractPath supports request.js by holding or executing the extract path page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function extractPath(value) {
const target = String(value || '')
if (!target) {
return ''
}
if (/^[a-z][a-z\d+\-.]*:\/\//i.test(target)) {
try {
return new URL(target).pathname
} catch (error) {}
}
return target.split('?')[0] || ''
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: toBackendRequestPath supports request.js by holding or executing the to backend request path page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function toBackendRequestPath(url) {
const path = extractPath(url).replace(/\/+$/, '') || '/'
if (path === '/admin/api') {
return '/admin'
}
if (path.startsWith('/admin/api/')) {
return `/admin/${path.slice('/admin/api/'.length)}`
}
if (path === '/api/admin') {
return '/admin'
}
if (path.startsWith('/api/admin/')) {
return `/admin/${path.slice('/api/admin/'.length)}`
}
if (path === '/admin' || path.startsWith('/admin/')) {
return path
}
return path.startsWith('/') ? `/admin${path}` : `/admin/${path}`
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: isAuthFreePath supports request.js by holding or executing the is auth free path page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isAuthFreePath(url) {
return [
'/auth/login',
'/auth/refresh',
'/auth/login-shops/'
].some(path => String(url || '').includes(path))
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: normalizeError supports request.js by holding or executing the normalize error page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function normalizeError(message, statusCode, raw) {
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
error.statusCode = statusCode
error.raw = raw
return error
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: rawRequest supports request.js by holding or executing the raw request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function rawRequest(options) {
idleSession.markActive()
return new Promise((resolve, reject) => {
wx.request({
...options,
success: resolve,
fail: reject
})
})
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: queueRequest supports request.js by holding or executing the queue request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function queueRequest(retry) {
return new Promise((resolve, reject) => {
requestQueue.push({
resolve,
reject,
retry
})
})
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: flushQueue supports request.js by holding or executing the flush queue page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
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)
})
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: redirectToLogin supports request.js by holding or executing the redirect to login page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function redirectToLogin() {
if (redirectingToLogin) {
return
}
const pages = getCurrentPages()
const current = pages[pages.length - 1]
2026-06-04 16:39:06 +08:00
if (current && current.route === 'admin/pages/login/index') {
return
}
redirectingToLogin = true
2026-06-04 16:39:06 +08:00
const currentPath = current ? `/${current.route}` : '/admin/pages/workbench/index'
const query = current && current.options ? current.options : {}
const queryString = Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&')
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
wx.showToast({
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
icon: 'none'
})
setTimeout(() => {
wx.reLaunch({
2026-06-04 16:39:06 +08:00
url: `/admin/pages/login/index?redirect=${encodeURIComponent(redirect)}`,
complete() {
redirectingToLogin = false
}
})
}, 240)
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: buildSignatureHeaders supports request.js by holding or executing the build signature headers page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildSignatureHeaders(options) {
const headers = {
[DEVICE_ID_HEADER]: getDeviceId()
}
const method = String(options.method || 'GET').toUpperCase()
const accessToken = auth.getAccessToken()
if (accessToken && !isAuthFreePath(options.url)) {
headers.Authorization = `Bearer ${accessToken}`
}
if (!ENABLE_REQUEST_SIGNING || !accessToken || isAuthFreePath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) {
return headers
}
const formData = options.formData
const hasFormData = formData && Object.keys(formData).length > 0
const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase()
const payload = contentType.includes('application/json') && !hasFormData
? buildJsonPayload(options.data)
: buildCanonicalParams(formData || options.data || options.params)
const timestamp = String(Date.now())
const nonce = randomNonce()
const canonical = [
method,
toBackendRequestPath(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-05-23 18:45:41 +08:00
/**
* Purpose: refreshToken supports request.js by holding or executing the refresh token page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function refreshToken() {
const refreshTokenValue = auth.getRefreshToken()
if (!refreshTokenValue) {
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
}
const response = await rawRequest({
url: `${ADMIN_API_BASE_URL}/auth/refresh`,
method: 'POST',
timeout: REQUEST_TIMEOUT,
header: {
'Content-Type': 'application/json',
[DEVICE_ID_HEADER]: getDeviceId()
},
data: {
refreshToken: refreshTokenValue
}
})
if (response.statusCode === 200 && response.data && response.data.code === 200 && response.data.data) {
auth.setSession(response.data.data)
const app = getApp()
2026-06-04 16:39:06 +08:00
if (app && typeof app.bootstrapAdminSession === 'function') {
app.bootstrapAdminSession()
}
return response.data.data
}
throw normalizeError(
(response.data && response.data.message) || '\u5237\u65b0\u540e\u53f0\u767b\u5f55\u6001\u5931\u8d25',
response.statusCode,
response
)
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: handleUnauthorized supports request.js by holding or executing the handle unauthorized page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function handleUnauthorized(options) {
if (options._retry || isAuthFreePath(options.url)) {
const app = getApp()
if (app && typeof app.clearAdminSession === 'function') {
app.clearAdminSession()
} else {
auth.clearSession()
}
redirectToLogin()
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
}
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)
const app = getApp()
if (app && typeof app.clearAdminSession === 'function') {
app.clearAdminSession()
} else {
auth.clearSession()
}
redirectToLogin()
throw error
} finally {
isRefreshing = false
}
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: unwrapResponse supports request.js by holding or executing the unwrap response page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function unwrapResponse(response, options) {
idleSession.markActive()
if (response.statusCode === 401) {
return handleUnauthorized(options)
}
if (response.statusCode === 403) {
throw normalizeError(
(response.data && response.data.message) || '\u6743\u9650\u4e0d\u8db3',
response.statusCode,
response
)
}
if (response.statusCode >= 400) {
throw normalizeError(
(response.data && response.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
response.statusCode,
response
)
}
const payload = response.data
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
if (payload.code === 200) {
return payload.data
}
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
}
return payload
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: buildDedupeKey supports request.js by holding or executing the build dedupe key page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
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 ''
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: isSafeMethod supports request.js by holding or executing the is safe method page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isSafeMethod(method) {
return ['GET', 'HEAD', 'OPTIONS'].includes(method)
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: buildActionFingerprint supports request.js by holding or executing the build action fingerprint page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildActionFingerprint(options, method) {
const paramsText = buildCanonicalParams(options.params)
const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data)
return sha256Hex([
options.url || '',
paramsText,
payloadText
].join('\n'))
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: resolveRepeatMessage supports request.js by holding or executing the resolve repeat message page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resolveRepeatMessage(url) {
const path = String(url || '')
if (path.includes('/auth/login')) {
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/auth/switch-shop')) {
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/auth/logout')) {
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/coupon/distribute') || path.includes('/coupon/assign') || path.includes('/order/update-status')) {
return '\u64cd\u4f5c\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/upload')) {
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (
path.includes('/user/create')
|| path.includes('/user/update')
|| path.includes('/product/create')
|| path.includes('/product/update')
|| path.includes('/shops/create')
|| path.includes('/shops/update')
|| path.includes('/tag/create')
|| path.includes('/tag/update')
|| path.includes('/permission/create')
|| path.includes('/permission/update')
|| path.includes('/nail-artist/save')
) {
return '\u4fdd\u5b58\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: buildActionGuardConfig supports request.js by holding or executing the build action guard config page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
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-05-23 18:45:41 +08:00
/**
* Purpose: request supports request.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function request(options) {
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 requestOptions = {
...options,
method,
header
}
const actionGuardConfig = buildActionGuardConfig(options, method)
const executeRequest = () => new Promise((resolve, reject) => {
wx.request({
url: buildRequestUrl(options.url, options.params),
method,
timeout: options.timeout || REQUEST_TIMEOUT,
header,
data: method === 'GET' ? undefined : options.data,
success: async response => {
try {
const data = await unwrapResponse(response, requestOptions)
resolve(data)
} catch (error) {
reject(error)
}
},
fail: 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