统一甲屿云命名体系
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
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 isSafeMethod = (method: string): boolean => ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())
|
||||
|
||||
const toHex = (bytes: ArrayBuffer): string => {
|
||||
return Array.from(new Uint8Array(bytes)).map(value => value.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
const sha256Hex = async (message: string): Promise<string> => {
|
||||
const bytes = new TextEncoder().encode(message)
|
||||
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
||||
return toHex(digest)
|
||||
}
|
||||
|
||||
const hmacSha256Hex = async (secret: string, message: string): Promise<string> => {
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message))
|
||||
return toHex(signature)
|
||||
}
|
||||
|
||||
const randomNonce = (deviceId: string): string => {
|
||||
const randomPart = crypto.getRandomValues(new Uint32Array(2))
|
||||
const [first = 0, second = 0] = randomPart
|
||||
return `${Date.now()}-${deviceId}-${first.toString(36)}${second.toString(36)}`
|
||||
}
|
||||
|
||||
const getDeviceId = (): string => {
|
||||
const existing = window.localStorage.getItem(DEVICE_ID_STORAGE_KEY)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const generated = crypto.randomUUID ? crypto.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)
|
||||
return `${basePath}${urlPath.startsWith('/') ? urlPath : `/${urlPath}`}`.replace(/^\/admin\/api/, '/admin')
|
||||
}
|
||||
|
||||
const buildCanonicalParams = (params: unknown): string => {
|
||||
if (!params || typeof params !== 'object') {
|
||||
return ''
|
||||
}
|
||||
return Object.entries(params as Record<string, unknown>)
|
||||
.filter(([, value]) => value !== undefined && value !== null && value !== '')
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
|
||||
.join('&')
|
||||
}
|
||||
|
||||
const buildJsonPayload = (data: unknown): string => {
|
||||
if (data === undefined || data === null || data instanceof FormData) {
|
||||
return ''
|
||||
}
|
||||
if (typeof data === 'string') {
|
||||
return data
|
||||
}
|
||||
return JSON.stringify(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 = buildJsonPayload(config.data)
|
||||
const canonical = [
|
||||
method,
|
||||
toBackendRequestPath(config),
|
||||
buildCanonicalParams(config.params),
|
||||
await sha256Hex(payload),
|
||||
timestamp,
|
||||
nonce
|
||||
].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
|
||||
}
|
||||
Reference in New Issue
Block a user