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 = 'yuminail-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 & { set?: (name: string, value: string) => void get?: (name: string) => unknown } /** * 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) { return Array.from(new Uint8Array(bytes)) .map(byte => byte.toString(16).padStart(2, '0')) .join('') } /** * 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 digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(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 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) } /** * 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 crypto.randomUUID === 'function') { return `${Date.now()}-${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, 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) { 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).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 = {} 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 }