-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_api_new.patch
More file actions
560 lines (547 loc) · 35.2 KB
/
diff_api_new.patch
File metadata and controls
560 lines (547 loc) · 35.2 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
diff --git a/admin/src/lib/api.ts b/admin/src/lib/api.ts
index f701c8aa..8fc74684 100644
--- a/admin/src/lib/api.ts
+++ b/admin/src/lib/api.ts
@@ -1,88 +1,492 @@
-const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
-const ADMIN_API_KEY = import.meta.env.VITE_ADMIN_API_KEY;
+import {
+ clearTokens as clearStoredTokens,
+ readAccessToken,
+ readRefreshToken,
+ writeTokens,
+} from '@/lib/authStorage';
-interface ApiConfig {
- baseURL?: string;
+import type {
+ ApiKey,
+ ApiKeyCreateRequest,
+ ApiKeyCreateResponse,
+ ApiKeyListResponse,
+ ApiKeyRevokeResponse,
+ ApiKeyUpdateRequest,
+ ApiKeyStatus,
+ UsageDto,
+ BillingPlanDto,
+ InvoiceDto,
+ ApiLogDto,
+ ValidationLogDto,
+ AuditLogDto,
+ LogsFilterParams,
+ LogsListResponse,
+ LogsExportRequest,
+ LogsExportResponse,
+ ValidationResultDto
+} from '@/lib/types';
+
+const DEFAULT_BASE_URL = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '';
+const DEFAULT_API_KEY = (import.meta.env.VITE_ADMIN_API_KEY as string | undefined) ?? '';
+
+export interface ApiClientConfig {
+ baseUrl?: string;
+ apiKey?: string;
+ fetchImpl?: typeof fetch;
+}
+
+export interface ApiRequestOptions extends Omit<RequestInit, 'headers'> {
headers?: Record<string, string>;
}
-class ApiClient {
- private config: ApiConfig;
-
- constructor(config: ApiConfig = {}) {
- this.config = {
- baseURL: config.baseURL || API_BASE_URL,
- headers: {
- 'Content-Type': 'application/json',
- 'X-API-Key': ADMIN_API_KEY || '',
- ...config.headers,
- },
- };
- }
-
- private async request<T>(
- endpoint: string,
- options: RequestInit = {}
- ): Promise<T> {
- const url = `${this.config.baseURL}${endpoint}`;
-
- const response = await fetch(url, {
- ...options,
- headers: {
- ...this.config.headers,
- ...options.headers,
- },
- });
+export interface ApiErrorInit {
+ status: number;
+ statusText: string;
+ url: string;
+ data?: unknown;
+}
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.detail || `HTTP ${response.status}: ${response.statusText}`);
+export class ApiError extends Error {
+ public readonly status: number;
+ public readonly statusText: string;
+ public readonly url: string;
+ public readonly data?: unknown;
+
+ constructor(message: string, init: ApiErrorInit) {
+ super(message);
+ this.name = 'ApiError';
+ this.status = init.status;
+ this.statusText = init.statusText;
+ this.url = init.url;
+ this.data = init.data;
+ }
+}
+
+const isFormData = (value: unknown): value is FormData =>
+ typeof FormData !== 'undefined' && value instanceof FormData;
+
+const isBlob = (value: unknown): value is Blob =>
+ typeof Blob !== 'undefined' && value instanceof Blob;
+
+const isURLSearchParams = (value: unknown): value is URLSearchParams =>
+ typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams;
+
+const isReadableStream =
+ typeof ReadableStream !== 'undefined'
+ ? (value: unknown): value is ReadableStream<Uint8Array> => value instanceof ReadableStream
+ : (_value: unknown): _value is ReadableStream<Uint8Array> => false;
+
+const isArrayBuffer = (value: unknown): value is ArrayBuffer =>
+ typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
+
+const isArrayBufferView = (value: unknown): value is ArrayBufferView =>
+ typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value as ArrayBufferView);
+
+const redirectToLogin = () => {
+ if (typeof window !== 'undefined') {
+ window.location.replace('/login');
+ }
+};
+
+export class ApiClient {
+ private readonly baseUrl: string;
+ private readonly apiKey: string;
+ private readonly fetchImpl: typeof fetch;
+
+ constructor(config: ApiClientConfig = {}) {
+ const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
+ this.baseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
+ this.apiKey = config.apiKey ?? DEFAULT_API_KEY;
+ this.fetchImpl = config.fetchImpl ?? fetch;
+ }
+
+ private buildUrl(endpoint: string): string {
+ if (endpoint.startsWith('http://') || endpoint.startsWith('https://')) {
+ return endpoint;
+ }
+
+ const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
+ return `${this.baseUrl}${normalizedEndpoint}`;
+ }
+
+ private shouldSerializeBody(method: string): boolean {
+ return method !== 'GET' && method !== 'HEAD';
+ }
+
+ private prepareBody(body: unknown, method: string): BodyInit | undefined {
+ if (!this.shouldSerializeBody(method) || body === undefined || body === null) {
+ return undefined;
+ }
+
+ if (
+ isFormData(body) ||
+ isBlob(body) ||
+ isURLSearchParams(body) ||
+ isReadableStream(body) ||
+ isArrayBuffer(body) ||
+ isArrayBufferView(body) ||
+ typeof body === 'string'
+ ) {
+ return body as BodyInit;
+ }
+
+ return JSON.stringify(body);
+ }
+
+ private async parseResponse(response: Response): Promise<unknown> {
+ if (response.status === 204 || response.status === 205) {
+ return undefined;
}
- const contentType = response.headers.get('content-type');
- if (contentType && contentType.includes('application/json')) {
+ const contentType = response.headers.get('content-type') ?? '';
+ const isJson = contentType.includes('application/json');
+
+ if (isJson) {
return response.json();
}
- return response.text() as unknown as T;
+ return response.text();
+ }
+
+ private getAuthToken(): string | null {
+ return readAccessToken();
+ }
+
+ private async refreshToken(): Promise<boolean> {
+ const refreshToken = readRefreshToken();
+ if (!refreshToken) {
+ return false;
+ }
+
+ try {
+ const response = await this.fetchImpl(this.buildUrl('/auth/refresh'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ refresh_token: refreshToken }),
+ });
+
+ if (response.ok) {
+ const tokens = await response.json();
+ writeTokens({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token });
+ return true;
+ }
+ } catch (error) {
+ console.error('Token refresh failed:', error);
+ }
+
+ clearStoredTokens();
+ redirectToLogin();
+ return false;
+ }
+
+ private ensureBaseHeaders(headers: Headers, body: unknown, apiKey?: string): void {
+ const token = this.getAuthToken();
+
+ if (token && !apiKey) {
+ headers.set('Authorization', `Bearer ${token}`);
+ } else if (apiKey) {
+ headers.set('X-API-Key', apiKey);
+ }
+
+ if (!isFormData(body)) {
+ headers.set('Content-Type', 'application/json');
+ } else {
+ headers.delete('Content-Type');
+ }
}
- async get<T>(endpoint: string): Promise<T> {
- return this.request<T>(endpoint, { method: 'GET' });
+ private extractErrorMessage(payload: unknown, response: Response): string {
+ if (typeof payload === 'string' && payload.trim()) {
+ return payload;
+ }
+
+ if (payload && typeof payload === 'object') {
+ const candidate =
+ (payload as Record<string, unknown>).detail ??
+ (payload as Record<string, unknown>).message ??
+ (payload as Record<string, unknown>).error ??
+ (payload as Record<string, unknown>).title;
+
+ if (typeof candidate === 'string' && candidate.trim()) {
+ return candidate;
+ }
+ }
+
+ return `HTTP ${response.status}: ${response.statusText}`;
+ }
+
+ async request<T>(endpoint: string, options: ApiRequestOptions = {}): Promise<T> {
+ const method = (options.method ?? 'GET').toUpperCase();
+ const url = this.buildUrl(endpoint);
+ const headers = new Headers(options.headers);
+ const body = this.prepareBody(options.body, method);
+
+ const providedKey =
+ (options.headers &&
+ (options.headers['X-API-Key'] ?? (options.headers['x-api-key'] as string | undefined))) ??
+ undefined;
+ const resolvedApiKey = (providedKey ?? this.apiKey ?? '').trim();
+ const token = this.getAuthToken();
+
+ if (!token && !resolvedApiKey) {
+ throw new ApiError('Authentication required. Please log in or provide API key.', {
+ status: 401,
+ statusText: 'Unauthorized',
+ url,
+ });
+ }
+
+ this.ensureBaseHeaders(headers, options.body, resolvedApiKey);
+
+ let response: Response;
+
+ try {
+ response = await this.fetchImpl(url, {
+ ...options,
+ method,
+ headers,
+ body,
+ });
+ } catch (error) {
+ throw new ApiError('Network request failed', {
+ status: 0,
+ statusText: 'FETCH_ERROR',
+ url,
+ data: error,
+ });
+ }
+
+ if (response.status === 401 && token && !providedKey) {
+ const refreshed = await this.refreshToken();
+ if (refreshed) {
+ const newHeaders = new Headers(options.headers);
+ this.ensureBaseHeaders(newHeaders, options.body);
+
+ try {
+ const retryResponse = await this.fetchImpl(url, {
+ ...options,
+ method,
+ headers: newHeaders,
+ body,
+ });
+
+ if (!retryResponse.ok) {
+ const retryPayload = await this.parseResponse(retryResponse);
+ const message = this.extractErrorMessage(retryPayload, retryResponse);
+ throw new ApiError(message, {
+ status: retryResponse.status,
+ statusText: retryResponse.statusText,
+ url,
+ data: retryPayload,
+ });
+ }
+
+ return (await this.parseResponse(retryResponse)) as T;
+ } catch (retryError) {
+ if (retryError instanceof ApiError) {
+ throw retryError;
+ }
+ throw new ApiError('Retry request failed', {
+ status: 0,
+ statusText: 'RETRY_ERROR',
+ url,
+ data: retryError,
+ });
+ }
+ }
+
+ throw new ApiError('Authentication failed', {
+ status: 401,
+ statusText: 'Unauthorized',
+ url,
+ });
+ }
+
+ const payload = await this.parseResponse(response);
+
+ if (!response.ok) {
+ const message = this.extractErrorMessage(payload, response);
+ throw new ApiError(message, {
+ status: response.status,
+ statusText: response.statusText,
+ url,
+ data: payload,
+ });
+ }
+
+ return payload as T;
}
- async post<T>(endpoint: string, data?: any): Promise<T> {
- return this.request<T>(endpoint, {
- method: 'POST',
- body: data ? JSON.stringify(data) : undefined,
- });
+ get<T>(endpoint: string, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'GET' });
}
- async put<T>(endpoint: string, data?: any): Promise<T> {
- return this.request<T>(endpoint, {
- method: 'PUT',
- body: data ? JSON.stringify(data) : undefined,
- });
+ post<T>(endpoint: string, body?: unknown, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'POST', body });
}
- async delete<T>(endpoint: string): Promise<T> {
- return this.request<T>(endpoint, { method: 'DELETE' });
+ put<T>(endpoint: string, body?: unknown, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'PUT', body });
}
- async uploadFile<T>(endpoint: string, file: File): Promise<T> {
- const formData = new FormData();
- formData.append('file', file);
+ patch<T>(endpoint: string, body?: unknown, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'PATCH', body });
+ }
- return this.request<T>(endpoint, {
- method: 'POST',
- body: formData,
- headers: {
- 'X-API-Key': ADMIN_API_KEY || '',
- },
- });
+ delete<T>(endpoint: string, options?: Omit<ApiRequestOptions, 'method'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'DELETE' });
}
}
+
+export interface ListApiKeysParams {
+ tenantId?: string;
+ status?: ApiKeyStatus;
+ page?: number;
+ perPage?: number;
+}
+
+const buildApiKeyQuery = (params?: ListApiKeysParams): string => {
+ if (!params) {
+ return '';
+ }
+
+ const searchParams = new URLSearchParams();
+ if (params.tenantId) {
+ searchParams.append('tenant_id', params.tenantId);
+ }
+ if (params.status) {
+ searchParams.append('status', params.status);
+ }
+ if (typeof params.page === 'number') {
+ searchParams.append('page', String(params.page));
+ }
+ if (typeof params.perPage === 'number') {
+ searchParams.append('per_page', String(params.perPage));
+ }
+
+ const query = searchParams.toString();
+ return query ? `?${query}` : '';
+};
+
+export const listApiKeys = (params?: ListApiKeysParams): Promise<ApiKeyListResponse> => {
+ const query = buildApiKeyQuery(params);
+ return apiClient.get<ApiKeyListResponse>(`/api-keys${query}`);
+};
+
+export const createApiKey = (payload: ApiKeyCreateRequest): Promise<ApiKeyCreateResponse> => {
+ return apiClient.post<ApiKeyCreateResponse>('/api-keys', payload);
+};
+
+export const updateApiKey = (id: string, payload: ApiKeyUpdateRequest): Promise<ApiKey> => {
+ return apiClient.put<ApiKey>(`/api-keys/${id}`, payload);
+};
+
+export const rotateApiKey = (id: string): Promise<ApiKeyCreateResponse> => {
+ return apiClient.patch<ApiKeyCreateResponse>(`/api-keys/${id}/rotate`);
+};
+
+export const revokeApiKey = (id: string): Promise<ApiKeyRevokeResponse> => {
+ return apiClient.delete<ApiKeyRevokeResponse>(`/api-keys/${id}`);
+};
+
export const apiClient = new ApiClient();
-export default apiClient;
\ No newline at end of file
+export const createApiClient = (config?: ApiClientConfig): ApiClient => new ApiClient(config);
+
+// Billing API functions
+export const getUsage = async (): Promise<UsageDto> => {
+ return apiClient.get<UsageDto>('/usage');
+};
+
+export const getBillingPlan = async (): Promise<BillingPlanDto> => {
+ return apiClient.get<BillingPlanDto>('/billing/plan');
+};
+
+export const getInvoices = async (): Promise<InvoiceDto[]> => {
+ return apiClient.get<InvoiceDto[]>('/billing/invoices');
+};
+
+// Logs & Monitoring API functions
+export type LogCategory = 'api' | 'validation' | 'audit';
+
+const buildLogsQuery = (params?: LogsFilterParams): string => {
+ if (!params) {
+ return '';
+ }
+
+ const searchParams = new URLSearchParams();
+ if (params.start_date) {
+ searchParams.append('start_date', params.start_date);
+ }
+ if (params.end_date) {
+ searchParams.append('end_date', params.end_date);
+ }
+ if (params.status) {
+ searchParams.append('status', params.status);
+ }
+ if (params.result) {
+ searchParams.append('result', params.result);
+ }
+ if (params.action) {
+ searchParams.append('action', params.action);
+ }
+ if (params.tenant_id) {
+ searchParams.append('tenant_id', params.tenant_id);
+ }
+ if (params.endpoint) {
+ searchParams.append('endpoint', params.endpoint);
+ }
+ if (typeof params.min_status_code === 'number') {
+ searchParams.append('min_status_code', String(params.min_status_code));
+ }
+ if (typeof params.max_status_code === 'number') {
+ searchParams.append('max_status_code', String(params.max_status_code));
+ }
+ if (typeof params.page === 'number') {
+ searchParams.append('page', String(params.page));
+ }
+ if (typeof params.per_page === 'number') {
+ searchParams.append('per_page', String(params.per_page));
+ }
+ if (params.sort_by) {
+ searchParams.append('sort_by', params.sort_by);
+ }
+ if (params.sort_order) {
+ searchParams.append('sort_order', params.sort_order);
+ }
+
+ const query = searchParams.toString();
+ return query ? `?${query}` : '';
+};
+
+export const getApiLogs = async (params?: LogsFilterParams): Promise<LogsListResponse<ApiLogDto>> => {
+ const query = buildLogsQuery(params);
+ return apiClient.get<LogsListResponse<ApiLogDto>>(`/logs/api${query}`);
+};
+
+export const getValidationLogs = async (params?: LogsFilterParams): Promise<LogsListResponse<ValidationLogDto>> => {
+ const query = buildLogsQuery(params);
+ return apiClient.get<LogsListResponse<ValidationLogDto>>(`/logs/validation${query}`);
+};
+
+export const getAuditLogs = async (params?: LogsFilterParams): Promise<LogsListResponse<AuditLogDto>> => {
+ const query = buildLogsQuery(params);
+ return apiClient.get<LogsListResponse<AuditLogDto>>(`/logs/audit${query}`);
+};
+
+export const exportLogs = async (logType: LogCategory, request: LogsExportRequest): Promise<LogsExportResponse> => {
+ return apiClient.post<LogsExportResponse>(`/logs/${logType}/export`, request);
+};
+
+// Docs & Playground API functions
+export const getDocs = async (): Promise<string> => {
+ return apiClient.get<string>('/docs');
+};
+
+export const runValidation = async (payload: object): Promise<ValidationResultDto> => {
+ return apiClient.post<ValidationResultDto>('/validate', payload);
+};
+
+export default apiClient;
+