client.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import type { JsonValue } from '@shared/types'
  2. import { bool, normalizeUser, record, string } from '@/utils/normalize'
  3. export class ApiError extends Error {
  4. readonly status: number
  5. readonly code?: string
  6. readonly details?: JsonValue
  7. constructor(message: string, status = 0, code?: string, details?: JsonValue) {
  8. super(message)
  9. this.name = 'ApiError'
  10. this.status = status
  11. this.code = code
  12. this.details = details
  13. }
  14. }
  15. let csrfToken = ''
  16. let csrfAccountId: string | null | undefined
  17. let securityGeneration = 0
  18. let csrfRefresh: { generation: number; promise: Promise<void> } | undefined
  19. const unauthorizedListeners = new Set<() => void>()
  20. const securityChannel = typeof window !== 'undefined' && typeof window.BroadcastChannel !== 'undefined'
  21. ? new window.BroadcastChannel('hermes-yaoyao-security')
  22. : undefined
  23. securityChannel?.addEventListener('message', event => {
  24. // Another window shares cookies, but may now belong to another account.
  25. // Revalidate that identity before using its token for a pending action.
  26. if (typeof event.data === 'string' && event.data !== csrfToken) csrfToken = ''
  27. })
  28. export function setApiCsrfToken(token?: string | null, accountId?: string | null): void {
  29. if (accountId !== undefined) {
  30. if (csrfAccountId !== undefined && csrfAccountId !== accountId) securityGeneration += 1
  31. csrfAccountId = accountId
  32. }
  33. csrfToken = token?.trim() ?? ''
  34. securityChannel?.postMessage(csrfToken)
  35. }
  36. export function clearApiSecurityContext(): void {
  37. securityGeneration += 1
  38. csrfToken = ''
  39. csrfAccountId = undefined
  40. csrfRefresh = undefined
  41. }
  42. function requireSecurityGeneration(generation: number): void {
  43. if (generation !== securityGeneration) throw new ApiError('登录状态已变化,请重新操作', 0, 'SECURITY_CONTEXT_CHANGED')
  44. }
  45. function refreshCsrfToken(rejectedToken: string): Promise<void> {
  46. if (csrfToken && csrfToken !== rejectedToken) return Promise.resolve()
  47. const generation = securityGeneration, accountId = csrfAccountId
  48. if (csrfRefresh?.generation === generation) return csrfRefresh.promise
  49. const renew = async () => {
  50. requireSecurityGeneration(generation)
  51. const payload = await apiRequest<unknown>('/api/app/bootstrap?csrfOnly=1', {
  52. csrf: false, notifyUnauthorized: false, timeoutMs: 10_000,
  53. })
  54. requireSecurityGeneration(generation)
  55. const root = record(unwrapData(payload)), status = record(root.status)
  56. const user = root.user ?? root.identity
  57. const token = string(root.csrfToken ?? root.csrf_token ?? root.csrf).trim()
  58. const authRequired = root.authRequired ?? root.auth_required ?? status.authRequired ?? status.auth_required
  59. if (!token || (!('userId' in root) && !user && authRequired === undefined)
  60. || ('userId' in root && root.userId !== null && typeof root.userId !== 'string'))
  61. throw new ApiError('无法更新安全令牌,请稍后重试', 0, 'CSRF_REFRESH_FAILED')
  62. // Older servers ignore csrfOnly and return a complete bootstrap response.
  63. const currentAccount = 'userId' in root ? (typeof root.userId === 'string' ? root.userId : null)
  64. : user ? normalizeUser(user).id
  65. : bool(authRequired) ? null : 'local'
  66. if (accountId !== undefined && currentAccount !== accountId) {
  67. clearApiSecurityContext()
  68. for (const listener of unauthorizedListeners) listener()
  69. throw new ApiError('登录账号已变化,请重新登录后操作', 401, 'SECURITY_CONTEXT_CHANGED')
  70. }
  71. setApiCsrfToken(token, currentAccount)
  72. }
  73. // Cookie issuance must also be serialized across windows when supported;
  74. // otherwise two expired-cookie responses can replace one another's token.
  75. const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined
  76. const promise = (locks ? locks.request('hermes-yaoyao-csrf-refresh', renew) : renew())
  77. .finally(() => { if (csrfRefresh?.promise === promise) csrfRefresh = undefined })
  78. csrfRefresh = { generation, promise }
  79. return promise
  80. }
  81. function waitForCsrfRefresh(promise: Promise<void>, signal: AbortSignal): Promise<void> {
  82. return new Promise((resolve, reject) => {
  83. const abort = () => { cleanup(); reject(new DOMException('Request aborted', 'AbortError')) }
  84. const cleanup = () => signal.removeEventListener('abort', abort)
  85. signal.addEventListener('abort', abort, { once: true })
  86. promise.then(() => { cleanup(); resolve() }, error => { cleanup(); reject(error) })
  87. if (signal.aborted) abort()
  88. })
  89. }
  90. export function onApiUnauthorized(listener: () => void): () => void {
  91. unauthorizedListeners.add(listener)
  92. return () => unauthorizedListeners.delete(listener)
  93. }
  94. export interface ApiRequestOptions extends Omit<RequestInit, 'body'> {
  95. body?: JsonValue | FormData | Blob
  96. csrf?: boolean
  97. timeoutMs?: number
  98. notifyUnauthorized?: boolean
  99. }
  100. function isBodyInit(value: ApiRequestOptions['body']): value is FormData | Blob {
  101. return (typeof FormData !== 'undefined' && value instanceof FormData)
  102. || (typeof Blob !== 'undefined' && value instanceof Blob)
  103. }
  104. function errorMessage(payload: unknown, fallback: string): string {
  105. if (payload && typeof payload === 'object') {
  106. const record = payload as Record<string, unknown>
  107. const nested = record.error && typeof record.error === 'object'
  108. ? record.error as Record<string, unknown>
  109. : undefined
  110. for (const candidate of [record.message, record.error, nested?.message, record.detail]) {
  111. if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()
  112. }
  113. if (Array.isArray(record.detail)) {
  114. const validation = record.detail.find(item => item && typeof item === 'object') as Record<string, unknown> | undefined
  115. if (validation && typeof validation.msg === 'string' && validation.msg.trim()) {
  116. const location = Array.isArray(validation.loc)
  117. ? validation.loc.filter(item => typeof item === 'string' || typeof item === 'number').join('.')
  118. : ''
  119. return location ? `${location}:${validation.msg.trim()}` : validation.msg.trim()
  120. }
  121. }
  122. }
  123. if (typeof payload === 'string' && payload.trim()) return payload.trim()
  124. return fallback
  125. }
  126. export async function apiRequest<T>(path: string, options: ApiRequestOptions = {}): Promise<T> {
  127. if (!path.startsWith('/api/app/')) throw new ApiError('客户端仅允许访问应用接口', 0, 'INVALID_PATH')
  128. const method = (options.method ?? 'GET').toUpperCase()
  129. const requiresCsrf = options.csrf !== false && !['GET', 'HEAD', 'OPTIONS'].includes(method)
  130. const generation = securityGeneration
  131. const headers = new Headers(options.headers)
  132. headers.set('Accept', 'application/json')
  133. let body: BodyInit | undefined
  134. if (options.body !== undefined) {
  135. if (isBodyInit(options.body)) {
  136. if (typeof FormData !== 'undefined' && options.body instanceof FormData) {
  137. const snapshot = new FormData()
  138. options.body.forEach((value, key) => snapshot.append(key, value))
  139. body = snapshot
  140. } else body = options.body
  141. } else {
  142. headers.set('Content-Type', 'application/json')
  143. body = JSON.stringify(options.body)
  144. }
  145. }
  146. const controller = new AbortController()
  147. const timeout = window.setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000)
  148. const abort = () => controller.abort(options.signal?.reason)
  149. options.signal?.addEventListener('abort', abort, { once: true })
  150. if (options.signal?.aborted) abort()
  151. try {
  152. if (controller.signal.aborted) throw new DOMException('Request aborted', 'AbortError')
  153. if (requiresCsrf && !csrfToken) await waitForCsrfRefresh(refreshCsrfToken(''), controller.signal)
  154. for (let attempt = 0; attempt < 2; attempt += 1) {
  155. const requestHeaders = new Headers(headers)
  156. if (controller.signal.aborted) throw new DOMException('Request aborted', 'AbortError')
  157. if (requiresCsrf) {
  158. requireSecurityGeneration(generation)
  159. requestHeaders.set('X-CSRF-Token', csrfToken)
  160. }
  161. const sentToken = requestHeaders.get('X-CSRF-Token') ?? ''
  162. const response = await fetch(path, {
  163. ...options,
  164. method,
  165. headers: requestHeaders,
  166. body,
  167. credentials: 'include',
  168. cache: 'no-store',
  169. signal: controller.signal,
  170. })
  171. const contentType = response.headers.get('content-type') ?? ''
  172. const payload = response.status === 204
  173. ? undefined
  174. : contentType.includes('application/json')
  175. ? await response.json().catch(() => undefined)
  176. : await response.text().catch(() => undefined)
  177. if (!response.ok) {
  178. const record = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined
  179. const code = typeof record?.code === 'string' ? record.code : undefined
  180. if (requiresCsrf && attempt === 0 && response.status === 403 && code === 'invalid_csrf') {
  181. requireSecurityGeneration(generation)
  182. // This explicit rejection occurs before the server executes the action.
  183. // Preserve the original body and idempotency key; never retry timeouts.
  184. await waitForCsrfRefresh(refreshCsrfToken(sentToken), controller.signal)
  185. continue
  186. }
  187. if (response.status === 401
  188. && generation === securityGeneration
  189. && options.notifyUnauthorized !== false) {
  190. // A response from before logout/account switching cannot expire a new login.
  191. for (const listener of unauthorizedListeners) listener()
  192. }
  193. throw new ApiError(
  194. errorMessage(payload, `请求失败(${response.status})`),
  195. response.status,
  196. code,
  197. payload as JsonValue,
  198. )
  199. }
  200. return payload as T
  201. }
  202. throw new ApiError('安全令牌校验失败,请稍后重试', 403, 'invalid_csrf')
  203. } catch (error) {
  204. if (error instanceof ApiError) throw error
  205. if (controller.signal.aborted) throw new ApiError('请求已取消或超时', 0, 'REQUEST_ABORTED')
  206. throw new ApiError(error instanceof Error ? error.message : '网络请求失败', 0, 'NETWORK_ERROR')
  207. } finally {
  208. window.clearTimeout(timeout)
  209. options.signal?.removeEventListener('abort', abort)
  210. }
  211. }
  212. export function apiUrl(path: string, query: Record<string, string | number | boolean | null | undefined> = {}): string {
  213. const params = new URLSearchParams()
  214. for (const [key, value] of Object.entries(query)) {
  215. if (value !== undefined && value !== null && value !== '') params.set(key, String(value))
  216. }
  217. const encoded = params.toString()
  218. return encoded ? `${path}?${encoded}` : path
  219. }
  220. export function unwrapData<T>(payload: T | { data: T }): T {
  221. return payload && typeof payload === 'object' && 'data' in payload
  222. ? (payload as { data: T }).data
  223. : payload as T
  224. }