Files
JayuCloud/JY-Salon-Front/src/utils/request-signature.ts
T

336 lines
11 KiB
TypeScript

import type { InternalAxiosRequestConfig } from 'axios'
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'
const DEVICE_ID_STORAGE_KEY = 'jayu_salon_web_device_id'
const SIGNATURE_VERSION = 'v1'
type HeaderContainer = Record<string, unknown>
export interface RequestSignatureOptions {
authFree: boolean
}
const SHA256_K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
])
const isSafeMethod = (method: string): boolean => ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())
const toHex = (bytes: ArrayBuffer | Uint8Array): string => {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
return Array.from(view).map(value => value.toString(16).padStart(2, '0')).join('')
}
const encodeUtf8 = (text: string): Uint8Array => {
return new TextEncoder().encode(text)
}
const toArrayBuffer = (bytes: Uint8Array): ArrayBuffer => {
const buffer = new ArrayBuffer(bytes.byteLength)
new Uint8Array(buffer).set(bytes)
return buffer
}
const rightRotate = (value: number, bits: number): number => {
return (value >>> bits) | (value << (32 - bits))
}
const concatBytes = (left: Uint8Array, right: Uint8Array): Uint8Array => {
const result = new Uint8Array(left.length + right.length)
result.set(left, 0)
result.set(right, left.length)
return result
}
const sha256Bytes = (input: Uint8Array): Uint8Array => {
const paddedLength = Math.ceil((input.length + 9) / 64) * 64
const padded = new Uint8Array(paddedLength)
padded.set(input)
padded[input.length] = 0x80
const bitLength = input.length * 8
const view = new DataView(padded.buffer)
view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false)
view.setUint32(paddedLength - 4, bitLength >>> 0, false)
let h0 = 0x6a09e667
let h1 = 0xbb67ae85
let h2 = 0x3c6ef372
let h3 = 0xa54ff53a
let h4 = 0x510e527f
let h5 = 0x9b05688c
let h6 = 0x1f83d9ab
let h7 = 0x5be0cd19
const words = new Uint32Array(64)
for (let offset = 0; offset < paddedLength; offset += 64) {
for (let index = 0; index < 16; index++) {
words[index] = view.getUint32(offset + index * 4, false)
}
for (let index = 16; index < 64; index++) {
const word15 = words[index - 15]!
const word2 = words[index - 2]!
const s0 = rightRotate(word15, 7) ^ rightRotate(word15, 18) ^ (word15 >>> 3)
const s1 = rightRotate(word2, 17) ^ rightRotate(word2, 19) ^ (word2 >>> 10)
words[index] = (words[index - 16]! + s0 + words[index - 7]! + s1) >>> 0
}
let a = h0
let b = h1
let c = h2
let d = h3
let e = h4
let f = h5
let g = h6
let h = h7
for (let index = 0; index < 64; index++) {
const s1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)
const ch = (e & f) ^ (~e & g)
const temp1 = (h + s1 + ch + SHA256_K[index]! + words[index]!) >>> 0
const s0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)
const maj = (a & b) ^ (a & c) ^ (b & c)
const temp2 = (s0 + maj) >>> 0
h = g
g = f
f = e
e = (d + temp1) >>> 0
d = c
c = b
b = a
a = (temp1 + temp2) >>> 0
}
h0 = (h0 + a) >>> 0
h1 = (h1 + b) >>> 0
h2 = (h2 + c) >>> 0
h3 = (h3 + d) >>> 0
h4 = (h4 + e) >>> 0
h5 = (h5 + f) >>> 0
h6 = (h6 + g) >>> 0
h7 = (h7 + h) >>> 0
}
const output = new Uint8Array(32)
const outputView = new DataView(output.buffer)
;[h0, h1, h2, h3, h4, h5, h6, h7].forEach((value, index) => {
outputView.setUint32(index * 4, value, false)
})
return output
}
const hmacSha256Bytes = (secret: string, message: string): Uint8Array => {
const blockSize = 64
let key = encodeUtf8(secret)
if (key.length > blockSize) {
key = sha256Bytes(key)
}
const paddedKey = new Uint8Array(blockSize)
paddedKey.set(key)
const outer = new Uint8Array(blockSize)
const inner = new Uint8Array(blockSize)
for (let index = 0; index < blockSize; index++) {
outer[index] = paddedKey[index]! ^ 0x5c
inner[index] = paddedKey[index]! ^ 0x36
}
return sha256Bytes(concatBytes(outer, sha256Bytes(concatBytes(inner, encodeUtf8(message)))))
}
const getSubtleCrypto = (): SubtleCrypto | undefined => {
return globalThis.crypto?.subtle
}
const sha256Hex = async (message: string): Promise<string> => {
const bytes = encodeUtf8(message)
const subtle = getSubtleCrypto()
if (!subtle) {
return toHex(sha256Bytes(bytes))
}
const digest = await subtle.digest('SHA-256', toArrayBuffer(bytes))
return toHex(digest)
}
const hmacSha256Hex = async (secret: string, message: string): Promise<string> => {
const subtle = getSubtleCrypto()
if (!subtle) {
return toHex(hmacSha256Bytes(secret, message))
}
const key = await subtle.importKey(
'raw',
toArrayBuffer(encodeUtf8(secret)),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
)
const signature = await subtle.sign('HMAC', key, toArrayBuffer(encodeUtf8(message)))
return toHex(signature)
}
const randomNonce = (deviceId: string): string => {
const cryptoObject = globalThis.crypto
if (typeof cryptoObject?.getRandomValues === 'function') {
const randomPart = cryptoObject.getRandomValues(new Uint32Array(2))
const [first = 0, second = 0] = randomPart
return `${Date.now()}-${deviceId}-${first.toString(36)}${second.toString(36)}`
}
return `${Date.now()}-${deviceId}-${Math.random().toString(36).slice(2, 12)}`
}
const getDeviceId = (): string => {
const existing = window.localStorage.getItem(DEVICE_ID_STORAGE_KEY)
if (existing) {
return existing
}
const cryptoObject = globalThis.crypto
const generated = typeof cryptoObject?.randomUUID === 'function'
? cryptoObject.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2)}`
window.localStorage.setItem(DEVICE_ID_STORAGE_KEY, generated)
return generated
}
const setHeader = (headers: HeaderContainer, key: string, value: string): void => {
headers[key] = value
}
const extractPath = (value: string): string => {
const target = String(value || '')
if (!target) {
return '/'
}
if (/^[a-z][a-z\d+\-.]*:\/\//i.test(target)) {
const parsed = new URL(target)
return parsed.pathname || '/'
}
return target.split('?')[0] || '/'
}
const toBackendRequestPath = (config: InternalAxiosRequestConfig): string => {
const baseURL = String(config.baseURL || '')
const url = String(config.url || '')
const basePath = extractPath(baseURL).replace(/\/+$/, '')
const urlPath = extractPath(url)
const path = `${basePath}${urlPath.startsWith('/') ? urlPath : `/${urlPath}`}`
.replace(/^\/admin\/api/, '/admin')
if (path === '/api') {
return '/'
}
if (path.startsWith('/api/')) {
return `/${path.slice('/api/'.length)}`
}
return path
}
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(values)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, value]) => `${key}=${value.sort().join(',')}`)
.join('&')
}
const buildJsonPayload = (data: unknown): string => {
if (data === undefined || data === null || data === '' || data instanceof FormData) {
return ''
}
if (typeof data === 'string') {
return data
}
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,
options: RequestSignatureOptions
): Promise<InternalAxiosRequestConfig> => {
config.headers = config.headers || {}
const headers = config.headers as HeaderContainer
const deviceId = getDeviceId()
setHeader(headers, DEVICE_ID_HEADER, deviceId)
const method = String(config.method || 'GET').toUpperCase()
if (options.authFree || !accessToken || isSafeMethod(method)) {
return config
}
const timestamp = String(Date.now())
const nonce = randomNonce(deviceId)
const payload = resolvePayload(config, headers)
const canonical = [
method,
toBackendRequestPath(config),
timestamp,
nonce,
await sha256Hex(payload)
].join('\n')
setHeader(headers, HEADER_TIMESTAMP, timestamp)
setHeader(headers, HEADER_NONCE, nonce)
setHeader(headers, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION)
setHeader(headers, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical))
return config
}