52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import type { InternalAxiosRequestConfig } from 'axios'
|
|
import { createHash, createHmac } from 'node:crypto'
|
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
import { attachRequestSignature } from './request-signature'
|
|
|
|
describe('request signature', () => {
|
|
afterEach(() => {
|
|
vi.restoreAllMocks()
|
|
vi.unstubAllGlobals()
|
|
localStorage.clear()
|
|
})
|
|
|
|
it('falls back when Web Crypto subtle digest is unavailable', async () => {
|
|
vi.spyOn(Date, 'now').mockReturnValue(1700000000000)
|
|
vi.stubGlobal('crypto', {
|
|
randomUUID: () => 'fallback-id'
|
|
})
|
|
|
|
const config = {
|
|
method: 'post',
|
|
baseURL: '/api',
|
|
url: '/order/checkout-preview',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
data: {
|
|
items: []
|
|
}
|
|
} as unknown as InternalAxiosRequestConfig
|
|
|
|
await attachRequestSignature(config, 'access-token')
|
|
|
|
const headers = config.headers as Record<string, string>
|
|
const payloadHash = createHash('sha256').update(JSON.stringify({ items: [] })).digest('hex')
|
|
const canonical = [
|
|
'POST',
|
|
'/order/checkout-preview',
|
|
'1700000000000',
|
|
'1700000000000-fallback-id',
|
|
payloadHash
|
|
].join('\n')
|
|
const expectedSignature = createHmac('sha256', 'access-token').update(canonical).digest('hex')
|
|
|
|
expect(headers['X-Timestamp']).toBe('1700000000000')
|
|
expect(headers['X-Nonce']).toBe('1700000000000-fallback-id')
|
|
expect(headers['X-Sign-Version']).toBe('v1')
|
|
expect(headers['X-Signature']).toBe(expectedSignature)
|
|
})
|
|
})
|