@onairos/react-native 3.1.16 → 3.1.17

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