修复店务前端请求签名

This commit is contained in:
2026-07-01 13:03:29 +08:00
parent 9f1d2dec77
commit 5756d14fbd
2 changed files with 92 additions and 13 deletions
@@ -54,10 +54,40 @@ describe('request signature', () => {
const canonical = [
'POST',
'/admin/manager/planning/appointments',
'a=1&b=2',
payloadHash,
'1789999999000',
'1789999999000-00000000-0000-4000-8000-000000000001-ak'
'1789999999000-00000000-0000-4000-8000-000000000001-ak',
payloadHash
].join('\n')
const expectedSignature = createHmac('sha256', 'token-secret').update(canonical).digest('hex')
expect(config.headers['X-Signature']).toBe(expectedSignature)
})
it('hashes canonical parameters as payload when unsafe request has no json body', async () => {
vi.spyOn(Date, 'now').mockReturnValue(1_789_999_999_000)
vi.stubGlobal('crypto', {
randomUUID: () => '00000000-0000-4000-8000-000000000001',
getRandomValues: (array: Uint32Array) => {
array[0] = 10
array[1] = 20
return array
}
})
const config = await attachRequestSignature({
headers: {},
method: 'post',
baseURL: '/admin/api',
url: '/manager/example',
params: { b: 2, a: 1 },
data: undefined
} as InternalAxiosRequestConfig, 'token-secret', { authFree: false })
const payloadHash = createHash('sha256').update('a=1&b=2').digest('hex')
const canonical = [
'POST',
'/admin/manager/example',
'1789999999000',
'1789999999000-00000000-0000-4000-8000-000000000001-ak',
payloadHash
].join('\n')
const expectedSignature = createHmac('sha256', 'token-secret').update(canonical).digest('hex')
+59 -10
View File
@@ -225,19 +225,53 @@ const toBackendRequestPath = (config: InternalAxiosRequestConfig): string => {
return `${basePath}${urlPath.startsWith('/') ? urlPath : `/${urlPath}`}`.replace(/^\/admin\/api/, '/admin')
}
const buildCanonicalParams = (params: unknown): string => {
if (!params || typeof params !== 'object') {
const appendParam = (target: Record<string, string[]>, key: string, value: unknown): void => {
if (value === undefined || value === null || value === '') {
return
}
if (Array.isArray(value)) {
value.forEach(item => appendParam(target, key, item))
return
}
target[key] = [...(target[key] || []), String(value)]
}
const collectParams = (source: unknown, target: Record<string, string[]>): void => {
if (!source) {
return
}
if (source instanceof URLSearchParams) {
source.forEach((value, key) => appendParam(target, key, value))
return
}
if (source instanceof FormData) {
source.forEach((value, key) => {
if (!(value instanceof Blob)) {
appendParam(target, key, value)
}
})
return
}
if (typeof source === 'object') {
Object.entries(source as Record<string, unknown>).forEach(([key, value]) => appendParam(target, key, value))
}
}
const buildCanonicalParams = (params: unknown, data: unknown): string => {
const values: Record<string, string[]> = {}
collectParams(params, values)
collectParams(data, values)
if (Object.keys(values).length === 0) {
return ''
}
return Object.entries(params as Record<string, unknown>)
.filter(([, value]) => value !== undefined && value !== null && value !== '')
return Object.entries(values)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
.map(([key, value]) => `${key}=${value.sort().join(',')}`)
.join('&')
}
const buildJsonPayload = (data: unknown): string => {
if (data === undefined || data === null || data instanceof FormData) {
if (data === undefined || data === null || data === '' || data instanceof FormData) {
return ''
}
if (typeof data === 'string') {
@@ -246,6 +280,22 @@ const buildJsonPayload = (data: unknown): string => {
return JSON.stringify(data)
}
const getHeader = (headers: HeaderContainer, key: string): string => {
const matchedKey = Object.keys(headers).find(item => item.toLowerCase() === key.toLowerCase())
return matchedKey ? String(headers[matchedKey] || '') : ''
}
const resolvePayload = (config: InternalAxiosRequestConfig, headers: HeaderContainer): string => {
const contentType = getHeader(headers, 'Content-Type').toLowerCase()
const shouldBuildJsonPayload = contentType.includes('application/json')
|| (!contentType && config.data !== undefined && !(config.data instanceof FormData) && !(config.data instanceof URLSearchParams))
const jsonPayload = shouldBuildJsonPayload ? buildJsonPayload(config.data) : ''
if (jsonPayload) {
return jsonPayload
}
return buildCanonicalParams(config.params, config.data)
}
export const attachRequestSignature = async (
config: InternalAxiosRequestConfig,
accessToken: string,
@@ -261,14 +311,13 @@ export const attachRequestSignature = async (
}
const timestamp = String(Date.now())
const nonce = randomNonce(deviceId)
const payload = buildJsonPayload(config.data)
const payload = resolvePayload(config, headers)
const canonical = [
method,
toBackendRequestPath(config),
buildCanonicalParams(config.params),
await sha256Hex(payload),
timestamp,
nonce
nonce,
await sha256Hex(payload)
].join('\n')
setHeader(headers, HEADER_TIMESTAMP, timestamp)
setHeader(headers, HEADER_NONCE, nonce)