api.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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): Promise<ModelInfo[]> {
  450. const cacheKey = `models_${type || 'all'}_${loaded ? 'loaded' : '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. // Request a high limit to get all models (default is 50)
  460. params.push('limit=1000');
  461. if (params.length > 0) endpoint += '?' + params.join('&');
  462. const response = await this.request<{ models: ModelInfo[] }>(endpoint);
  463. const models = response.models.map(model => ({
  464. ...model,
  465. id: model.sha256_short || model.name,
  466. size: model.file_size || model.size,
  467. path: model.path || model.name,
  468. }));
  469. // Cache models for 30 seconds as they don't change frequently
  470. cache.set(cacheKey, models, 30000);
  471. return models;
  472. }
  473. async getModelInfo(modelId: string): Promise<ModelInfo> {
  474. const cacheKey = `model_info_${modelId}`;
  475. const cachedResult = cache.get(cacheKey);
  476. if (cachedResult) {
  477. return cachedResult;
  478. }
  479. const result = await this.request<ModelInfo>(`/models/${modelId}`);
  480. cache.set(cacheKey, result, 30000); // Cache for 30 seconds
  481. return result;
  482. }
  483. async loadModel(modelId: string): Promise<void> {
  484. // Clear model cache when loading
  485. cache.delete(`model_info_${modelId}`);
  486. return this.request<void>(`/models/${modelId}/load`, {
  487. method: 'POST',
  488. });
  489. }
  490. async unloadModel(modelId: string): Promise<void> {
  491. // Clear model cache when unloading
  492. cache.delete(`model_info_${modelId}`);
  493. return this.request<void>(`/models/${modelId}/unload`, {
  494. method: 'POST',
  495. });
  496. }
  497. async scanModels(): Promise<void> {
  498. // Clear all model caches when scanning
  499. cache.clear();
  500. return this.request<void>('/models/refresh', {
  501. method: 'POST',
  502. });
  503. }
  504. async convertModel(modelName: string, quantizationType: string, outputPath?: string): Promise<{ request_id: string; message: string }> {
  505. return this.request<{ request_id: string; message: string }>('/models/convert', {
  506. method: 'POST',
  507. body: JSON.stringify({
  508. model_name: modelName,
  509. quantization_type: quantizationType,
  510. output_path: outputPath,
  511. }),
  512. });
  513. }
  514. // System endpoints
  515. async getHealth(): Promise<{ status: string }> {
  516. return this.request<{ status: string }>('/health');
  517. }
  518. async getStatus(): Promise<any> {
  519. return this.request<any>('/status');
  520. }
  521. async getSystemInfo(): Promise<any> {
  522. return this.request<any>('/system');
  523. }
  524. async restartServer(): Promise<{ message: string }> {
  525. return this.request<{ message: string }>('/system/restart', {
  526. method: 'POST',
  527. body: JSON.stringify({}),
  528. });
  529. }
  530. // Configuration endpoints with caching
  531. async getSamplers(): Promise<Array<{ name: string; description: string; recommended_steps: number }>> {
  532. const cacheKey = 'samplers';
  533. const cachedResult = cache.get(cacheKey);
  534. if (cachedResult) {
  535. return cachedResult;
  536. }
  537. const response = await this.request<{ samplers: Array<{ name: string; description: string; recommended_steps: number }> }>('/samplers');
  538. cache.set(cacheKey, response.samplers, 60000); // Cache for 1 minute
  539. return response.samplers;
  540. }
  541. async getSchedulers(): Promise<Array<{ name: string; description: string }>> {
  542. const cacheKey = 'schedulers';
  543. const cachedResult = cache.get(cacheKey);
  544. if (cachedResult) {
  545. return cachedResult;
  546. }
  547. const response = await this.request<{ schedulers: Array<{ name: string; description: string }> }>('/schedulers');
  548. cache.set(cacheKey, response.schedulers, 60000); // Cache for 1 minute
  549. return response.schedulers;
  550. }
  551. // Cache management methods
  552. clearCache(): void {
  553. cache.clear();
  554. }
  555. clearCacheByPrefix(prefix: string): void {
  556. const keysToDelete: string[] = [];
  557. (cache as any).cache.forEach((_: any, key: string) => {
  558. if (key.startsWith(prefix)) {
  559. keysToDelete.push(key);
  560. }
  561. });
  562. keysToDelete.forEach(key => cache.delete(key));
  563. }
  564. }
  565. // Generic API request function for authentication
  566. export async function apiRequest(
  567. endpoint: string,
  568. options: RequestInit = {}
  569. ): Promise<Response> {
  570. const { apiUrl, apiBase } = getApiConfig();
  571. const url = `${apiUrl}${apiBase}${endpoint}`;
  572. // Get authentication method from server config
  573. const authMethod = typeof window !== 'undefined' && window.__SERVER_CONFIG__
  574. ? window.__SERVER_CONFIG__.authMethod
  575. : 'jwt';
  576. // Add auth token or Unix user header based on auth method
  577. const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;
  578. const unixUser = typeof window !== 'undefined' ? localStorage.getItem('unix_user') : null;
  579. const headers: Record<string, string> = {
  580. 'Content-Type': 'application/json',
  581. ...options.headers as Record<string, string>,
  582. };
  583. if (authMethod === 'unix' && unixUser) {
  584. // For Unix auth, send the username in X-Unix-User header
  585. headers['X-Unix-User'] = unixUser;
  586. } else if (token) {
  587. // For JWT auth, send the token in Authorization header
  588. headers['Authorization'] = `Bearer ${token}`;
  589. }
  590. return fetch(url, {
  591. ...options,
  592. headers,
  593. });
  594. }
  595. // Authentication API endpoints
  596. export const authApi = {
  597. async login(username: string, password?: string) {
  598. // Get authentication method from server config
  599. const authMethod = typeof window !== 'undefined' && window.__SERVER_CONFIG__
  600. ? window.__SERVER_CONFIG__.authMethod
  601. : 'jwt';
  602. // For both Unix and JWT auth, send username and password
  603. // The server will handle whether password is required based on PAM availability
  604. const response = await apiRequest('/auth/login', {
  605. method: 'POST',
  606. body: JSON.stringify({ username, password }),
  607. });
  608. if (!response.ok) {
  609. const error = await response.json().catch(() => ({ message: 'Login failed' }));
  610. throw new Error(error.message || 'Login failed');
  611. }
  612. return response.json();
  613. },
  614. async validateToken(token: string) {
  615. const response = await apiRequest('/auth/validate', {
  616. headers: { 'Authorization': `Bearer ${token}` },
  617. });
  618. if (!response.ok) {
  619. throw new Error('Token validation failed');
  620. }
  621. return response.json();
  622. },
  623. async refreshToken() {
  624. const response = await apiRequest('/auth/refresh', {
  625. method: 'POST',
  626. });
  627. if (!response.ok) {
  628. throw new Error('Token refresh failed');
  629. }
  630. return response.json();
  631. },
  632. async logout() {
  633. await apiRequest('/auth/logout', {
  634. method: 'POST',
  635. });
  636. },
  637. async getCurrentUser() {
  638. const response = await apiRequest('/auth/me');
  639. if (!response.ok) {
  640. throw new Error('Failed to get current user');
  641. }
  642. return response.json();
  643. },
  644. async changePassword(oldPassword: string, newPassword: string) {
  645. const response = await apiRequest('/auth/change-password', {
  646. method: 'POST',
  647. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }),
  648. });
  649. if (!response.ok) {
  650. const error = await response.json().catch(() => ({ message: 'Password change failed' }));
  651. throw new Error(error.message || 'Password change failed');
  652. }
  653. return response.json();
  654. },
  655. // API Key management
  656. async getApiKeys() {
  657. const response = await apiRequest('/auth/api-keys');
  658. if (!response.ok) {
  659. throw new Error('Failed to get API keys');
  660. }
  661. return response.json();
  662. },
  663. async createApiKey(name: string, scopes?: string[]) {
  664. const response = await apiRequest('/auth/api-keys', {
  665. method: 'POST',
  666. body: JSON.stringify({ name, scopes }),
  667. });
  668. if (!response.ok) {
  669. const error = await response.json().catch(() => ({ message: 'Failed to create API key' }));
  670. throw new Error(error.message || 'Failed to create API key');
  671. }
  672. return response.json();
  673. },
  674. async deleteApiKey(keyId: string) {
  675. const response = await apiRequest(`/auth/api-keys/${keyId}`, {
  676. method: 'DELETE',
  677. });
  678. if (!response.ok) {
  679. throw new Error('Failed to delete API key');
  680. }
  681. return response.json();
  682. },
  683. // User management (admin only)
  684. async getUsers() {
  685. const response = await apiRequest('/auth/users');
  686. if (!response.ok) {
  687. throw new Error('Failed to get users');
  688. }
  689. return response.json();
  690. },
  691. async createUser(userData: { username: string; email?: string; password: string; role?: string }) {
  692. const response = await apiRequest('/auth/users', {
  693. method: 'POST',
  694. body: JSON.stringify(userData),
  695. });
  696. if (!response.ok) {
  697. const error = await response.json().catch(() => ({ message: 'Failed to create user' }));
  698. throw new Error(error.message || 'Failed to create user');
  699. }
  700. return response.json();
  701. },
  702. async updateUser(userId: string, userData: { email?: string; role?: string; active?: boolean }) {
  703. const response = await apiRequest(`/auth/users/${userId}`, {
  704. method: 'PUT',
  705. body: JSON.stringify(userData),
  706. });
  707. if (!response.ok) {
  708. const error = await response.json().catch(() => ({ message: 'Failed to update user' }));
  709. throw new Error(error.message || 'Failed to update user');
  710. }
  711. return response.json();
  712. },
  713. async deleteUser(userId: string) {
  714. const response = await apiRequest(`/auth/users/${userId}`, {
  715. method: 'DELETE',
  716. });
  717. if (!response.ok) {
  718. throw new Error('Failed to delete user');
  719. }
  720. return response.json();
  721. }
  722. };
  723. export const apiClient = new ApiClient();