Files
JayuCloud/JC-Salon-Frontend/src/utils/request-signature.ts
T

475 lines
18 KiB
TypeScript

import type { InternalAxiosRequestConfig } from 'axios'
/**
* Purpose: HEADER_TIMESTAMP supports request-signature.ts 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'
/**
* Purpose: HEADER_NONCE supports request-signature.ts 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'
/**
* Purpose: HEADER_SIGNATURE supports request-signature.ts 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'
/**
* Purpose: HEADER_SIGNATURE_VERSION supports request-signature.ts 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'
/**
* Purpose: DEVICE_ID_HEADER supports request-signature.ts 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'
/**
* Purpose: DEVICE_ID_STORAGE_KEY supports request-signature.ts by holding or executing the device id storage key 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_STORAGE_KEY = 'fingertipdesigner-device-id'
/**
* Purpose: SIGNATURE_VERSION supports request-signature.ts by holding or executing the 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 SIGNATURE_VERSION = 'v1'
/**
* Purpose: HeaderContainer supports request-signature.ts by holding or executing the header container page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
type HeaderContainer = Record<string, unknown> & {
set?: (name: string, value: string) => void
get?: (name: string) => unknown
}
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
])
/**
* Purpose: RequestSignatureOptions supports request-signature.ts by holding or executing the request signature options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface RequestSignatureOptions {
authFree?: boolean
}
/**
* Purpose: isSafeMethod supports request-signature.ts 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?: string) {
return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase())
}
/**
* Purpose: toHex supports request-signature.ts by holding or executing the to hex 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 toHex(bytes: ArrayBuffer | Uint8Array) {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
return Array.from(view)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('')
}
function encodeUtf8(text: string) {
return new TextEncoder().encode(text)
}
function rightRotate(value: number, bits: number) {
return (value >>> bits) | (value << (32 - bits))
}
function concatBytes(left: Uint8Array, right: Uint8Array) {
const result = new Uint8Array(left.length + right.length)
result.set(left, 0)
result.set(right, left.length)
return result
}
function sha256Bytes(input: 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
}
function hmacSha256Bytes(secret: string, message: string) {
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)))))
}
function getSubtleCrypto() {
return globalThis.crypto?.subtle
}
/**
* Purpose: sha256Hex supports request-signature.ts by holding or executing the sha256 hex 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 sha256Hex(text: string) {
const subtle = getSubtleCrypto()
if (!subtle) {
return toHex(sha256Bytes(encodeUtf8(text)))
}
const digest = await subtle.digest('SHA-256', encodeUtf8(text))
return toHex(digest)
}
/**
* Purpose: hmacSha256Hex supports request-signature.ts by holding or executing the hmac sha256 hex 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 hmacSha256Hex(secret: string, message: string) {
const subtle = getSubtleCrypto()
if (!subtle) {
return toHex(hmacSha256Bytes(secret, message))
}
const key = await subtle.importKey(
'raw',
encodeUtf8(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
)
const signature = await subtle.sign('HMAC', key, encodeUtf8(message))
return toHex(signature)
}
/**
* Purpose: randomNonce supports request-signature.ts by holding or executing the random nonce 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 randomNonce() {
if (typeof globalThis.crypto?.randomUUID === 'function') {
return `${Date.now()}-${globalThis.crypto.randomUUID()}`
}
return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`
}
/**
* Purpose: getDeviceId supports request-signature.ts by holding or executing the get device id 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.
*/
export function getDeviceId() {
try {
const stored = localStorage.getItem(DEVICE_ID_STORAGE_KEY)
if (stored) {
return stored
}
const next = `web-${randomNonce()}`
localStorage.setItem(DEVICE_ID_STORAGE_KEY, next)
return next
} catch {
return `web-${randomNonce()}`
}
}
/**
* Purpose: setHeader supports request-signature.ts by holding or executing the set header 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 setHeader(config: InternalAxiosRequestConfig, name: string, value: string) {
const headers = config.headers as HeaderContainer | undefined
if (headers && typeof headers.set === 'function') {
headers.set(name, value)
return
}
config.headers = {
...(headers || {}),
[name]: value
} as InternalAxiosRequestConfig['headers']
}
/**
* Purpose: getHeader supports request-signature.ts by holding or executing the get header 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 getHeader(config: InternalAxiosRequestConfig, name: string) {
const headers = config.headers as HeaderContainer | undefined
if (!headers) {
return ''
}
if (typeof headers.get === 'function') {
const value = headers.get(name)
if (value !== undefined && value !== null) {
return String(value)
}
}
return String(headers[name] || headers[name.toLowerCase()] || '')
}
/**
* Purpose: extractPath supports request-signature.ts 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?: string) {
if (!value) {
return ''
}
try {
return new URL(value, window.location.origin).pathname
} catch {
return value.split('?')[0] || ''
}
}
/**
* Purpose: joinAxiosPath supports request-signature.ts by holding or executing the join axios 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 joinAxiosPath(baseUrl?: string, requestUrl?: string) {
if (requestUrl && /^[a-z][a-z\d+\-.]*:\/\//i.test(requestUrl)) {
return extractPath(requestUrl)
}
const basePath = extractPath(baseUrl).replace(/^\/+|\/+$/g, '')
const requestPath = extractPath(requestUrl).replace(/^\/+|\/+$/g, '')
const joined = [basePath, requestPath].filter(Boolean).join('/')
return joined ? `/${joined}` : '/'
}
/**
* Purpose: toBackendRequestPath supports request-signature.ts 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(baseUrl?: string, requestUrl?: string) {
const path = joinAxiosPath(baseUrl, requestUrl)
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 === '/api') {
return '/'
}
if (path.startsWith('/api/')) {
return `/${path.slice('/api/'.length)}`
}
return path
}
/**
* Purpose: appendParam supports request-signature.ts by holding or executing the append param 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 appendParam(target: Record<string, unknown[]>, key: string, value: unknown) {
if (value === undefined || value === null || value === '') {
return
}
if (!target[key]) {
target[key] = []
}
if (Array.isArray(value)) {
value.forEach(item => appendParam(target, key, item))
return
}
target[key].push(value)
}
/**
* Purpose: collectParams supports request-signature.ts by holding or executing the collect params 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 collectParams(source: unknown, target: Record<string, unknown[]>) {
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))
}
}
/**
* Purpose: buildCanonicalParams supports request-signature.ts by holding or executing the build canonical params 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 buildCanonicalParams(...sources: unknown[]) {
const params: Record<string, unknown[]> = {}
sources.forEach(source => collectParams(source, params))
return Object.keys(params)
.sort()
.map(key => {
const normalized = params[key]
?.map(value => String(value))
.sort()
.join(',') || ''
return `${key}=${normalized}`
})
.join('&')
}
/**
* Purpose: buildJsonPayload supports request-signature.ts by holding or executing the build json payload 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 buildJsonPayload(data: unknown) {
if (data === undefined || data === null || data === '') {
return ''
}
if (typeof data === 'string') {
return data
}
return JSON.stringify(data)
}
/**
* Purpose: resolvePayload supports request-signature.ts by holding or executing the resolve payload 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 resolvePayload(config: InternalAxiosRequestConfig) {
const contentType = getHeader(config, 'Content-Type').toLowerCase()
const jsonPayload = contentType.includes('application/json') ? buildJsonPayload(config.data) : ''
if (jsonPayload) {
return jsonPayload
}
return buildCanonicalParams(config.params, config.data)
}
/**
* Purpose: attachRequestSignature supports request-signature.ts by holding or executing the attach request signature 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.
*/
export async function attachRequestSignature(
config: InternalAxiosRequestConfig,
accessToken?: string | null,
options: RequestSignatureOptions = {}
) {
setHeader(config, DEVICE_ID_HEADER, getDeviceId())
const method = String(config.method || 'GET').toUpperCase()
if (!accessToken || options.authFree || isSafeMethod(method)) {
return config
}
const timestamp = String(Date.now())
const nonce = randomNonce()
const payloadHash = await sha256Hex(resolvePayload(config))
const canonical = [
method,
toBackendRequestPath(config.baseURL, config.url),
timestamp,
nonce,
payloadHash
].join('\n')
setHeader(config, HEADER_TIMESTAMP, timestamp)
setHeader(config, HEADER_NONCE, nonce)
setHeader(config, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical))
setHeader(config, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION)
return config
}