@onairos/react-native 3.3.0 → 3.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,922 +1,979 @@
1
- import type { OnairosConfig, ApiKeyValidationResult } from '../types';
2
- import AsyncStorage from '@react-native-async-storage/async-storage';
3
-
4
- // Admin key for backend validation
5
- export const ADMIN_API_KEY = 'OnairosIsAUnicorn2025';
6
-
7
- // API key types
8
- export enum ApiKeyType {
9
- DEVELOPER = 'developer',
10
- ADMIN = 'admin',
11
- INVALID = 'invalid'
12
- }
13
-
14
- // JWT token storage key
15
- const JWT_TOKEN_KEY = 'onairos_jwt_token';
16
-
17
- /**
18
- * Two-Tier Authentication Service for Onairos React Native SDK
19
- *
20
- * This service implements the two-tier authentication system:
21
- * 1. Developer API Keys: For app-level operations (email verification, app registration)
22
- * 2. JWT User Tokens: For user-level operations (PIN storage, user profile)
23
- *
24
- * How it works:
25
- * 1. Initialize with developer API key
26
- * 2. Use API key for email verification requests
27
- * 3. Store JWT token from email verification response
28
- * 4. Use JWT token for user-authenticated requests
29
- * 5. Handle token expiration gracefully
30
- *
31
- * Backend Integration:
32
- * - Developer routes: Authorization: Bearer ${API_KEY}
33
- * - User routes: Authorization: Bearer ${JWT_TOKEN}
34
- */
35
-
36
- // Global configuration state
37
- let globalConfig: OnairosConfig | null = null;
38
- let validationCache: Map<string, { result: ApiKeyValidationResult; timestamp: number }> = new Map();
39
- let isInitialized = false;
40
- let userToken: string | null = null;
41
-
42
- // Cache duration (5 minutes)
43
- const CACHE_DURATION = 5 * 60 * 1000;
44
-
45
- // API endpoints for different environments (updated to standard)
46
- const API_ENDPOINTS = {
47
- production: 'https://api.onairos.uk',
48
- staging: 'https://staging-api.onairos.uk',
49
- development: 'https://dev-api.onairos.uk',
50
- };
51
-
52
- /**
53
- * Initialize the SDK with developer API key
54
- * @param config API configuration including developer API key
55
- */
56
- export const initializeApiKey = async (config: OnairosConfig): Promise<void> => {
57
- try {
58
- console.log('🔑 Initializing Onairos SDK with developer API key...');
59
-
60
- if (!config.apiKey) {
61
- throw new Error('Developer API key is required for SDK initialization');
62
- }
63
-
64
- // Check if it's admin key first (admin key is shorter than 32 chars)
65
- if (!isAdminKey(config.apiKey) && config.apiKey.length < 32) {
66
- throw new Error('Invalid API key format. Developer keys must be at least 32 characters long.');
67
- }
68
-
69
- // Set global configuration
70
- globalConfig = {
71
- apiKey: config.apiKey,
72
- environment: config.environment || 'production',
73
- enableLogging: config.enableLogging !== false, // Default to true
74
- timeout: config.timeout || 30000,
75
- retryAttempts: config.retryAttempts || 3,
76
- };
77
-
78
- if (globalConfig.enableLogging) {
79
- console.log('📝 SDK Configuration:', {
80
- environment: globalConfig.environment,
81
- timeout: globalConfig.timeout,
82
- retryAttempts: globalConfig.retryAttempts,
83
- apiKeyPrefix: config.apiKey.substring(0, 8) + '...',
84
- enableLogging: globalConfig.enableLogging,
85
- });
86
- }
87
-
88
- // Validate the API key (handles both admin and developer keys)
89
- const validation = await validateApiKey(config.apiKey);
90
-
91
- if (!validation.isValid) {
92
- // If it's a network error or JSON parse error, warn but don't fail initialization
93
- // Use defensive coding to handle cases where validation.error might be undefined
94
- const errorMessage = validation.error || '';
95
- if (errorMessage.includes('Network error') ||
96
- errorMessage.includes('JSON Parse error') ||
97
- errorMessage.includes('API validation endpoint returned')) {
98
- console.warn('⚠️ API key validation failed due to network/server issues, continuing in offline mode:', validation.error);
99
- console.warn('📝 SDK will function with limited validation. Ensure your API key is valid for production use.');
100
- } else {
101
- throw new Error(`API key validation failed: ${validation.error}`);
102
- }
103
- }
104
-
105
- // Try to load existing JWT token
106
- await loadJWT();
107
-
108
- isInitialized = true;
109
-
110
- if (globalConfig.enableLogging) {
111
- console.log(' Onairos SDK initialized successfully');
112
-
113
- if (isAdminKey(config.apiKey)) {
114
- console.log('🔑 Admin API key ready with full permissions');
115
- } else {
116
- console.log('🔑 Developer API key ready for app-level operations');
117
- }
118
-
119
- if (userToken) {
120
- console.log('🎫 User JWT token loaded from storage');
121
- }
122
- if (validation.permissions) {
123
- console.log('🔐 API Key Permissions:', validation.permissions);
124
- }
125
- if (validation.rateLimits) {
126
- console.log('⏱️ Rate Limits:', validation.rateLimits);
127
- }
128
- }
129
- } catch (error) {
130
- console.error('❌ Failed to initialize Onairos SDK:', error);
131
- isInitialized = false;
132
- throw error;
133
- }
134
- };
135
-
136
- /**
137
- * Determine API key type
138
- * @param apiKey The API key to check
139
- * @returns The type of API key
140
- */
141
- export const getApiKeyType = (apiKey: string): ApiKeyType => {
142
- if (apiKey === ADMIN_API_KEY) {
143
- return ApiKeyType.ADMIN;
144
- }
145
-
146
- // Developer keys should be at least 32 characters and start with specific prefix
147
- if (apiKey.length >= 32 && (apiKey.startsWith('dev_') || apiKey.startsWith('pk_') || apiKey.startsWith('ona_'))) {
148
- return ApiKeyType.DEVELOPER;
149
- }
150
-
151
- return ApiKeyType.INVALID;
152
- };
153
-
154
- /**
155
- * Check if API key is admin key
156
- * @param apiKey The API key to check
157
- * @returns True if admin key
158
- */
159
- export const isAdminKey = (apiKey: string): boolean => {
160
- return apiKey === ADMIN_API_KEY;
161
- };
162
-
163
- /**
164
- * Validate an API key with the Onairos backend
165
- * @param apiKey The API key to validate
166
- * @returns Validation result with permissions and rate limits
167
- */
168
- export const validateApiKey = async (apiKey: string): Promise<ApiKeyValidationResult> => {
169
- try {
170
- console.log('🔍 Validating API key...');
171
-
172
- // Check if it's an admin key
173
- if (isAdminKey(apiKey)) {
174
- console.log('🔑 Admin key detected - granting full permissions');
175
- return {
176
- isValid: true,
177
- permissions: ['*'], // Full permissions for admin
178
- rateLimits: {
179
- remaining: 999999,
180
- resetTime: Date.now() + 24 * 60 * 60 * 1000 // 24 hours
181
- },
182
- keyType: ApiKeyType.ADMIN
183
- };
184
- }
185
-
186
- // Check basic format for developer keys
187
- const keyType = getApiKeyType(apiKey);
188
- if (keyType === ApiKeyType.INVALID) {
189
- return {
190
- isValid: false,
191
- error: 'Invalid API key format. Developer keys must be at least 32 characters and start with "dev_", "pk_", or "ona_"',
192
- keyType: ApiKeyType.INVALID
193
- };
194
- }
195
-
196
- // Check cache first
197
- const cached = validationCache.get(apiKey);
198
- if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
199
- if (globalConfig?.enableLogging) {
200
- console.log('📋 Using cached API key validation result');
201
- }
202
- return cached.result;
203
- }
204
-
205
- const environment = globalConfig?.environment || 'production';
206
- const baseUrl = API_ENDPOINTS[environment];
207
- const timeout = globalConfig?.timeout || 30000;
208
- const maxRetries = globalConfig?.retryAttempts || 3;
209
-
210
- // Retry logic for network failures
211
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
212
- // Create abort controller for timeout
213
- const controller = new AbortController();
214
- const timeoutId = setTimeout(() => controller.abort(), timeout);
215
-
216
- try {
217
- if (globalConfig?.enableLogging && attempt > 1) {
218
- console.log(`🔄 Retry attempt ${attempt}/${maxRetries} for API key validation`);
219
- }
220
-
221
- const response = await fetch(`${baseUrl}/auth/validate-key`, {
222
- method: 'POST',
223
- headers: {
224
- 'Content-Type': 'application/json',
225
- 'Authorization': `Bearer ${apiKey}`,
226
- 'User-Agent': 'OnairosReactNative/3.2.1',
227
- 'X-API-Key-Type': keyType,
228
- 'X-SDK-Platform': 'react-native',
229
- 'X-Retry-Attempt': attempt.toString(),
230
- },
231
- body: JSON.stringify({
232
- environment,
233
- sdk_version: '3.2.1',
234
- platform: 'react-native',
235
- keyType,
236
- timestamp: new Date().toISOString(),
237
- attempt,
238
- }),
239
- signal: controller.signal,
240
- });
241
-
242
- clearTimeout(timeoutId);
243
-
244
- // First check if we got a valid response
245
- if (!response) {
246
- throw new Error('No response received from server');
247
- }
248
-
249
- // Check if response is actually JSON before trying to parse
250
- const contentType = response.headers.get('content-type');
251
- const isJsonResponse = contentType && contentType.includes('application/json');
252
-
253
- if (!isJsonResponse) {
254
- const textContent = await response.text();
255
- const previewText = textContent.substring(0, 200);
256
-
257
- console.error('❌ API endpoint returned non-JSON response:', {
258
- status: response.status,
259
- statusText: response.statusText,
260
- contentType: contentType || 'unknown',
261
- preview: previewText,
262
- url: `${baseUrl}/auth/validate-key`,
263
- attempt: attempt
264
- });
265
-
266
- // Handle specific error cases
267
- if (response.status === 404) {
268
- throw new Error(`API validation endpoint not found (404). The endpoint ${baseUrl}/auth/validate-key may not exist or be configured correctly.`);
269
- } else if (response.status === 500) {
270
- throw new Error(`Server error (500). The Onairos backend is experiencing issues.`);
271
- } else if (response.status === 502 || response.status === 503) {
272
- throw new Error(`Service unavailable (${response.status}). The Onairos backend may be temporarily down.`);
273
- } else if (textContent.includes('<html') || textContent.includes('<!DOCTYPE')) {
274
- throw new Error(`Server returned HTML page instead of JSON API response. This often indicates a routing issue or server misconfiguration.`);
275
- } else {
276
- throw new Error(`API validation endpoint returned ${response.status} - ${response.statusText}. Expected JSON but got ${contentType || 'unknown content type'}.`);
277
- }
278
- }
279
-
280
- // Parse JSON response
281
- let data;
282
- try {
283
- data = await response.json();
284
- } catch (jsonError) {
285
- console.error('❌ Failed to parse JSON response:', {
286
- error: jsonError.message,
287
- status: response.status,
288
- contentType,
289
- attempt: attempt
290
- });
291
- throw new Error(`Failed to parse server response as JSON: ${jsonError.message}`);
292
- }
293
-
294
- // Handle successful response
295
- if (response.ok && data.success) {
296
- const result: ApiKeyValidationResult = {
297
- isValid: true,
298
- permissions: data.permissions || [],
299
- rateLimits: data.rateLimits || null,
300
- keyType: keyType,
301
- };
302
-
303
- // Cache the successful result
304
- validationCache.set(apiKey, {
305
- result,
306
- timestamp: Date.now(),
307
- });
308
-
309
- if (globalConfig?.enableLogging) {
310
- console.log('✅ API key validation successful');
311
- }
312
-
313
- return result;
314
- } else {
315
- // Handle API errors (invalid key, etc.)
316
- const errorMessage = data.error || data.message || `HTTP ${response.status}: ${response.statusText}`;
317
-
318
- const result: ApiKeyValidationResult = {
319
- isValid: false,
320
- error: errorMessage,
321
- keyType: keyType,
322
- };
323
-
324
- // For client errors (4xx), don't retry
325
- if (response.status >= 400 && response.status < 500) {
326
- if (globalConfig?.enableLogging) {
327
- console.error('❌ API key validation failed (client error):', errorMessage);
328
- }
329
- return result;
330
- }
331
-
332
- // For server errors (5xx), retry
333
- throw new Error(errorMessage);
334
- }
335
-
336
- } catch (fetchError: any) {
337
- clearTimeout(timeoutId);
338
-
339
- if (fetchError.name === 'AbortError') {
340
- const errorMessage = `API key validation timeout (${timeout}ms)`;
341
- console.error('⏱️ API key validation timeout');
342
-
343
- if (attempt === maxRetries) {
344
- return { isValid: false, error: errorMessage, keyType: keyType };
345
- }
346
- continue; // Retry timeout errors
347
- }
348
-
349
- // Enhanced error message based on error type
350
- let errorMessage = `Network error during API key validation: ${fetchError.message}`;
351
-
352
- // Add specific guidance for common errors
353
- if (fetchError.message.includes('JSON Parse error') || fetchError.message.includes('Unexpected character')) {
354
- errorMessage = `Server returned invalid JSON response. This usually indicates the API endpoint returned HTML instead of JSON (often a 404 or server error page). ${fetchError.message}`;
355
- } else if (fetchError.message.includes('Network request failed') || fetchError.message.includes('fetch')) {
356
- errorMessage = `Network connectivity issue. Please check internet connection and verify the Onairos API is accessible. ${fetchError.message}`;
357
- } else if (fetchError.message.includes('DNS') || fetchError.message.includes('ENOTFOUND')) {
358
- errorMessage = `DNS resolution failed for ${baseUrl}. Please check network settings and domain accessibility. ${fetchError.message}`;
359
- }
360
-
361
- console.error('🌐 Network error during API key validation:', {
362
- error: fetchError,
363
- endpoint: `${baseUrl}/auth/validate-key`,
364
- attempt: attempt,
365
- maxRetries: maxRetries,
366
- retryable: attempt < maxRetries
367
- });
368
-
369
- // If this is the last attempt, return the error
370
- if (attempt === maxRetries) {
371
- return {
372
- isValid: false,
373
- error: errorMessage,
374
- keyType: keyType
375
- };
376
- }
377
-
378
- // Wait before retrying (exponential backoff)
379
- const backoffDelay = Math.min(1000 * Math.pow(2, attempt - 1), 5000);
380
- if (globalConfig?.enableLogging) {
381
- console.log(`⏳ Waiting ${backoffDelay}ms before retry...`);
382
- }
383
- await new Promise<void>(resolve => setTimeout(() => resolve(), backoffDelay));
384
- }
385
- }
386
-
387
- // This should never be reached, but just in case
388
- return {
389
- isValid: false,
390
- error: 'All retry attempts exhausted',
391
- keyType: keyType
392
- };
393
-
394
- } catch (error: any) {
395
- const errorMessage = `API key validation error: ${error.message}`;
396
- console.error('❌ API key validation error:', error);
397
- return { isValid: false, error: errorMessage, keyType: ApiKeyType.INVALID };
398
- }
399
- };
400
-
401
- /**
402
- * Get the current API configuration
403
- * @returns Current API configuration or null if not initialized
404
- */
405
- export const getApiConfig = (): OnairosConfig | null => {
406
- return globalConfig;
407
- };
408
-
409
- /**
410
- * Get the current API key
411
- * @returns Current API key or null if not initialized
412
- */
413
- export const getApiKey = (): string | null => {
414
- return globalConfig?.apiKey || null;
415
- };
416
-
417
- /**
418
- * Check if the SDK is properly initialized
419
- * @returns True if initialized with valid API key
420
- */
421
- export const isApiKeyInitialized = (): boolean => {
422
- return isInitialized && globalConfig !== null;
423
- };
424
-
425
- /**
426
- * Store JWT token securely after email verification
427
- * @param token JWT token from email verification response
428
- */
429
- export const storeJWT = async (token: string): Promise<void> => {
430
- try {
431
- await AsyncStorage.setItem(JWT_TOKEN_KEY, token);
432
- userToken = token;
433
-
434
- if (globalConfig?.enableLogging) {
435
- console.log('🎫 JWT token stored successfully');
436
- }
437
- } catch (error) {
438
- console.error('❌ Failed to store JWT token:', error);
439
- throw error;
440
- }
441
- };
442
-
443
- /**
444
- * Load JWT token from storage
445
- * @returns JWT token or null if not found
446
- */
447
- export const loadJWT = async (): Promise<string | null> => {
448
- try {
449
- const token = await AsyncStorage.getItem(JWT_TOKEN_KEY);
450
- userToken = token;
451
- return token;
452
- } catch (error) {
453
- console.error('❌ Failed to load JWT token:', error);
454
- return null;
455
- }
456
- };
457
-
458
- /**
459
- * Get current JWT token
460
- * @returns JWT token or null if not available
461
- */
462
- export const getJWT = (): string | null => {
463
- return userToken;
464
- };
465
-
466
- /**
467
- * Clear JWT token (on logout or token expiration)
468
- */
469
- export const clearJWT = async (): Promise<void> => {
470
- try {
471
- await AsyncStorage.removeItem(JWT_TOKEN_KEY);
472
- userToken = null;
473
-
474
- if (globalConfig?.enableLogging) {
475
- console.log('🗑️ JWT token cleared');
476
- }
477
- } catch (error) {
478
- console.error('❌ Failed to clear JWT token:', error);
479
- }
480
- };
481
-
482
- /**
483
- * React Native compatible base64 decoder
484
- * @param str Base64 encoded string
485
- * @returns Decoded string
486
- */
487
- const base64Decode = (str: string): string => {
488
- // Simple base64 decoding for React Native
489
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
490
- let result = '';
491
- let i = 0;
492
-
493
- str = str.replace(/[^A-Za-z0-9+/]/g, '');
494
-
495
- while (i < str.length) {
496
- const a = chars.indexOf(str.charAt(i++));
497
- const b = chars.indexOf(str.charAt(i++));
498
- const c = chars.indexOf(str.charAt(i++));
499
- const d = chars.indexOf(str.charAt(i++));
500
-
501
- const bitmap = (a << 18) | (b << 12) | (c << 6) | d;
502
-
503
- result += String.fromCharCode((bitmap >> 16) & 255);
504
- if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
505
- if (d !== 64) result += String.fromCharCode(bitmap & 255);
506
- }
507
-
508
- return result;
509
- };
510
-
511
- /**
512
- * Decode JWT token payload (React Native compatible)
513
- * @param token JWT token string
514
- * @returns Decoded payload or null if invalid
515
- */
516
- export const decodeJWTPayload = (token: string): any => {
517
- try {
518
- // Split JWT token (header.payload.signature)
519
- const parts = token.split('.');
520
- if (parts.length !== 3) {
521
- console.error('❌ Invalid JWT token format');
522
- return null;
523
- }
524
-
525
- // Decode payload (base64url to base64)
526
- const payload = parts[1];
527
- const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
528
-
529
- // Add padding if needed
530
- const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=');
531
-
532
- // Decode base64 to JSON using React Native compatible decoder
533
- const decoded = base64Decode(padded);
534
- return JSON.parse(decoded);
535
- } catch (error) {
536
- console.error('❌ Failed to decode JWT token:', error);
537
- return null;
538
- }
539
- };
540
-
541
- /**
542
- * Extract username from JWT token
543
- * @param token JWT token (optional, uses stored token if not provided)
544
- * @returns Username or null if not found
545
- */
546
- export const extractUsernameFromJWT = (token?: string): string | null => {
547
- try {
548
- const jwtToken = token || userToken;
549
- if (!jwtToken) {
550
- console.warn('⚠️ No JWT token available for username extraction');
551
- return null;
552
- }
553
-
554
- const payload = decodeJWTPayload(jwtToken);
555
- if (!payload) {
556
- return null;
557
- }
558
-
559
- // Try different possible username fields in order of preference
560
- const username = payload.userName || payload.username || payload.userId || payload.email;
561
-
562
- if (globalConfig?.enableLogging) {
563
- console.log('👤 Extracted username from JWT:', username);
564
- }
565
-
566
- return username || null;
567
- } catch (error) {
568
- console.error('❌ Failed to extract username from JWT:', error);
569
- return null;
570
- }
571
- };
572
-
573
- /**
574
- * Extract user data from JWT token
575
- * @param token JWT token (optional, uses stored token if not provided)
576
- * @returns User data object or null if not found
577
- */
578
- export const extractUserDataFromJWT = (token?: string): any => {
579
- try {
580
- const jwtToken = token || userToken;
581
- if (!jwtToken) {
582
- console.warn('⚠️ No JWT token available for user data extraction');
583
- return null;
584
- }
585
-
586
- const payload = decodeJWTPayload(jwtToken);
587
- if (!payload) {
588
- return null;
589
- }
590
-
591
- const userData = {
592
- id: payload.id,
593
- email: payload.email,
594
- userId: payload.userId,
595
- userName: payload.userName || payload.username,
596
- verified: payload.verified,
597
- iat: payload.iat,
598
- exp: payload.exp
599
- };
600
-
601
- if (globalConfig?.enableLogging) {
602
- console.log('👤 Extracted user data from JWT:', userData);
603
- }
604
-
605
- return userData;
606
- } catch (error) {
607
- console.error(' Failed to extract user data from JWT:', error);
608
- return null;
609
- }
610
- };
611
-
612
- /**
613
- * Check if user is authenticated with JWT token
614
- * @returns True if user has valid JWT token
615
- */
616
- export const isUserAuthenticated = (): boolean => {
617
- return !!userToken;
618
- };
619
-
620
- /**
621
- * Get authenticated headers for API requests
622
- * @returns Headers object with Authorization and other required headers
623
- */
624
- export const getAuthHeaders = (): Record<string, string> => {
625
- if (!globalConfig?.apiKey) {
626
- throw new Error('SDK not initialized. Call initializeApiKey() first.');
627
- }
628
-
629
- const keyType = getApiKeyType(globalConfig.apiKey);
630
-
631
- return {
632
- 'Content-Type': 'application/json',
633
- 'Authorization': `Bearer ${globalConfig.apiKey}`,
634
- 'User-Agent': 'OnairosReactNative/3.0.72',
635
- 'X-SDK-Version': '3.0.72',
636
- 'X-SDK-Environment': globalConfig.environment || 'production',
637
- 'X-API-Key-Type': keyType,
638
- 'X-Timestamp': new Date().toISOString(),
639
- };
640
- };
641
-
642
- /**
643
- * Get authentication headers for developer API requests
644
- * @returns Headers with developer API key
645
- */
646
- export const getDeveloperAuthHeaders = (): Record<string, string> => {
647
- if (!globalConfig?.apiKey) {
648
- throw new Error('SDK not initialized. Call initializeApiKey() first.');
649
- }
650
-
651
- const keyType = getApiKeyType(globalConfig.apiKey);
652
-
653
- return {
654
- 'Content-Type': 'application/json',
655
- 'Authorization': `Bearer ${globalConfig.apiKey}`,
656
- 'User-Agent': 'OnairosSDK/1.0.0',
657
- 'X-SDK-Version': '3.0.72',
658
- 'X-SDK-Environment': globalConfig.environment || 'production',
659
- 'X-API-Key-Type': keyType,
660
- 'X-Timestamp': new Date().toISOString(),
661
- };
662
- };
663
-
664
- /**
665
- * Get authentication headers for user JWT requests
666
- * @returns Headers with user JWT token
667
- */
668
- export const getUserAuthHeaders = (): Record<string, string> => {
669
- if (!userToken) {
670
- throw new Error('User not authenticated. Please verify email first.');
671
- }
672
-
673
- return {
674
- 'Content-Type': 'application/json',
675
- 'Authorization': `Bearer ${userToken}`,
676
- 'User-Agent': 'OnairosSDK/1.0.0',
677
- 'X-SDK-Version': '3.0.72',
678
- 'X-SDK-Environment': globalConfig?.environment || 'production',
679
- };
680
- };
681
-
682
- /**
683
- * Make an authenticated API request
684
- * @param endpoint The API endpoint (relative to base URL)
685
- * @param options Fetch options
686
- * @returns Response promise
687
- */
688
- export const makeAuthenticatedRequest = async (
689
- endpoint: string,
690
- options: RequestInit = {}
691
- ): Promise<Response> => {
692
- if (!isApiKeyInitialized()) {
693
- throw new Error('SDK not initialized. Call initializeApiKey() first.');
694
- }
695
-
696
- const config = getApiConfig()!;
697
- const baseUrl = API_ENDPOINTS[config.environment || 'production'];
698
- const url = `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
699
-
700
- // Merge authentication headers
701
- const headers = {
702
- ...getAuthHeaders(),
703
- ...(options.headers || {}),
704
- };
705
-
706
- // Add timeout
707
- const controller = new AbortController();
708
- const timeoutId = setTimeout(() => controller.abort(), config.timeout || 30000);
709
-
710
- try {
711
- if (config.enableLogging) {
712
- console.log(`🌐 Making authenticated request to: ${endpoint}`);
713
- }
714
-
715
- const response = await fetch(url, {
716
- ...options,
717
- headers,
718
- signal: controller.signal,
719
- });
720
-
721
- clearTimeout(timeoutId);
722
-
723
- if (config.enableLogging) {
724
- console.log(`📡 Response status: ${response.status} for ${endpoint}`);
725
- }
726
-
727
- // Handle API key errors
728
- if (response.status === 401) {
729
- console.error('❌ API key authentication failed. Please check your API key.');
730
- throw new Error('Invalid or expired API key');
731
- }
732
-
733
- if (response.status === 403) {
734
- console.error(' API key permissions insufficient for this operation.');
735
- throw new Error('Insufficient API key permissions');
736
- }
737
-
738
- if (response.status === 429) {
739
- console.error('❌ API rate limit exceeded. Please try again later.');
740
- throw new Error('Rate limit exceeded');
741
- }
742
-
743
- return response;
744
- } catch (error) {
745
- clearTimeout(timeoutId);
746
-
747
- if (error.name === 'AbortError') {
748
- console.error('⏱️ Request timeout for:', endpoint);
749
- throw new Error('Request timeout');
750
- }
751
-
752
- throw error;
753
- }
754
- };
755
-
756
- /**
757
- * Make authenticated request with developer API key
758
- * @param endpoint The API endpoint
759
- * @param options Fetch options
760
- * @returns Response promise
761
- */
762
- export const makeDeveloperRequest = async (
763
- endpoint: string,
764
- options: RequestInit = {}
765
- ): Promise<Response> => {
766
- if (!isApiKeyInitialized()) {
767
- throw new Error('SDK not initialized. Call initializeApiKey() first.');
768
- }
769
-
770
- const config = getApiConfig()!;
771
- const baseUrl = API_ENDPOINTS[config.environment || 'production'];
772
- const url = `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
773
-
774
- // Merge developer authentication headers
775
- const headers = {
776
- ...getDeveloperAuthHeaders(),
777
- ...(options.headers || {}),
778
- };
779
-
780
- // Add timeout
781
- const controller = new AbortController();
782
- const timeoutId = setTimeout(() => controller.abort(), config.timeout || 30000);
783
-
784
- try {
785
- if (config.enableLogging) {
786
- console.log(`🌐 Making developer request to: ${endpoint}`);
787
- }
788
-
789
- const response = await fetch(url, {
790
- ...options,
791
- headers,
792
- signal: controller.signal,
793
- });
794
-
795
- clearTimeout(timeoutId);
796
-
797
- if (config.enableLogging) {
798
- console.log(`📡 Developer request response: ${response.status} for ${endpoint}`);
799
- }
800
-
801
- // Handle API key errors
802
- if (response.status === 401) {
803
- console.error('❌ Developer API key authentication failed');
804
- throw new Error('Invalid or expired API key');
805
- }
806
-
807
- if (response.status === 403) {
808
- console.error('❌ Developer API key permissions insufficient');
809
- throw new Error('Insufficient API key permissions');
810
- }
811
-
812
- if (response.status === 429) {
813
- console.error('❌ API rate limit exceeded');
814
- throw new Error('Rate limit exceeded');
815
- }
816
-
817
- return response;
818
- } catch (error) {
819
- clearTimeout(timeoutId);
820
-
821
- if (error.name === 'AbortError') {
822
- console.error('⏱️ Request timeout for:', endpoint);
823
- throw new Error('Request timeout');
824
- }
825
-
826
- throw error;
827
- }
828
- };
829
-
830
- /**
831
- * Make authenticated request with user JWT token
832
- * @param endpoint The API endpoint
833
- * @param options Fetch options
834
- * @returns Response promise
835
- */
836
- export const makeUserRequest = async (
837
- endpoint: string,
838
- options: RequestInit = {}
839
- ): Promise<Response> => {
840
- if (!isUserAuthenticated()) {
841
- await loadJWT(); // Try to load from storage
842
- }
843
-
844
- if (!isUserAuthenticated()) {
845
- throw new Error('User not authenticated. Please verify email first.');
846
- }
847
-
848
- const config = getApiConfig() || { environment: 'production', timeout: 30000, enableLogging: false };
849
- const baseUrl = API_ENDPOINTS[config.environment || 'production'];
850
- const url = `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
851
-
852
- // Merge user authentication headers
853
- const headers = {
854
- ...getUserAuthHeaders(),
855
- ...(options.headers || {}),
856
- };
857
-
858
- // Add timeout
859
- const controller = new AbortController();
860
- const timeoutId = setTimeout(() => controller.abort(), config.timeout || 30000);
861
-
862
- try {
863
- if (config.enableLogging) {
864
- console.log(`🌐 Making user request to: ${endpoint}`);
865
- }
866
-
867
- const response = await fetch(url, {
868
- ...options,
869
- headers,
870
- signal: controller.signal,
871
- });
872
-
873
- clearTimeout(timeoutId);
874
-
875
- if (config.enableLogging) {
876
- console.log(`📡 User request response: ${response.status} for ${endpoint}`);
877
- }
878
-
879
- // Handle JWT token errors
880
- if (response.status === 401) {
881
- console.error('❌ JWT token authentication failed - token may be expired');
882
- await clearJWT(); // Clear expired token
883
- throw new Error('Authentication expired. Please verify email again.');
884
- }
885
-
886
- if (response.status === 403) {
887
- console.error('❌ JWT token permissions insufficient');
888
- throw new Error('Insufficient permissions for this operation');
889
- }
890
-
891
- return response;
892
- } catch (error) {
893
- clearTimeout(timeoutId);
894
-
895
- if (error.name === 'AbortError') {
896
- console.error('⏱️ Request timeout for:', endpoint);
897
- throw new Error('Request timeout');
898
- }
899
-
900
- throw error;
901
- }
902
- };
903
-
904
- /**
905
- * Clear the API key validation cache
906
- */
907
- export const clearValidationCache = (): void => {
908
- validationCache.clear();
909
- if (globalConfig?.enableLogging) {
910
- console.log('🗑️ API key validation cache cleared');
911
- }
912
- };
913
-
914
- /**
915
- * Reset the SDK initialization state
916
- */
917
- export const resetApiKeyService = (): void => {
918
- globalConfig = null;
919
- isInitialized = false;
920
- clearValidationCache();
921
- console.log('🔄 API key service reset');
1
+ import type { OnairosConfig, ApiKeyValidationResult } from '../types';
2
+ import AsyncStorage from '@react-native-async-storage/async-storage';
3
+ import NetInfo from '@react-native-community/netinfo';
4
+
5
+ // Admin key for backend validation
6
+ export const ADMIN_API_KEY = 'OnairosIsAUnicorn2025';
7
+
8
+ // API key types
9
+ export enum ApiKeyType {
10
+ DEVELOPER = 'developer',
11
+ ADMIN = 'admin',
12
+ INVALID = 'invalid'
13
+ }
14
+
15
+ // JWT token storage key
16
+ const JWT_TOKEN_KEY = 'onairos_jwt_token';
17
+
18
+ /**
19
+ * Two-Tier Authentication Service for Onairos React Native SDK
20
+ *
21
+ * This service implements the two-tier authentication system:
22
+ * 1. Developer API Keys: For app-level operations (email verification, app registration)
23
+ * 2. JWT User Tokens: For user-level operations (PIN storage, user profile)
24
+ *
25
+ * How it works:
26
+ * 1. Initialize with developer API key
27
+ * 2. Use API key for email verification requests
28
+ * 3. Store JWT token from email verification response
29
+ * 4. Use JWT token for user-authenticated requests
30
+ * 5. Handle token expiration gracefully
31
+ *
32
+ * Backend Integration:
33
+ * - Developer routes: Authorization: Bearer ${API_KEY}
34
+ * - User routes: Authorization: Bearer ${JWT_TOKEN}
35
+ */
36
+
37
+ // Global configuration state
38
+ let globalConfig: OnairosConfig | null = null;
39
+ let validationCache: Map<string, { result: ApiKeyValidationResult; timestamp: number }> = new Map();
40
+ let isInitialized = false;
41
+ let userToken: string | null = null;
42
+
43
+ // Cache duration (5 minutes)
44
+ const CACHE_DURATION = 5 * 60 * 1000;
45
+
46
+ /**
47
+ * Check network connectivity
48
+ * @returns Promise<boolean> - true if connected, false otherwise
49
+ */
50
+ const checkNetworkConnectivity = async (): Promise<boolean> => {
51
+ try {
52
+ const netInfo = await NetInfo.fetch();
53
+ return netInfo.isConnected === true && netInfo.isInternetReachable !== false;
54
+ } catch (error) {
55
+ console.warn('⚠️ Failed to check network connectivity:', error);
56
+ // If we can't check connectivity, assume we're connected and let the request fail naturally
57
+ return true;
58
+ }
59
+ };
60
+
61
+ // API endpoints for different environments (updated to handle non-existent dev endpoint)
62
+ const API_ENDPOINTS = {
63
+ production: 'https://api2.onairos.uk',
64
+ staging: 'https://api2.onairos.uk', // Fallback to production for staging
65
+ development: 'https://api2.onairos.uk', // Fallback to production since dev-api2.onairos.uk doesn't exist
66
+ };
67
+
68
+ /**
69
+ * Initialize the SDK with developer API key
70
+ * @param config API configuration including developer API key
71
+ */
72
+ export const initializeApiKey = async (config: OnairosConfig): Promise<void> => {
73
+ try {
74
+ console.log('🔑 Initializing Onairos SDK with developer API key...');
75
+
76
+ if (!config.apiKey) {
77
+ throw new Error('Developer API key is required for SDK initialization');
78
+ }
79
+
80
+ // Check if it's admin key first (admin key is shorter than 32 chars)
81
+ if (!isAdminKey(config.apiKey) && config.apiKey.length < 32) {
82
+ throw new Error('Invalid API key format. Developer keys must be at least 32 characters long.');
83
+ }
84
+
85
+ // Set global configuration
86
+ globalConfig = {
87
+ apiKey: config.apiKey,
88
+ environment: config.environment || 'production',
89
+ enableLogging: config.enableLogging !== false, // Default to true
90
+ timeout: config.timeout || 30000,
91
+ retryAttempts: config.retryAttempts || 3,
92
+ };
93
+
94
+ if (globalConfig.enableLogging) {
95
+ console.log('📝 SDK Configuration:', {
96
+ environment: globalConfig.environment,
97
+ timeout: globalConfig.timeout,
98
+ retryAttempts: globalConfig.retryAttempts,
99
+ apiKeyPrefix: config.apiKey.substring(0, 8) + '...',
100
+ enableLogging: globalConfig.enableLogging,
101
+ });
102
+ }
103
+
104
+ // Validate the API key (handles both admin and developer keys)
105
+ const validation = await validateApiKey(config.apiKey);
106
+
107
+ if (!validation.isValid) {
108
+ // Use defensive coding to handle cases where validation.error might be undefined
109
+ const errorMessage = validation.error || '';
110
+
111
+ // Check if it's a network/connectivity issue (either from error message or the flag)
112
+ const isNetworkError = validation.isNetworkError ||
113
+ errorMessage.includes('Network request failed') ||
114
+ errorMessage.includes('Network error') ||
115
+ errorMessage.includes('JSON Parse error') ||
116
+ errorMessage.includes('API validation endpoint returned') ||
117
+ errorMessage.includes('timeout') ||
118
+ errorMessage.includes('ENOTFOUND') ||
119
+ errorMessage.includes('fetch') ||
120
+ errorMessage.includes('No network connection');
121
+
122
+ if (isNetworkError) {
123
+ console.warn('⚠️ API key validation failed due to network/connectivity issues');
124
+ console.warn('🔄 Continuing in offline mode with basic validation');
125
+ console.warn('📝 SDK will function with limited validation. Network connectivity will be retried automatically.');
126
+ console.warn('🌐 Error details:', validation.error);
127
+
128
+ // Continue initialization in offline mode - don't throw error
129
+ console.log('📱 SDK initialized in offline mode - will retry validation when network is available');
130
+ } else {
131
+ // Only throw for actual API key validation errors (not network issues)
132
+ throw new Error(`API key validation failed: ${validation.error}`);
133
+ }
134
+ }
135
+
136
+ // Try to load existing JWT token
137
+ await loadJWT();
138
+
139
+ isInitialized = true;
140
+
141
+ if (globalConfig.enableLogging) {
142
+ console.log('✅ Onairos SDK initialized successfully');
143
+
144
+ if (isAdminKey(config.apiKey)) {
145
+ console.log('🔑 Admin API key ready with full permissions');
146
+ } else {
147
+ console.log('🔑 Developer API key ready for app-level operations');
148
+ }
149
+
150
+ if (userToken) {
151
+ console.log('🎫 User JWT token loaded from storage');
152
+ }
153
+ if (validation.permissions) {
154
+ console.log('🔐 API Key Permissions:', validation.permissions);
155
+ }
156
+ if (validation.rateLimits) {
157
+ console.log('⏱️ Rate Limits:', validation.rateLimits);
158
+ }
159
+ }
160
+ } catch (error) {
161
+ console.error('❌ Failed to initialize Onairos SDK:', error);
162
+ isInitialized = false;
163
+ throw error;
164
+ }
165
+ };
166
+
167
+ /**
168
+ * Determine API key type
169
+ * @param apiKey The API key to check
170
+ * @returns The type of API key
171
+ */
172
+ export const getApiKeyType = (apiKey: string): ApiKeyType => {
173
+ if (apiKey === ADMIN_API_KEY) {
174
+ return ApiKeyType.ADMIN;
175
+ }
176
+
177
+ // Developer keys should be at least 32 characters and start with specific prefix
178
+ if (apiKey.length >= 32 && (apiKey.startsWith('dev_') || apiKey.startsWith('pk_') || apiKey.startsWith('ona_'))) {
179
+ return ApiKeyType.DEVELOPER;
180
+ }
181
+
182
+ return ApiKeyType.INVALID;
183
+ };
184
+
185
+ /**
186
+ * Check if API key is admin key
187
+ * @param apiKey The API key to check
188
+ * @returns True if admin key
189
+ */
190
+ export const isAdminKey = (apiKey: string): boolean => {
191
+ return apiKey === ADMIN_API_KEY;
192
+ };
193
+
194
+ /**
195
+ * Validate an API key with the Onairos backend
196
+ * @param apiKey The API key to validate
197
+ * @returns Validation result with permissions and rate limits
198
+ */
199
+ export const validateApiKey = async (apiKey: string): Promise<ApiKeyValidationResult> => {
200
+ try {
201
+ console.log('🔍 Validating API key...');
202
+
203
+ // Check if it's an admin key
204
+ if (isAdminKey(apiKey)) {
205
+ console.log('🔑 Admin key detected - granting full permissions');
206
+ return {
207
+ isValid: true,
208
+ permissions: ['*'], // Full permissions for admin
209
+ rateLimits: {
210
+ remaining: 999999,
211
+ resetTime: Date.now() + 24 * 60 * 60 * 1000 // 24 hours
212
+ },
213
+ keyType: ApiKeyType.ADMIN
214
+ };
215
+ }
216
+
217
+ // Check basic format for developer keys
218
+ const keyType = getApiKeyType(apiKey);
219
+ if (keyType === ApiKeyType.INVALID) {
220
+ return {
221
+ isValid: false,
222
+ error: 'Invalid API key format. Developer keys must be at least 32 characters and start with "dev_", "pk_", or "ona_"',
223
+ keyType: ApiKeyType.INVALID
224
+ };
225
+ }
226
+
227
+ // Check cache first
228
+ const cached = validationCache.get(apiKey);
229
+ if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
230
+ if (globalConfig?.enableLogging) {
231
+ console.log('📋 Using cached API key validation result');
232
+ }
233
+ return cached.result;
234
+ }
235
+
236
+ // Check network connectivity before making API calls
237
+ const isConnected = await checkNetworkConnectivity();
238
+ if (!isConnected) {
239
+ console.warn('⚠️ No network connectivity detected');
240
+ return {
241
+ isValid: false,
242
+ error: 'No network connection available. Please check your internet connection and try again.',
243
+ keyType: keyType,
244
+ isNetworkError: true
245
+ };
246
+ }
247
+
248
+ const environment = globalConfig?.environment || 'production';
249
+ const baseUrl = API_ENDPOINTS[environment];
250
+ const timeout = globalConfig?.timeout || 30000;
251
+ const maxRetries = globalConfig?.retryAttempts || 3;
252
+
253
+ // Retry logic for network failures
254
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
255
+ // Create abort controller for timeout
256
+ const controller = new AbortController();
257
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
258
+
259
+ try {
260
+ if (globalConfig?.enableLogging && attempt > 1) {
261
+ console.log(`🔄 Retry attempt ${attempt}/${maxRetries} for API key validation`);
262
+ }
263
+
264
+ const response = await fetch(`${baseUrl}/auth/validate-key`, {
265
+ method: 'POST',
266
+ headers: {
267
+ 'Content-Type': 'application/json',
268
+ 'Authorization': `Bearer ${apiKey}`,
269
+ 'User-Agent': 'OnairosReactNative/3.3.1',
270
+ 'X-API-Key-Type': keyType,
271
+ 'X-SDK-Platform': 'react-native',
272
+ 'X-Retry-Attempt': attempt.toString(),
273
+ },
274
+ body: JSON.stringify({
275
+ environment,
276
+ sdk_version: '3.3.1',
277
+ platform: 'react-native',
278
+ keyType,
279
+ timestamp: new Date().toISOString(),
280
+ attempt,
281
+ }),
282
+ signal: controller.signal,
283
+ });
284
+
285
+ clearTimeout(timeoutId);
286
+
287
+ // First check if we got a valid response
288
+ if (!response) {
289
+ throw new Error('No response received from server');
290
+ }
291
+
292
+ // Handle common HTTP errors that indicate server issues
293
+ if (response.status === 502) {
294
+ throw new Error('Onairos API is temporarily unavailable (502 Bad Gateway). Please try again later.');
295
+ }
296
+
297
+ if (response.status === 503) {
298
+ throw new Error('Onairos API is under maintenance (503 Service Unavailable). Please try again later.');
299
+ }
300
+
301
+ if (response.status === 504) {
302
+ throw new Error('Onairos API request timed out (504 Gateway Timeout). Please try again.');
303
+ }
304
+
305
+ // Check if response is actually JSON before trying to parse
306
+ const contentType = response.headers.get('content-type');
307
+ const isJsonResponse = contentType && contentType.includes('application/json');
308
+
309
+ if (!isJsonResponse) {
310
+ const textContent = await response.text();
311
+ const previewText = textContent.substring(0, 200);
312
+
313
+ console.error('❌ API endpoint returned non-JSON response:', {
314
+ status: response.status,
315
+ statusText: response.statusText,
316
+ contentType: contentType || 'unknown',
317
+ preview: previewText,
318
+ url: `${baseUrl}/auth/validate-key`,
319
+ attempt: attempt
320
+ });
321
+
322
+ // Handle specific error cases
323
+ if (response.status === 404) {
324
+ throw new Error(`API validation endpoint not found (404). The endpoint ${baseUrl}/auth/validate-key may not exist or be configured correctly.`);
325
+ } else if (response.status === 500) {
326
+ throw new Error(`Server error (500). The Onairos backend is experiencing issues.`);
327
+ } else if (response.status === 502 || response.status === 503) {
328
+ throw new Error(`Service unavailable (${response.status}). The Onairos backend may be temporarily down.`);
329
+ } else if (textContent.includes('<html') || textContent.includes('<!DOCTYPE')) {
330
+ throw new Error(`Server returned HTML page instead of JSON API response. This often indicates a routing issue or server misconfiguration.`);
331
+ } else {
332
+ throw new Error(`API validation endpoint returned ${response.status} - ${response.statusText}. Expected JSON but got ${contentType || 'unknown content type'}.`);
333
+ }
334
+ }
335
+
336
+ // Parse JSON response
337
+ let data;
338
+ try {
339
+ data = await response.json();
340
+ } catch (jsonError) {
341
+ console.error(' Failed to parse JSON response:', {
342
+ error: jsonError.message,
343
+ status: response.status,
344
+ contentType,
345
+ attempt: attempt
346
+ });
347
+ throw new Error(`Failed to parse server response as JSON: ${jsonError.message}`);
348
+ }
349
+
350
+ // Handle successful response
351
+ if (response.ok && data.success) {
352
+ const result: ApiKeyValidationResult = {
353
+ isValid: true,
354
+ permissions: data.permissions || [],
355
+ rateLimits: data.rateLimits || null,
356
+ keyType: keyType,
357
+ };
358
+
359
+ // Cache the successful result
360
+ validationCache.set(apiKey, {
361
+ result,
362
+ timestamp: Date.now(),
363
+ });
364
+
365
+ if (globalConfig?.enableLogging) {
366
+ console.log('✅ API key validation successful');
367
+ }
368
+
369
+ return result;
370
+ } else {
371
+ // Handle API errors (invalid key, etc.)
372
+ const errorMessage = data.error || data.message || `HTTP ${response.status}: ${response.statusText}`;
373
+
374
+ const result: ApiKeyValidationResult = {
375
+ isValid: false,
376
+ error: errorMessage,
377
+ keyType: keyType,
378
+ };
379
+
380
+ // For client errors (4xx), don't retry
381
+ if (response.status >= 400 && response.status < 500) {
382
+ if (globalConfig?.enableLogging) {
383
+ console.error('❌ API key validation failed (client error):', errorMessage);
384
+ }
385
+ return result;
386
+ }
387
+
388
+ // For server errors (5xx), retry
389
+ throw new Error(errorMessage);
390
+ }
391
+
392
+ } catch (fetchError: any) {
393
+ clearTimeout(timeoutId);
394
+
395
+ if (fetchError.name === 'AbortError') {
396
+ const errorMessage = `API key validation timeout (${timeout}ms)`;
397
+ console.error('⏱️ API key validation timeout');
398
+
399
+ if (attempt === maxRetries) {
400
+ return { isValid: false, error: errorMessage, keyType: keyType };
401
+ }
402
+ continue; // Retry timeout errors
403
+ }
404
+
405
+ // Enhanced error message based on error type
406
+ let errorMessage = `Network error during API key validation: ${fetchError.message}`;
407
+
408
+ // Add specific guidance for common errors
409
+ if (fetchError.message.includes('JSON Parse error') || fetchError.message.includes('Unexpected character')) {
410
+ errorMessage = `Server returned invalid JSON response. This usually indicates the API endpoint returned HTML instead of JSON (often a 404 or server error page). ${fetchError.message}`;
411
+ } else if (fetchError.message.includes('Network request failed') || fetchError.message.includes('fetch')) {
412
+ errorMessage = `Network connectivity issue. Please check internet connection and verify the Onairos API is accessible. ${fetchError.message}`;
413
+ } else if (fetchError.message.includes('DNS') || fetchError.message.includes('ENOTFOUND')) {
414
+ errorMessage = `DNS resolution failed for ${baseUrl}. Please check network settings and domain accessibility. ${fetchError.message}`;
415
+ }
416
+
417
+ console.error('🌐 Network error during API key validation:', {
418
+ error: fetchError,
419
+ endpoint: `${baseUrl}/auth/validate-key`,
420
+ attempt: attempt,
421
+ maxRetries: maxRetries,
422
+ retryable: attempt < maxRetries
423
+ });
424
+
425
+ // If this is the last attempt, return the error
426
+ if (attempt === maxRetries) {
427
+ return {
428
+ isValid: false,
429
+ error: errorMessage,
430
+ keyType: keyType,
431
+ isNetworkError: true // Flag to indicate this is a network issue, not an API key issue
432
+ };
433
+ }
434
+
435
+ // Wait before retrying (exponential backoff)
436
+ const backoffDelay = Math.min(1000 * Math.pow(2, attempt - 1), 5000);
437
+ if (globalConfig?.enableLogging) {
438
+ console.log(`⏳ Waiting ${backoffDelay}ms before retry...`);
439
+ }
440
+ await new Promise<void>(resolve => setTimeout(() => resolve(), backoffDelay));
441
+ }
442
+ }
443
+
444
+ // This should never be reached, but just in case
445
+ return {
446
+ isValid: false,
447
+ error: 'All retry attempts exhausted',
448
+ keyType: keyType
449
+ };
450
+
451
+ } catch (error: any) {
452
+ const errorMessage = `API key validation error: ${error.message}`;
453
+ console.error('❌ API key validation error:', error);
454
+ return { isValid: false, error: errorMessage, keyType: ApiKeyType.INVALID };
455
+ }
456
+ };
457
+
458
+ /**
459
+ * Get the current API configuration
460
+ * @returns Current API configuration or null if not initialized
461
+ */
462
+ export const getApiConfig = (): OnairosConfig | null => {
463
+ return globalConfig;
464
+ };
465
+
466
+ /**
467
+ * Get the current API key
468
+ * @returns Current API key or null if not initialized
469
+ */
470
+ export const getApiKey = (): string | null => {
471
+ return globalConfig?.apiKey || null;
472
+ };
473
+
474
+ /**
475
+ * Check if the SDK is properly initialized
476
+ * @returns True if initialized with valid API key
477
+ */
478
+ export const isApiKeyInitialized = (): boolean => {
479
+ return isInitialized && globalConfig !== null;
480
+ };
481
+
482
+ /**
483
+ * Store JWT token securely after email verification
484
+ * @param token JWT token from email verification response
485
+ */
486
+ export const storeJWT = async (token: string): Promise<void> => {
487
+ try {
488
+ await AsyncStorage.setItem(JWT_TOKEN_KEY, token);
489
+ userToken = token;
490
+
491
+ if (globalConfig?.enableLogging) {
492
+ console.log('🎫 JWT token stored successfully');
493
+ }
494
+ } catch (error) {
495
+ console.error('❌ Failed to store JWT token:', error);
496
+ throw error;
497
+ }
498
+ };
499
+
500
+ /**
501
+ * Load JWT token from storage
502
+ * @returns JWT token or null if not found
503
+ */
504
+ export const loadJWT = async (): Promise<string | null> => {
505
+ try {
506
+ const token = await AsyncStorage.getItem(JWT_TOKEN_KEY);
507
+ userToken = token;
508
+ return token;
509
+ } catch (error) {
510
+ console.error('❌ Failed to load JWT token:', error);
511
+ return null;
512
+ }
513
+ };
514
+
515
+ /**
516
+ * Get current JWT token
517
+ * @returns JWT token or null if not available
518
+ */
519
+ export const getJWT = (): string | null => {
520
+ return userToken;
521
+ };
522
+
523
+ /**
524
+ * Clear JWT token (on logout or token expiration)
525
+ */
526
+ export const clearJWT = async (): Promise<void> => {
527
+ try {
528
+ await AsyncStorage.removeItem(JWT_TOKEN_KEY);
529
+ userToken = null;
530
+
531
+ if (globalConfig?.enableLogging) {
532
+ console.log('🗑️ JWT token cleared');
533
+ }
534
+ } catch (error) {
535
+ console.error('❌ Failed to clear JWT token:', error);
536
+ }
537
+ };
538
+
539
+ /**
540
+ * React Native compatible base64 decoder
541
+ * @param str Base64 encoded string
542
+ * @returns Decoded string
543
+ */
544
+ const base64Decode = (str: string): string => {
545
+ // Simple base64 decoding for React Native
546
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
547
+ let result = '';
548
+ let i = 0;
549
+
550
+ str = str.replace(/[^A-Za-z0-9+/]/g, '');
551
+
552
+ while (i < str.length) {
553
+ const a = chars.indexOf(str.charAt(i++));
554
+ const b = chars.indexOf(str.charAt(i++));
555
+ const c = chars.indexOf(str.charAt(i++));
556
+ const d = chars.indexOf(str.charAt(i++));
557
+
558
+ const bitmap = (a << 18) | (b << 12) | (c << 6) | d;
559
+
560
+ result += String.fromCharCode((bitmap >> 16) & 255);
561
+ if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
562
+ if (d !== 64) result += String.fromCharCode(bitmap & 255);
563
+ }
564
+
565
+ return result;
566
+ };
567
+
568
+ /**
569
+ * Decode JWT token payload (React Native compatible)
570
+ * @param token JWT token string
571
+ * @returns Decoded payload or null if invalid
572
+ */
573
+ export const decodeJWTPayload = (token: string): any => {
574
+ try {
575
+ // Split JWT token (header.payload.signature)
576
+ const parts = token.split('.');
577
+ if (parts.length !== 3) {
578
+ console.error('❌ Invalid JWT token format');
579
+ return null;
580
+ }
581
+
582
+ // Decode payload (base64url to base64)
583
+ const payload = parts[1];
584
+ const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
585
+
586
+ // Add padding if needed
587
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=');
588
+
589
+ // Decode base64 to JSON using React Native compatible decoder
590
+ const decoded = base64Decode(padded);
591
+ return JSON.parse(decoded);
592
+ } catch (error) {
593
+ console.error('❌ Failed to decode JWT token:', error);
594
+ return null;
595
+ }
596
+ };
597
+
598
+ /**
599
+ * Extract username from JWT token
600
+ * @param token JWT token (optional, uses stored token if not provided)
601
+ * @returns Username or null if not found
602
+ */
603
+ export const extractUsernameFromJWT = (token?: string): string | null => {
604
+ try {
605
+ const jwtToken = token || userToken;
606
+ if (!jwtToken) {
607
+ console.warn('⚠️ No JWT token available for username extraction');
608
+ return null;
609
+ }
610
+
611
+ const payload = decodeJWTPayload(jwtToken);
612
+ if (!payload) {
613
+ return null;
614
+ }
615
+
616
+ // Try different possible username fields in order of preference
617
+ const username = payload.userName || payload.username || payload.userId || payload.email;
618
+
619
+ if (globalConfig?.enableLogging) {
620
+ console.log('👤 Extracted username from JWT:', username);
621
+ }
622
+
623
+ return username || null;
624
+ } catch (error) {
625
+ console.error('❌ Failed to extract username from JWT:', error);
626
+ return null;
627
+ }
628
+ };
629
+
630
+ /**
631
+ * Extract user data from JWT token
632
+ * @param token JWT token (optional, uses stored token if not provided)
633
+ * @returns User data object or null if not found
634
+ */
635
+ export const extractUserDataFromJWT = (token?: string): any => {
636
+ try {
637
+ const jwtToken = token || userToken;
638
+ if (!jwtToken) {
639
+ console.warn('⚠️ No JWT token available for user data extraction');
640
+ return null;
641
+ }
642
+
643
+ const payload = decodeJWTPayload(jwtToken);
644
+ if (!payload) {
645
+ return null;
646
+ }
647
+
648
+ const userData = {
649
+ id: payload.id,
650
+ email: payload.email,
651
+ userId: payload.userId,
652
+ userName: payload.userName || payload.username,
653
+ verified: payload.verified,
654
+ iat: payload.iat,
655
+ exp: payload.exp
656
+ };
657
+
658
+ if (globalConfig?.enableLogging) {
659
+ console.log('👤 Extracted user data from JWT:', userData);
660
+ }
661
+
662
+ return userData;
663
+ } catch (error) {
664
+ console.error('❌ Failed to extract user data from JWT:', error);
665
+ return null;
666
+ }
667
+ };
668
+
669
+ /**
670
+ * Check if user is authenticated with JWT token
671
+ * @returns True if user has valid JWT token
672
+ */
673
+ export const isUserAuthenticated = (): boolean => {
674
+ return !!userToken;
675
+ };
676
+
677
+ /**
678
+ * Get authenticated headers for API requests
679
+ * @returns Headers object with Authorization and other required headers
680
+ */
681
+ export const getAuthHeaders = (): Record<string, string> => {
682
+ if (!globalConfig?.apiKey) {
683
+ throw new Error('SDK not initialized. Call initializeApiKey() first.');
684
+ }
685
+
686
+ const keyType = getApiKeyType(globalConfig.apiKey);
687
+
688
+ return {
689
+ 'Content-Type': 'application/json',
690
+ 'Authorization': `Bearer ${globalConfig.apiKey}`,
691
+ 'User-Agent': 'OnairosReactNative/3.0.72',
692
+ 'X-SDK-Version': '3.0.72',
693
+ 'X-SDK-Environment': globalConfig.environment || 'production',
694
+ 'X-API-Key-Type': keyType,
695
+ 'X-Timestamp': new Date().toISOString(),
696
+ };
697
+ };
698
+
699
+ /**
700
+ * Get authentication headers for developer API requests
701
+ * @returns Headers with developer API key
702
+ */
703
+ export const getDeveloperAuthHeaders = (): Record<string, string> => {
704
+ if (!globalConfig?.apiKey) {
705
+ throw new Error('SDK not initialized. Call initializeApiKey() first.');
706
+ }
707
+
708
+ const keyType = getApiKeyType(globalConfig.apiKey);
709
+
710
+ return {
711
+ 'Content-Type': 'application/json',
712
+ 'Authorization': `Bearer ${globalConfig.apiKey}`,
713
+ 'User-Agent': 'OnairosSDK/1.0.0',
714
+ 'X-SDK-Version': '3.0.72',
715
+ 'X-SDK-Environment': globalConfig.environment || 'production',
716
+ 'X-API-Key-Type': keyType,
717
+ 'X-Timestamp': new Date().toISOString(),
718
+ };
719
+ };
720
+
721
+ /**
722
+ * Get authentication headers for user JWT requests
723
+ * @returns Headers with user JWT token
724
+ */
725
+ export const getUserAuthHeaders = (): Record<string, string> => {
726
+ if (!userToken) {
727
+ throw new Error('User not authenticated. Please verify email first.');
728
+ }
729
+
730
+ return {
731
+ 'Content-Type': 'application/json',
732
+ 'Authorization': `Bearer ${userToken}`,
733
+ 'User-Agent': 'OnairosSDK/1.0.0',
734
+ 'X-SDK-Version': '3.0.72',
735
+ 'X-SDK-Environment': globalConfig?.environment || 'production',
736
+ };
737
+ };
738
+
739
+ /**
740
+ * Make an authenticated API request
741
+ * @param endpoint The API endpoint (relative to base URL)
742
+ * @param options Fetch options
743
+ * @returns Response promise
744
+ */
745
+ export const makeAuthenticatedRequest = async (
746
+ endpoint: string,
747
+ options: RequestInit = {}
748
+ ): Promise<Response> => {
749
+ if (!isApiKeyInitialized()) {
750
+ throw new Error('SDK not initialized. Call initializeApiKey() first.');
751
+ }
752
+
753
+ const config = getApiConfig()!;
754
+ const baseUrl = API_ENDPOINTS[config.environment || 'production'];
755
+ const url = `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
756
+
757
+ // Merge authentication headers
758
+ const headers = {
759
+ ...getAuthHeaders(),
760
+ ...(options.headers || {}),
761
+ };
762
+
763
+ // Add timeout
764
+ const controller = new AbortController();
765
+ const timeoutId = setTimeout(() => controller.abort(), config.timeout || 30000);
766
+
767
+ try {
768
+ if (config.enableLogging) {
769
+ console.log(`🌐 Making authenticated request to: ${endpoint}`);
770
+ }
771
+
772
+ const response = await fetch(url, {
773
+ ...options,
774
+ headers,
775
+ signal: controller.signal,
776
+ });
777
+
778
+ clearTimeout(timeoutId);
779
+
780
+ if (config.enableLogging) {
781
+ console.log(`📡 Response status: ${response.status} for ${endpoint}`);
782
+ }
783
+
784
+ // Handle API key errors
785
+ if (response.status === 401) {
786
+ console.error('❌ API key authentication failed. Please check your API key.');
787
+ throw new Error('Invalid or expired API key');
788
+ }
789
+
790
+ if (response.status === 403) {
791
+ console.error('❌ API key permissions insufficient for this operation.');
792
+ throw new Error('Insufficient API key permissions');
793
+ }
794
+
795
+ if (response.status === 429) {
796
+ console.error('❌ API rate limit exceeded. Please try again later.');
797
+ throw new Error('Rate limit exceeded');
798
+ }
799
+
800
+ return response;
801
+ } catch (error) {
802
+ clearTimeout(timeoutId);
803
+
804
+ if (error.name === 'AbortError') {
805
+ console.error('⏱️ Request timeout for:', endpoint);
806
+ throw new Error('Request timeout');
807
+ }
808
+
809
+ throw error;
810
+ }
811
+ };
812
+
813
+ /**
814
+ * Make authenticated request with developer API key
815
+ * @param endpoint The API endpoint
816
+ * @param options Fetch options
817
+ * @returns Response promise
818
+ */
819
+ export const makeDeveloperRequest = async (
820
+ endpoint: string,
821
+ options: RequestInit = {}
822
+ ): Promise<Response> => {
823
+ if (!isApiKeyInitialized()) {
824
+ throw new Error('SDK not initialized. Call initializeApiKey() first.');
825
+ }
826
+
827
+ const config = getApiConfig()!;
828
+ const baseUrl = API_ENDPOINTS[config.environment || 'production'];
829
+ const url = `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
830
+
831
+ // Merge developer authentication headers
832
+ const headers = {
833
+ ...getDeveloperAuthHeaders(),
834
+ ...(options.headers || {}),
835
+ };
836
+
837
+ // Add timeout
838
+ const controller = new AbortController();
839
+ const timeoutId = setTimeout(() => controller.abort(), config.timeout || 30000);
840
+
841
+ try {
842
+ if (config.enableLogging) {
843
+ console.log(`🌐 Making developer request to: ${endpoint}`);
844
+ }
845
+
846
+ const response = await fetch(url, {
847
+ ...options,
848
+ headers,
849
+ signal: controller.signal,
850
+ });
851
+
852
+ clearTimeout(timeoutId);
853
+
854
+ if (config.enableLogging) {
855
+ console.log(`📡 Developer request response: ${response.status} for ${endpoint}`);
856
+ }
857
+
858
+ // Handle API key errors
859
+ if (response.status === 401) {
860
+ console.error('❌ Developer API key authentication failed');
861
+ throw new Error('Invalid or expired API key');
862
+ }
863
+
864
+ if (response.status === 403) {
865
+ console.error('❌ Developer API key permissions insufficient');
866
+ throw new Error('Insufficient API key permissions');
867
+ }
868
+
869
+ if (response.status === 429) {
870
+ console.error('❌ API rate limit exceeded');
871
+ throw new Error('Rate limit exceeded');
872
+ }
873
+
874
+ return response;
875
+ } catch (error) {
876
+ clearTimeout(timeoutId);
877
+
878
+ if (error.name === 'AbortError') {
879
+ console.error('⏱️ Request timeout for:', endpoint);
880
+ throw new Error('Request timeout');
881
+ }
882
+
883
+ throw error;
884
+ }
885
+ };
886
+
887
+ /**
888
+ * Make authenticated request with user JWT token
889
+ * @param endpoint The API endpoint
890
+ * @param options Fetch options
891
+ * @returns Response promise
892
+ */
893
+ export const makeUserRequest = async (
894
+ endpoint: string,
895
+ options: RequestInit = {}
896
+ ): Promise<Response> => {
897
+ if (!isUserAuthenticated()) {
898
+ await loadJWT(); // Try to load from storage
899
+ }
900
+
901
+ if (!isUserAuthenticated()) {
902
+ throw new Error('User not authenticated. Please verify email first.');
903
+ }
904
+
905
+ const config = getApiConfig() || { environment: 'production', timeout: 30000, enableLogging: false };
906
+ const baseUrl = API_ENDPOINTS[config.environment || 'production'];
907
+ const url = `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
908
+
909
+ // Merge user authentication headers
910
+ const headers = {
911
+ ...getUserAuthHeaders(),
912
+ ...(options.headers || {}),
913
+ };
914
+
915
+ // Add timeout
916
+ const controller = new AbortController();
917
+ const timeoutId = setTimeout(() => controller.abort(), config.timeout || 30000);
918
+
919
+ try {
920
+ if (config.enableLogging) {
921
+ console.log(`🌐 Making user request to: ${endpoint}`);
922
+ }
923
+
924
+ const response = await fetch(url, {
925
+ ...options,
926
+ headers,
927
+ signal: controller.signal,
928
+ });
929
+
930
+ clearTimeout(timeoutId);
931
+
932
+ if (config.enableLogging) {
933
+ console.log(`📡 User request response: ${response.status} for ${endpoint}`);
934
+ }
935
+
936
+ // Handle JWT token errors
937
+ if (response.status === 401) {
938
+ console.error('❌ JWT token authentication failed - token may be expired');
939
+ await clearJWT(); // Clear expired token
940
+ throw new Error('Authentication expired. Please verify email again.');
941
+ }
942
+
943
+ if (response.status === 403) {
944
+ console.error('❌ JWT token permissions insufficient');
945
+ throw new Error('Insufficient permissions for this operation');
946
+ }
947
+
948
+ return response;
949
+ } catch (error) {
950
+ clearTimeout(timeoutId);
951
+
952
+ if (error.name === 'AbortError') {
953
+ console.error('⏱️ Request timeout for:', endpoint);
954
+ throw new Error('Request timeout');
955
+ }
956
+
957
+ throw error;
958
+ }
959
+ };
960
+
961
+ /**
962
+ * Clear the API key validation cache
963
+ */
964
+ export const clearValidationCache = (): void => {
965
+ validationCache.clear();
966
+ if (globalConfig?.enableLogging) {
967
+ console.log('🗑️ API key validation cache cleared');
968
+ }
969
+ };
970
+
971
+ /**
972
+ * Reset the SDK initialization state
973
+ */
974
+ export const resetApiKeyService = (): void => {
975
+ globalConfig = null;
976
+ isInitialized = false;
977
+ clearValidationCache();
978
+ console.log('🔄 API key service reset');
922
979
  };