All files / src/lib http-client.ts

100% Statements 36/36
100% Branches 34/34
100% Functions 12/12
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127                          74x 74x 74x 74x                 56x                                       53x     11x       7x 4x   11x     11x         53x         53x 53x 53x                 535x 424x   111x 111x       523x   523x                     517x 8x 8x 1x       516x 523x   523x 56x 56x     460x     53x 423x   47x   34x 18x    
import { config } from './config'
import { readCookie } from './cookies'
 
export interface ApiErrorBody {
  status: 'error'
  message: string
}
 
export class ApiError extends Error {
  readonly status: number
  readonly body: ApiErrorBody | undefined
 
  constructor(status: number, body: ApiErrorBody | undefined, message: string) {
    super(message)
    this.name = 'ApiError'
    this.status = status
    this.body = body
  }
}
 
interface RequestOptions extends Omit<RequestInit, 'body'> {
  body?: unknown
}
 
function isApiErrorBody(value: unknown): value is ApiErrorBody {
  return (
    typeof value === 'object' &&
    value !== null &&
    'status' in value &&
    'message' in value &&
    (value as { status: unknown }).status === 'error'
  )
}
 
/**
 * The backend does not track refresh sessions server-side beyond the cookie
 * itself, so "refreshing" is just: call /auth/refresh once, let the browser
 * store the rotated cookies, and retry the original request. Concurrent 401s
 * (e.g. several queries firing at once) share one in-flight refresh instead
 * of each triggering their own POST /auth/refresh.
 *
 * Exported so non-JSON callers (e.g. lib/upload.ts) can apply the same
 * single-refresh-then-retry behavior instead of duplicating it — this
 * behavior must live in exactly one place.
 */
let refreshPromise: Promise<boolean> | null = null
 
export function refreshSession(): Promise<boolean> {
  refreshPromise ??= fetch(`${config.apiBaseUrl}/auth/refresh`, {
    method: 'POST',
    credentials: 'include',
  })
    .then((response) => response.ok)
    .catch(() => false)
    .finally(() => {
      refreshPromise = null
    })
 
  return refreshPromise
}
 
// A 401 from these is never a stale-access-token situation, so retrying them
// after a silent refresh would be meaningless (or, for /auth/refresh itself, recursive).
const SESSION_REFRESH_EXEMPT_PATHS = new Set(['/auth/login', '/auth/refresh'])
 
// Double-submit CSRF scheme: the backend sets a non-HttpOnly `csrf_token`
// cookie readable by JS, and expects it echoed back as this header on any
// request that mutates state. GET requests are exempt (safe/idempotent).
const CSRF_COOKIE_NAME = 'csrf_token'
const CSRF_HEADER_NAME = 'X-CSRF-Token'
const MUTATING_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE'])
 
/**
 * Exported so non-JSON callers (e.g. lib/upload.ts's multipart/form-data
 * POST) can attach the same CSRF header without duplicating the
 * cookie-reading logic — those requests bypass `request()` entirely because
 * it always JSON-stringifies its body and sets `Content-Type: application/json`.
 */
export function csrfHeaders(method: string | undefined): Record<string, string> {
  if (!method || !MUTATING_METHODS.has(method.toUpperCase())) {
    return {}
  }
  const token = readCookie(CSRF_COOKIE_NAME)
  return token ? { [CSRF_HEADER_NAME]: token } : {}
}
 
async function request<T>(path: string, options: RequestOptions = {}, isRetry = false): Promise<T> {
  const { body, headers, ...rest } = options
 
  const response = await fetch(`${config.apiBaseUrl}${path}`, {
    ...rest,
    credentials: 'include',
    headers: {
      ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
      ...csrfHeaders(rest.method),
      ...headers,
    },
    body: body !== undefined ? JSON.stringify(body) : undefined,
  })
 
  if (response.status === 401 && !isRetry && !SESSION_REFRESH_EXEMPT_PATHS.has(path)) {
    const refreshed = await refreshSession()
    if (refreshed) {
      return request<T>(path, options, true)
    }
  }
 
  const isJson = response.headers.get('content-type')?.includes('application/json') ?? false
  const data: unknown = isJson ? await response.json() : undefined
 
  if (!response.ok) {
    const errorBody = isApiErrorBody(data) ? data : undefined
    throw new ApiError(response.status, errorBody, errorBody?.message ?? response.statusText)
  }
 
  return data as T
}
 
export const httpClient = {
  get: <T>(path: string, options?: RequestOptions) => request<T>(path, { ...options, method: 'GET' }),
  post: <T>(path: string, body?: unknown, options?: RequestOptions) =>
    request<T>(path, { ...options, method: 'POST', body }),
  patch: <T>(path: string, body?: unknown, options?: RequestOptions) =>
    request<T>(path, { ...options, method: 'PATCH', body }),
  delete: <T>(path: string, options?: RequestOptions) => request<T>(path, { ...options, method: 'DELETE' }),
}