api.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. // API client for stable-diffusion REST API
  2. // Type for server config injected by the server
  3. declare global {
  4. interface Window {
  5. __SERVER_CONFIG__?: {
  6. apiUrl: string;
  7. apiBasePath: string;
  8. host: string;
  9. port: number;
  10. authMethod: 'none' | 'unix' | 'jwt';
  11. authEnabled: boolean;
  12. };
  13. }
  14. }
  15. // Request throttling to prevent excessive API calls
  16. class RequestThrottler {
  17. private requests: Map<string, { count: number; resetTime: number }> = new Map();
  18. private maxRequests: number = 10; // Max requests per time window
  19. private timeWindow: number = 1000; // Time window in milliseconds
  20. canMakeRequest(key: string): boolean {
  21. const now = Date.now();
  22. const request = this.requests.get(key);
  23. if (!request || now >= request.resetTime) {
  24. this.requests.set(key, { count: 1, resetTime: now + this.timeWindow });
  25. return true;
  26. }
  27. if (request.count >= this.maxRequests) {
  28. return false;
  29. }
  30. request.count++;
  31. return true;
  32. }
  33. getWaitTime(key: string): number {
  34. const request = this.requests.get(key);
  35. if (!request) return 0;
  36. const now = Date.now();
  37. if (now >= request.resetTime) return 0;
  38. return request.resetTime - now;
  39. }
  40. }
  41. // Global throttler instance
  42. const throttler = new RequestThrottler();
  43. // Debounce utility for frequent calls
  44. function debounce<T extends (...args: any[]) => any>(
  45. func: T,
  46. wait: number,
  47. immediate?: boolean
  48. ): (...args: Parameters<T>) => void {
  49. let timeout: NodeJS.Timeout | null = null;
  50. return function executedFunction(...args: Parameters<T>) {
  51. const later = () => {
  52. timeout = null;
  53. if (!immediate) func(...args);
  54. };
  55. const callNow = immediate && !timeout;
  56. if (timeout) clearTimeout(timeout);
  57. timeout = setTimeout(later, wait);
  58. if (callNow) func(...args);
  59. };
  60. }
  61. // Cache for API responses to reduce redundant calls
  62. class ApiCache {
  63. private cache: Map<string, { data: any; timestamp: number; ttl: number }> = new Map();
  64. private defaultTtl: number = 5000; // 5 seconds default TTL
  65. set(key: string, data: any, ttl?: number): void {
  66. this.cache.set(key, {
  67. data,
  68. timestamp: Date.now(),
  69. ttl: ttl || this.defaultTtl
  70. });
  71. }
  72. get(key: string): any | null {
  73. const cached = this.cache.get(key);
  74. if (!cached) return null;
  75. if (Date.now() - cached.timestamp > cached.ttl) {
  76. this.cache.delete(key);
  77. return null;
  78. }
  79. return cached.data;
  80. }
  81. clear(): void {
  82. this.cache.clear();
  83. }
  84. delete(key: string): void {
  85. this.cache.delete(key);
  86. }
  87. }
  88. const cache = new ApiCache();
  89. // Get configuration from server-injected config or fallback to environment/defaults
  90. // This function is called at runtime to ensure __SERVER_CONFIG__ is available
  91. function getApiConfig() {
  92. if (typeof window !== 'undefined' && window.__SERVER_CONFIG__) {
  93. return {
  94. apiUrl: window.__SERVER_CONFIG__.apiUrl,
  95. apiBase: window.__SERVER_CONFIG__.apiBasePath,
  96. };
  97. }
  98. // Fallback for development mode - use current window location
  99. if (typeof window !== 'undefined') {
  100. const protocol = window.location.protocol;
  101. const host = window.location.hostname;
  102. const port = window.location.port;
  103. return {
  104. apiUrl: `${protocol}//${host}:${port}`,
  105. apiBase: '/api',
  106. };
  107. }
  108. // Server-side fallback
  109. return {
  110. apiUrl: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8081',
  111. apiBase: process.env.NEXT_PUBLIC_API_BASE_PATH || '/api',
  112. };
  113. }
  114. export interface GenerationRequest {
  115. model?: string;
  116. prompt: string;
  117. negative_prompt?: string;
  118. width?: number;
  119. height?: number;
  120. steps?: number;
  121. cfg_scale?: number;
  122. seed?: string;
  123. sampling_method?: string;
  124. scheduler?: string;
  125. batch_count?: number;
  126. clip_skip?: number;
  127. strength?: number;
  128. control_strength?: number;
  129. }
  130. export interface JobInfo {
  131. id?: string;
  132. request_id?: string;
  133. status: 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled' | 'queued';
  134. progress?: number;
  135. result?: {
  136. images: string[];
  137. };
  138. outputs?: Array<{
  139. filename: string;
  140. url: string;
  141. path: string;
  142. }>;
  143. error?: string;
  144. created_at?: string;
  145. updated_at?: string;
  146. message?: string;
  147. queue_position?: number;
  148. }
  149. export interface ModelInfo {
  150. id?: string;
  151. name: string;
  152. path?: string;
  153. type: string;
  154. size?: number;
  155. file_size?: number;
  156. file_size_mb?: number;
  157. sha256?: string | null;
  158. sha256_short?: string | null;
  159. loaded?: boolean;
  160. }
  161. export interface QueueStatus {
  162. active_generations: number;
  163. jobs: JobInfo[];
  164. running: boolean;
  165. size: number;
  166. }
  167. export interface HealthStatus {
  168. status: 'ok' | 'error' | 'degraded';
  169. message: string;
  170. timestamp: string;
  171. uptime?: number;
  172. version?: string;
  173. }
  174. class ApiClient {
  175. private baseUrl: string = '';
  176. private isInitialized: boolean = false;
  177. // Initialize base URL
  178. private initBaseUrl(): string {
  179. if (!this.isInitialized) {
  180. const config = getApiConfig();
  181. this.baseUrl = `${config.apiUrl}${config.apiBase}`;
  182. this.isInitialized = true;
  183. }
  184. return this.baseUrl;
  185. }
  186. // Get base URL dynamically at runtime to ensure server config is loaded
  187. private getBaseUrl(): string {
  188. return this.initBaseUrl();
  189. }
  190. private async request<T>(
  191. endpoint: string,
  192. options: RequestInit = {}
  193. ): Promise<T> {
  194. const url = `${this.getBaseUrl()}${endpoint}`;
  195. // Check request throttling for certain endpoints
  196. const needsThrottling = endpoint.includes('/queue/status') || endpoint.includes('/health');
  197. if (needsThrottling) {
  198. const waitTime = throttler.getWaitTime(endpoint);
  199. if (waitTime > 0) {
  200. // Wait before making the request
  201. await new Promise(resolve => setTimeout(resolve, waitTime));
  202. }
  203. if (!throttler.canMakeRequest(endpoint)) {
  204. throw new Error('Too many requests. Please wait before making another request.');
  205. }
  206. }
  207. // Get authentication method from server config
  208. const authMethod = typeof window !== 'undefined' && window.__SERVER_CONFIG__
  209. ? window.__SERVER_CONFIG__.authMethod
  210. : 'jwt';
  211. // Add auth token or Unix user header based on auth method
  212. const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;
  213. const unixUser = typeof window !== 'undefined' ? localStorage.getItem('unix_user') : null;
  214. const headers: Record<string, string> = {
  215. 'Content-Type': 'application/json',
  216. ...options.headers as Record<string, string>,
  217. };
  218. if (authMethod === 'unix' && unixUser) {
  219. // For Unix auth, send the username in X-Unix-User header
  220. headers['X-Unix-User'] = unixUser;
  221. } else if (token) {
  222. // For JWT auth, send the token in Authorization header
  223. headers['Authorization'] = `Bearer ${token}`;
  224. }
  225. const response = await fetch(url, {
  226. ...options,
  227. headers,
  228. });
  229. if (!response.ok) {
  230. const errorData = await response.json().catch(() => ({
  231. error: { message: response.statusText },
  232. }));
  233. // Handle nested error structure: { error: { message: "..." } }
  234. const errorMessage =
  235. errorData.error?.message ||
  236. errorData.message ||
  237. errorData.error ||
  238. 'API request failed';
  239. throw new Error(errorMessage);
  240. }
  241. return response.json();
  242. }
  243. // Enhanced health check with caching and better error handling
  244. async checkHealth(): Promise<HealthStatus> {
  245. const cacheKey = 'health_check';
  246. const cachedResult = cache.get(cacheKey);
  247. if (cachedResult) {
  248. return cachedResult;
  249. }
  250. const endpoints = ['/queue/status', '/health', '/status', '/'];
  251. for (const endpoint of endpoints) {
  252. try {
  253. const response = await fetch(`${this.getBaseUrl()}${endpoint}`, {
  254. method: 'GET',
  255. headers: {
  256. 'Content-Type': 'application/json',
  257. },
  258. // Add timeout to prevent hanging requests
  259. signal: AbortSignal.timeout(3000), // Reduced timeout
  260. });
  261. if (response.ok) {
  262. const data = await response.json();
  263. // For queue status, consider it healthy if it returns valid structure
  264. if (endpoint === '/queue/status' && data.queue) {
  265. const result = {
  266. status: 'ok' as const,
  267. message: 'API is running and queue is accessible',
  268. timestamp: new Date().toISOString(),
  269. };
  270. cache.set(cacheKey, result, 10000); // Cache for 10 seconds
  271. return result;
  272. }
  273. // For other health endpoints
  274. const healthStatus: HealthStatus = {
  275. status: 'ok',
  276. message: 'API is running',
  277. timestamp: new Date().toISOString(),
  278. uptime: data.uptime,
  279. version: data.version || data.build || data.git_version,
  280. };
  281. // Handle different response formats
  282. if (data.status) {
  283. if (data.status === 'healthy' || data.status === 'running' || data.status === 'ok') {
  284. healthStatus.status = 'ok';
  285. healthStatus.message = data.message || 'API is running';
  286. } else if (data.status === 'degraded') {
  287. healthStatus.status = 'degraded';
  288. healthStatus.message = data.message || 'API is running in degraded mode';
  289. } else {
  290. healthStatus.status = 'error';
  291. healthStatus.message = data.message || 'API status is unknown';
  292. }
  293. }
  294. cache.set(cacheKey, healthStatus, 10000); // Cache for 10 seconds
  295. return healthStatus;
  296. }
  297. } catch (error) {
  298. // Continue to next endpoint if this one fails
  299. console.warn(`Health check failed for endpoint ${endpoint}:`, error);
  300. continue;
  301. }
  302. }
  303. // If all endpoints fail
  304. throw new Error('All health check endpoints are unavailable');
  305. }
  306. // Alternative simple connectivity check with caching
  307. async checkConnectivity(): Promise<boolean> {
  308. const cacheKey = 'connectivity_check';
  309. const cachedResult = cache.get(cacheKey);
  310. if (cachedResult !== null) {
  311. return cachedResult;
  312. }
  313. try {
  314. const response = await fetch(`${this.getBaseUrl()}`, {
  315. method: 'HEAD',
  316. signal: AbortSignal.timeout(2000), // Reduced timeout
  317. });
  318. const result = response.ok || response.status < 500;
  319. cache.set(cacheKey, result, 5000); // Cache for 5 seconds
  320. return result;
  321. } catch (error) {
  322. cache.set(cacheKey, false, 5000); // Cache failure for 5 seconds
  323. return false;
  324. }
  325. }
  326. // Generation endpoints
  327. async generateImage(params: GenerationRequest): Promise<JobInfo> {
  328. return this.request<JobInfo>('/generate/text2img', {
  329. method: 'POST',
  330. body: JSON.stringify(params),
  331. });
  332. }
  333. async text2img(params: GenerationRequest): Promise<JobInfo> {
  334. return this.request<JobInfo>('/generate/text2img', {
  335. method: 'POST',
  336. body: JSON.stringify(params),
  337. });
  338. }
  339. async img2img(params: GenerationRequest & { image: string }): Promise<JobInfo> {
  340. // Convert frontend field name to backend field name
  341. const backendParams = {
  342. ...params,
  343. init_image: params.image,
  344. image: undefined, // Remove the frontend field
  345. };
  346. return this.request<JobInfo>('/generate/img2img', {
  347. method: 'POST',
  348. body: JSON.stringify(backendParams),
  349. });
  350. }
  351. async inpainting(params: GenerationRequest & { source_image: string; mask_image: string }): Promise<JobInfo> {
  352. return this.request<JobInfo>('/generate/inpainting', {
  353. method: 'POST',
  354. body: JSON.stringify(params),
  355. });
  356. }
  357. // Job management with caching for status checks
  358. async getJobStatus(jobId: string): Promise<JobInfo> {
  359. const cacheKey = `job_status_${jobId}`;
  360. const cachedResult = cache.get(cacheKey);
  361. if (cachedResult) {
  362. return cachedResult;
  363. }
  364. const result = await this.request<JobInfo>(`/queue/job/${jobId}`);
  365. // Cache job status for a short time
  366. if (result.status === 'processing' || result.status === 'queued') {
  367. cache.set(cacheKey, result, 2000); // Cache for 2 seconds for active jobs
  368. } else {
  369. cache.set(cacheKey, result, 10000); // Cache for 10 seconds for completed jobs
  370. }
  371. return result;
  372. }
  373. // Get authenticated image URL with cache-busting
  374. getImageUrl(jobId: string, filename: string): string {
  375. const baseUrl = this.getBaseUrl();
  376. // Add cache-busting timestamp
  377. const timestamp = Date.now();
  378. const url = `${baseUrl}/queue/job/${jobId}/output/${filename}?t=${timestamp}`;
  379. return url;
  380. }
  381. // Download image with authentication
  382. async downloadImage(jobId: string, filename: string): Promise<Blob> {
  383. const url = this.getImageUrl(jobId, filename);
  384. // Get authentication method from server config
  385. const authMethod = typeof window !== 'undefined' && window.__SERVER_CONFIG__
  386. ? window.__SERVER_CONFIG__.authMethod
  387. : 'jwt';
  388. // Add auth token or Unix user header based on auth method
  389. const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;
  390. const unixUser = typeof window !== 'undefined' ? localStorage.getItem('unix_user') : null;
  391. const headers: Record<string, string> = {};
  392. if (authMethod === 'unix' && unixUser) {
  393. // For Unix auth, send the username in X-Unix-User header
  394. headers['X-Unix-User'] = unixUser;
  395. } else if (token) {
  396. // For JWT auth, send the token in Authorization header
  397. headers['Authorization'] = `Bearer ${token}`;
  398. }
  399. const response = await fetch(url, {
  400. headers,
  401. });
  402. if (!response.ok) {
  403. const errorData = await response.json().catch(() => ({
  404. error: { message: response.statusText },
  405. }));
  406. // Handle nested error structure: { error: { message: "..." } }
  407. const errorMessage =
  408. errorData.error?.message ||
  409. errorData.message ||
  410. errorData.error ||
  411. 'Failed to download image';
  412. throw new Error(errorMessage);
  413. }
  414. return response.blob();
  415. }
  416. async cancelJob(jobId: string): Promise<void> {
  417. // Clear job status cache when cancelling
  418. cache.delete(`job_status_${jobId}`);
  419. return this.request<void>('/queue/cancel', {
  420. method: 'POST',
  421. body: JSON.stringify({ job_id: jobId }),
  422. });
  423. }
  424. // Get queue status with caching and throttling
  425. async getQueueStatus(): Promise<QueueStatus> {
  426. const cacheKey = 'queue_status';
  427. const cachedResult = cache.get(cacheKey);
  428. if (cachedResult) {
  429. return cachedResult;
  430. }
  431. const response = await this.request<{ queue: QueueStatus }>('/queue/status');
  432. // Cache queue status based on current activity
  433. const hasActiveJobs = response.queue.jobs.some(job =>
  434. job.status === 'processing' || job.status === 'queued'
  435. );
  436. // Cache for shorter time if there are active jobs
  437. const cacheTime = hasActiveJobs ? 1000 : 5000; // 1 second for active, 5 seconds for idle
  438. cache.set(cacheKey, response.queue, cacheTime);
  439. return response.queue;
  440. }
  441. async clearQueue(): Promise<void> {
  442. // Clear all related caches
  443. cache.delete('queue_status');
  444. return this.request<void>('/queue/clear', {
  445. method: 'POST',
  446. });
  447. }
  448. // Model management
  449. async getModels(type?: string, loaded?: boolean, page: number = 1, limit: number = 50, search?: string): Promise<{ models: ModelInfo[]; pagination: any; statistics: any }> {
  450. const cacheKey = `models_${type || 'all'}_${loaded ? 'loaded' : 'all'}_${page}_${limit}_${search || 'all'}`;
  451. const cachedResult = cache.get(cacheKey);
  452. if (cachedResult) {
  453. return cachedResult;
  454. }
  455. let endpoint = '/models';
  456. const params = [];
  457. if (type && type !== 'loaded') params.push(`type=${type}`);
  458. if (type === 'loaded' || loaded) params.push('loaded=true');
  459. params.push(`page=${page}`);
  460. params.push(`limit=${limit}`);
  461. if (search) params.push(`search=${encodeURIComponent(search)}`);
  462. // Add include_metadata for additional information
  463. params.push('include_metadata=true');
  464. if (params.length > 0) endpoint += '?' + params.join('&');
  465. const response = await this.request<{
  466. models: ModelInfo[];
  467. pagination: {
  468. page: number;
  469. limit: number;
  470. total_count: number;
  471. total_pages: number;
  472. has_next: boolean;
  473. has_prev: boolean
  474. };
  475. statistics: any;
  476. }>(endpoint);
  477. const models = response.models.map(model => ({
  478. ...model,
  479. id: model.sha256_short || model.name,
  480. size: model.file_size || model.size,
  481. path: model.path || model.name,
  482. }));
  483. const result = {
  484. models,
  485. pagination: response.pagination,
  486. statistics: response.statistics || {}
  487. };
  488. // Cache models for 30 seconds as they don't change frequently
  489. cache.set(cacheKey, result, 30000);
  490. return result;
  491. }
  492. // Get all models (for backward compatibility)
  493. async getAllModels(type?: string, loaded?: boolean): Promise<ModelInfo[]> {
  494. const allModels: ModelInfo[] = [];
  495. let page = 1;
  496. const limit = 100;
  497. while (true) {
  498. const response = await this.getModels(type, loaded, page, limit);
  499. allModels.push(...response.models);
  500. if (!response.pagination.has_next) {
  501. break;
  502. }
  503. page++;
  504. }
  505. return allModels;
  506. }
  507. async getModelInfo(modelId: string): Promise<ModelInfo> {
  508. const cacheKey = `model_info_${modelId}`;
  509. const cachedResult = cache.get(cacheKey);
  510. if (cachedResult) {
  511. return cachedResult;
  512. }
  513. const result = await this.request<ModelInfo>(`/models/${modelId}`);
  514. cache.set(cacheKey, result, 30000); // Cache for 30 seconds
  515. return result;
  516. }
  517. async loadModel(modelId: string): Promise<void> {
  518. // Clear model cache when loading
  519. cache.delete(`model_info_${modelId}`);
  520. return this.request<void>(`/models/${modelId}/load`, {
  521. method: 'POST',
  522. });
  523. }
  524. async unloadModel(modelId: string): Promise<void> {
  525. // Clear model cache when unloading
  526. cache.delete(`model_info_${modelId}`);
  527. return this.request<void>(`/models/${modelId}/unload`, {
  528. method: 'POST',
  529. });
  530. }
  531. async scanModels(): Promise<void> {
  532. // Clear all model caches when scanning
  533. cache.clear();
  534. return this.request<void>('/models/refresh', {
  535. method: 'POST',
  536. });
  537. }
  538. async convertModel(modelName: string, quantizationType: string, outputPath?: string): Promise<{ request_id: string; message: string }> {
  539. return this.request<{ request_id: string; message: string }>('/models/convert', {
  540. method: 'POST',
  541. body: JSON.stringify({
  542. model_name: modelName,
  543. quantization_type: quantizationType,
  544. output_path: outputPath,
  545. }),
  546. });
  547. }
  548. // System endpoints
  549. async getHealth(): Promise<{ status: string }> {
  550. return this.request<{ status: string }>('/health');
  551. }
  552. async getStatus(): Promise<any> {
  553. return this.request<any>('/status');
  554. }
  555. async getSystemInfo(): Promise<any> {
  556. return this.request<any>('/system');
  557. }
  558. async restartServer(): Promise<{ message: string }> {
  559. return this.request<{ message: string }>('/system/restart', {
  560. method: 'POST',
  561. body: JSON.stringify({}),
  562. });
  563. }
  564. // Configuration endpoints with caching
  565. async getSamplers(): Promise<Array<{ name: string; description: string; recommended_steps: number }>> {
  566. const cacheKey = 'samplers';
  567. const cachedResult = cache.get(cacheKey);
  568. if (cachedResult) {
  569. return cachedResult;
  570. }
  571. const response = await this.request<{ samplers: Array<{ name: string; description: string; recommended_steps: number }> }>('/samplers');
  572. cache.set(cacheKey, response.samplers, 60000); // Cache for 1 minute
  573. return response.samplers;
  574. }
  575. async getSchedulers(): Promise<Array<{ name: string; description: string }>> {
  576. const cacheKey = 'schedulers';
  577. const cachedResult = cache.get(cacheKey);
  578. if (cachedResult) {
  579. return cachedResult;
  580. }
  581. const response = await this.request<{ schedulers: Array<{ name: string; description: string }> }>('/schedulers');
  582. cache.set(cacheKey, response.schedulers, 60000); // Cache for 1 minute
  583. return response.schedulers;
  584. }
  585. // Cache management methods
  586. clearCache(): void {
  587. cache.clear();
  588. }
  589. clearCacheByPrefix(prefix: string): void {
  590. const keysToDelete: string[] = [];
  591. (cache as any).cache.forEach((_: any, key: string) => {
  592. if (key.startsWith(prefix)) {
  593. keysToDelete.push(key);
  594. }
  595. });
  596. keysToDelete.forEach(key => cache.delete(key));
  597. }
  598. }
  599. // Generic API request function for authentication
  600. export async function apiRequest(
  601. endpoint: string,
  602. options: RequestInit = {}
  603. ): Promise<Response> {
  604. const { apiUrl, apiBase } = getApiConfig();
  605. const url = `${apiUrl}${apiBase}${endpoint}`;
  606. // Get authentication method from server config
  607. const authMethod = typeof window !== 'undefined' && window.__SERVER_CONFIG__
  608. ? window.__SERVER_CONFIG__.authMethod
  609. : 'jwt';
  610. // Add auth token or Unix user header based on auth method
  611. const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;
  612. const unixUser = typeof window !== 'undefined' ? localStorage.getItem('unix_user') : null;
  613. const headers: Record<string, string> = {
  614. 'Content-Type': 'application/json',
  615. ...options.headers as Record<string, string>,
  616. };
  617. if (authMethod === 'unix' && unixUser) {
  618. // For Unix auth, send the username in X-Unix-User header
  619. headers['X-Unix-User'] = unixUser;
  620. } else if (token) {
  621. // For JWT auth, send the token in Authorization header
  622. headers['Authorization'] = `Bearer ${token}`;
  623. }
  624. return fetch(url, {
  625. ...options,
  626. headers,
  627. });
  628. }
  629. // Authentication API endpoints
  630. export const authApi = {
  631. async login(username: string, password?: string) {
  632. // Get authentication method from server config
  633. const authMethod = typeof window !== 'undefined' && window.__SERVER_CONFIG__
  634. ? window.__SERVER_CONFIG__.authMethod
  635. : 'jwt';
  636. // For both Unix and JWT auth, send username and password
  637. // The server will handle whether password is required based on PAM availability
  638. const response = await apiRequest('/auth/login', {
  639. method: 'POST',
  640. body: JSON.stringify({ username, password }),
  641. });
  642. if (!response.ok) {
  643. const error = await response.json().catch(() => ({ message: 'Login failed' }));
  644. throw new Error(error.message || 'Login failed');
  645. }
  646. return response.json();
  647. },
  648. async validateToken(token: string) {
  649. const response = await apiRequest('/auth/validate', {
  650. headers: { 'Authorization': `Bearer ${token}` },
  651. });
  652. if (!response.ok) {
  653. throw new Error('Token validation failed');
  654. }
  655. return response.json();
  656. },
  657. async refreshToken() {
  658. const response = await apiRequest('/auth/refresh', {
  659. method: 'POST',
  660. });
  661. if (!response.ok) {
  662. throw new Error('Token refresh failed');
  663. }
  664. return response.json();
  665. },
  666. async logout() {
  667. await apiRequest('/auth/logout', {
  668. method: 'POST',
  669. });
  670. },
  671. async getCurrentUser() {
  672. const response = await apiRequest('/auth/me');
  673. if (!response.ok) {
  674. throw new Error('Failed to get current user');
  675. }
  676. return response.json();
  677. },
  678. async changePassword(oldPassword: string, newPassword: string) {
  679. const response = await apiRequest('/auth/change-password', {
  680. method: 'POST',
  681. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }),
  682. });
  683. if (!response.ok) {
  684. const error = await response.json().catch(() => ({ message: 'Password change failed' }));
  685. throw new Error(error.message || 'Password change failed');
  686. }
  687. return response.json();
  688. },
  689. // API Key management
  690. async getApiKeys() {
  691. const response = await apiRequest('/auth/api-keys');
  692. if (!response.ok) {
  693. throw new Error('Failed to get API keys');
  694. }
  695. return response.json();
  696. },
  697. async createApiKey(name: string, scopes?: string[]) {
  698. const response = await apiRequest('/auth/api-keys', {
  699. method: 'POST',
  700. body: JSON.stringify({ name, scopes }),
  701. });
  702. if (!response.ok) {
  703. const error = await response.json().catch(() => ({ message: 'Failed to create API key' }));
  704. throw new Error(error.message || 'Failed to create API key');
  705. }
  706. return response.json();
  707. },
  708. async deleteApiKey(keyId: string) {
  709. const response = await apiRequest(`/auth/api-keys/${keyId}`, {
  710. method: 'DELETE',
  711. });
  712. if (!response.ok) {
  713. throw new Error('Failed to delete API key');
  714. }
  715. return response.json();
  716. },
  717. // User management (admin only)
  718. async getUsers() {
  719. const response = await apiRequest('/auth/users');
  720. if (!response.ok) {
  721. throw new Error('Failed to get users');
  722. }
  723. return response.json();
  724. },
  725. async createUser(userData: { username: string; email?: string; password: string; role?: string }) {
  726. const response = await apiRequest('/auth/users', {
  727. method: 'POST',
  728. body: JSON.stringify(userData),
  729. });
  730. if (!response.ok) {
  731. const error = await response.json().catch(() => ({ message: 'Failed to create user' }));
  732. throw new Error(error.message || 'Failed to create user');
  733. }
  734. return response.json();
  735. },
  736. async updateUser(userId: string, userData: { email?: string; role?: string; active?: boolean }) {
  737. const response = await apiRequest(`/auth/users/${userId}`, {
  738. method: 'PUT',
  739. body: JSON.stringify(userData),
  740. });
  741. if (!response.ok) {
  742. const error = await response.json().catch(() => ({ message: 'Failed to update user' }));
  743. throw new Error(error.message || 'Failed to update user');
  744. }
  745. return response.json();
  746. },
  747. async deleteUser(userId: string) {
  748. const response = await apiRequest(`/auth/users/${userId}`, {
  749. method: 'DELETE',
  750. });
  751. if (!response.ok) {
  752. throw new Error('Failed to delete user');
  753. }
  754. return response.json();
  755. }
  756. };
  757. export const apiClient = new ApiClient();