237 lines
6.4 KiB
TypeScript
237 lines
6.4 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 = 'yuminail-device-id'
|
||
|
|
const SIGNATURE_VERSION = 'v1'
|
||
|
|
|
||
|
|
type HeaderContainer = Record<string, unknown> & {
|
||
|
|
set?: (name: string, value: string) => void
|
||
|
|
get?: (name: string) => unknown
|
||
|
|
}
|
||
|
|
|
||
|
|
interface RequestSignatureOptions {
|
||
|
|
authFree?: boolean
|
||
|
|
}
|
||
|
|
|
||
|
|
function isSafeMethod(method?: string) {
|
||
|
|
return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase())
|
||
|
|
}
|
||
|
|
|
||
|
|
function toHex(bytes: ArrayBuffer) {
|
||
|
|
return Array.from(new Uint8Array(bytes))
|
||
|
|
.map(byte => byte.toString(16).padStart(2, '0'))
|
||
|
|
.join('')
|
||
|
|
}
|
||
|
|
|
||
|
|
async function sha256Hex(text: string) {
|
||
|
|
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
|
||
|
|
return toHex(digest)
|
||
|
|
}
|
||
|
|
|
||
|
|
async function hmacSha256Hex(secret: string, message: 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)
|
||
|
|
}
|
||
|
|
|
||
|
|
function randomNonce() {
|
||
|
|
if (typeof crypto.randomUUID === 'function') {
|
||
|
|
return `${Date.now()}-${crypto.randomUUID()}`
|
||
|
|
}
|
||
|
|
return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`
|
||
|
|
}
|
||
|
|
|
||
|
|
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()}`
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
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']
|
||
|
|
}
|
||
|
|
|
||
|
|
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()] || '')
|
||
|
|
}
|
||
|
|
|
||
|
|
function extractPath(value?: string) {
|
||
|
|
if (!value) {
|
||
|
|
return ''
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
return new URL(value, window.location.origin).pathname
|
||
|
|
} catch {
|
||
|
|
return value.split('?')[0] || ''
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
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}` : '/'
|
||
|
|
}
|
||
|
|
|
||
|
|
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
|
||
|
|
}
|
||
|
|
|
||
|
|
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)
|
||
|
|
}
|
||
|
|
|
||
|
|
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))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
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('&')
|
||
|
|
}
|
||
|
|
|
||
|
|
function buildJsonPayload(data: unknown) {
|
||
|
|
if (data === undefined || data === null || data === '') {
|
||
|
|
return ''
|
||
|
|
}
|
||
|
|
if (typeof data === 'string') {
|
||
|
|
return data
|
||
|
|
}
|
||
|
|
return JSON.stringify(data)
|
||
|
|
}
|
||
|
|
|
||
|
|
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)
|
||
|
|
}
|
||
|
|
|
||
|
|
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
|
||
|
|
}
|