@onairosofficial/onairos-capacitor 0.1.0 → 0.1.1

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 (181) hide show
  1. package/LICENSE +194 -10
  2. package/README.md +182 -25
  3. package/dist/onairos.capacitor.esm.js +1 -0
  4. package/dist/onairos.capacitor.esm.turbopack.js +1 -0
  5. package/onairos.d.ts +656 -0
  6. package/package.json +186 -38
  7. package/src/OnairosReconnectButton.jsx +272 -0
  8. package/src/RSA.jsx +57 -0
  9. package/src/assets/NewLogo.png +0 -0
  10. package/src/assets/OnairosNewLogo.png +0 -0
  11. package/src/assets/chatgpt-icon.png +0 -0
  12. package/src/assets/fire-horse.png +0 -0
  13. package/src/assets/fire-horse.transparent.png +0 -0
  14. package/src/assets/latest-firehorse.png +0 -0
  15. package/src/assets/perplexity.png +0 -0
  16. package/src/assets/persona.png +0 -0
  17. package/src/assets/persona1.png +0 -0
  18. package/src/assets/persona2.png +0 -0
  19. package/src/assets/persona3.png +0 -0
  20. package/src/assets/persona4.png +0 -0
  21. package/src/assets/persona5.png +0 -0
  22. package/src/capacitorConnectorCatalog.js +38 -0
  23. package/src/capacitorOAuthConfig.js +52 -0
  24. package/src/chatgptHostedImport/index.js +303 -0
  25. package/src/components/AuthButtons.jsx +48 -0
  26. package/src/components/ConnectChatGPTModal.jsx +666 -0
  27. package/src/components/ConnectClaudeModal.jsx +610 -0
  28. package/src/components/ConnectGeminiModal.jsx +639 -0
  29. package/src/components/ConnectGrokModal.jsx +701 -0
  30. package/src/components/ConnectPerplexityModal.jsx +726 -0
  31. package/src/components/DataExplainerScreen.jsx +349 -0
  32. package/src/components/DataRequest.js +885 -0
  33. package/src/components/DataRequest.jsx +1055 -0
  34. package/src/components/EmailAuth.js +1871 -0
  35. package/src/components/EmailAuth.jsx +2062 -0
  36. package/src/components/ExtensionInstallPrompt.jsx +142 -0
  37. package/src/components/GoogleButton.js +133 -0
  38. package/src/components/LLMConnectorManager.jsx +201 -0
  39. package/src/components/LoadingPage.jsx +19 -0
  40. package/src/components/LoadingScreen.jsx +81 -0
  41. package/src/components/LunarBirthdate.jsx +96 -0
  42. package/src/components/LunarLoadingPage.jsx +251 -0
  43. package/src/components/Notification.jsx +21 -0
  44. package/src/components/OnairosAppButton.jsx +85 -0
  45. package/src/components/OnairosSSO.jsx +645 -0
  46. package/src/components/OnairosTrigger.jsx +61 -0
  47. package/src/components/PerplexityLogo.jsx +43 -0
  48. package/src/components/PinSetup.js +200 -0
  49. package/src/components/PinSetup.jsx +228 -0
  50. package/src/components/SDK_PIN_INTEGRATION_REQUIRED_CHANGES.md +526 -0
  51. package/src/components/SdkErrorBoundary.jsx +36 -0
  52. package/src/components/SecuritySetup.js +81 -0
  53. package/src/components/SessionUserBar.jsx +83 -0
  54. package/src/components/SignUp.js +123 -0
  55. package/src/components/TestTelegramButton.js +53 -0
  56. package/src/components/TrainingComponent.jsx +200 -0
  57. package/src/components/TrainingScreen.jsx +897 -0
  58. package/src/components/UniversalOnboarding.js +306 -0
  59. package/src/components/UniversalOnboarding.jsx +4837 -0
  60. package/src/components/ValentineLoadingPage.jsx +502 -0
  61. package/src/components/ValentineModeSelector.jsx +162 -0
  62. package/src/components/WelcomeScreen.jsx +435 -0
  63. package/src/components/WrappedLoadingPage.jsx +205 -0
  64. package/src/components/connectors/ChatGPTConnector.js +348 -0
  65. package/src/components/connectors/ChatGPTConnector.jsx +348 -0
  66. package/src/components/connectors/ClaudeConnector.js +44 -0
  67. package/src/components/connectors/ClaudeConnector.jsx +44 -0
  68. package/src/components/connectors/GeminiConnector.js +170 -0
  69. package/src/components/connectors/GeminiConnector.jsx +170 -0
  70. package/src/components/connectors/GmailConnector.js +148 -0
  71. package/src/components/connectors/GmailConnector.jsx +148 -0
  72. package/src/components/connectors/GrokConnector.js +16 -0
  73. package/src/components/connectors/GrokConnector.jsx +16 -0
  74. package/src/components/connectors/HingeConnector.js +419 -0
  75. package/src/components/connectors/HingeConnector.jsx +419 -0
  76. package/src/components/connectors/InstagramDataConnector.js +726 -0
  77. package/src/components/connectors/InstagramDataConnector.jsx +726 -0
  78. package/src/components/connectors/LinkedInConnector.js +4 -0
  79. package/src/components/connectors/LinkedInConnector.jsx +296 -0
  80. package/src/components/connectors/PerplexityConnector.jsx +16 -0
  81. package/src/components/connectors/PinterestConnector.js +208 -0
  82. package/src/components/connectors/PinterestConnector.jsx +208 -0
  83. package/src/components/connectors/README.md +292 -0
  84. package/src/components/connectors/RedditConnector.js +229 -0
  85. package/src/components/connectors/RedditConnector.jsx +229 -0
  86. package/src/components/connectors/SephoraConnector.js +482 -0
  87. package/src/components/connectors/SephoraConnector.jsx +482 -0
  88. package/src/components/connectors/TikTokConnector.jsx +430 -0
  89. package/src/components/connectors/YoutubeConnector.js +361 -0
  90. package/src/components/connectors/YoutubeConnector.jsx +361 -0
  91. package/src/components/connectors/index.js +50 -0
  92. package/src/components/icons.jsx +46 -0
  93. package/src/components/icons.tsx +21 -0
  94. package/src/components/ui/PageLayout.jsx +1255 -0
  95. package/src/components/ui/PrimaryButton.jsx +162 -0
  96. package/src/components/ui/button.jsx +49 -0
  97. package/src/components/ui/card.jsx +61 -0
  98. package/src/components/ui/checkbox.jsx +33 -0
  99. package/src/components/ui/label.jsx +29 -0
  100. package/src/components/utils/UpdateConnections.js +45 -0
  101. package/src/components/utils/oauthHelper.js +97 -0
  102. package/src/config/api-config.js +138 -0
  103. package/src/deepLink.jsx +38 -0
  104. package/src/getPin.js +26 -0
  105. package/src/icons/Avatar.png +0 -0
  106. package/src/icons/Sentiment.png +0 -0
  107. package/src/icons/Trait.png +0 -0
  108. package/src/iframe/DataRequestPage.jsx +285 -0
  109. package/src/iframe/OnairosButtonIntegration.md +148 -0
  110. package/src/iframe/components/Box.jsx +56 -0
  111. package/src/iframe/components/IndividualConnection.jsx +88 -0
  112. package/src/iframe/dataRequestHandler.js +714 -0
  113. package/src/iframe/data_request_iframe.html +27 -0
  114. package/src/iframe/data_request_page.js +47 -0
  115. package/src/iframe/icons/Avatar.png +1 -0
  116. package/src/iframe/icons/Avatar2.png +1 -0
  117. package/src/iframe/icons/Sentiment.png +1 -0
  118. package/src/iframe/icons/Trait.png +1 -0
  119. package/src/iframe/icons/onairos_logo.png +0 -0
  120. package/src/iframe/utils/api.js +57 -0
  121. package/src/index.js +274 -0
  122. package/src/laravel/OnairosVue.vue +410 -0
  123. package/src/laravel/blade-helpers.js +320 -0
  124. package/src/laravel/vite-plugin.js +179 -0
  125. package/src/mobile/MobileDataRequestPage.jsx +233 -0
  126. package/src/mobile/components/MobileBox.jsx +71 -0
  127. package/src/mobile/components/MobileIndividualConnection.jsx +51 -0
  128. package/src/mobile/shims/browser-apis.js +78 -0
  129. package/src/mobile/shims/lucide-shim.js +85 -0
  130. package/src/newUI/EMAIL_VERIFICATION_API_SCHEMA.md +268 -0
  131. package/src/newUI/PlatformConnectorsStep.tsx +435 -0
  132. package/src/newUI/PrimaryButton.tsx +213 -0
  133. package/src/newUI/SignInStep.tsx +194 -0
  134. package/src/newUI/VerificationStep.tsx +133 -0
  135. package/src/newUI/WelcomeScreen.tsx +311 -0
  136. package/src/newUI/services/connectedAccountsService.js +129 -0
  137. package/src/onairos.capacitor.jsx +16 -0
  138. package/src/onairos.core.jsx +133 -0
  139. package/src/onairos.jsx +14 -0
  140. package/src/onairos.native.jsx +15 -0
  141. package/src/onairosButton.jsx +9000 -0
  142. package/src/overlay/CheckBox.jsx +114 -0
  143. package/src/overlay/IndividualConnection copy.js +86 -0
  144. package/src/overlay/IndividualConnection.js +191 -0
  145. package/src/overlay/IndividualConnectionNew.jsx +157 -0
  146. package/src/overlay/box.js +84 -0
  147. package/src/overlay/overlay.js +437 -0
  148. package/src/styles/onairos-scoped-preflight.css +97 -0
  149. package/src/styles/sdkCssRegistry.js +20 -0
  150. package/src/styles/styleLoaderInsertShadow.js +69 -0
  151. package/src/styles/tailwind.capacitor.css +395 -0
  152. package/src/styles/tailwind.css +395 -0
  153. package/src/theme/colors.js +40 -0
  154. package/src/utils/apiKeyValidation.js +341 -0
  155. package/src/utils/apiResponseLogger.js +316 -0
  156. package/src/utils/authHeaders.js +275 -0
  157. package/src/utils/biometrics.js +26 -0
  158. package/src/utils/bookmarkletUtils.js +28 -0
  159. package/src/utils/capacitorDetection.js +278 -0
  160. package/src/utils/capacitorLLMHelper.js +352 -0
  161. package/src/utils/capacitorPlugins.js +366 -0
  162. package/src/utils/crossDomainSSO.js +587 -0
  163. package/src/utils/deepLinking.js +27 -0
  164. package/src/utils/devLogger.js +46 -0
  165. package/src/utils/extensionDetection.js +418 -0
  166. package/src/utils/extractMemory.js +277 -0
  167. package/src/utils/framerBrandingOverrides.js +40 -0
  168. package/src/utils/googleWebClientId.js +55 -0
  169. package/src/utils/overlayHandler.js +224 -0
  170. package/src/utils/platformDisconnect.js +309 -0
  171. package/src/utils/pollTrainingStatus.js +200 -0
  172. package/src/utils/rawMemoriesAccess.js +211 -0
  173. package/src/utils/resolveBackendAppId.js +47 -0
  174. package/src/utils/responseFormatter.js +140 -0
  175. package/src/utils/sdkDebugStorage.js +113 -0
  176. package/src/utils/sdkInitialization.js +645 -0
  177. package/src/utils/sessionManager.js +1258 -0
  178. package/src/utils/startBackgroundTraining.js +100 -0
  179. package/src/utils/userDataFormatter.js +222 -0
  180. package/index.d.ts +0 -1
  181. package/index.js +0 -1
@@ -0,0 +1,587 @@
1
+ /**
2
+ * Cross-Domain SSO Service for Onairos Apps
3
+ * Provides Google-like seamless authentication across Onairos subdomains:
4
+ * - love.onairos.uk (Valentine)
5
+ * - lunar.onairos.uk (Lunar New Year)
6
+ * - unwrap.onairos.uk (Wrapped)
7
+ * - onairos.uk (Main site)
8
+ *
9
+ * Security Features:
10
+ * - Token rotation on each SSO verification
11
+ * - Short-lived SSO tokens (5 minutes) for cross-domain transfer
12
+ * - Cryptographic nonce for replay attack prevention
13
+ * - Device fingerprint binding
14
+ * - Token refresh with sliding expiration
15
+ */
16
+
17
+ import { API_CONFIG } from '../config/api-config.js';
18
+ import {
19
+ checkValidSession,
20
+ createSession,
21
+ getStoredToken,
22
+ validateToken,
23
+ destroySession
24
+ } from './sessionManager.js';
25
+
26
+ // SSO Configuration
27
+ const SSO_CONFIG = {
28
+ // Onairos app domains that share SSO (cookie-based, same parent domain)
29
+ ONAIROS_DOMAINS: [
30
+ 'onairos.uk',
31
+ 'love.onairos.uk',
32
+ 'lunar.onairos.uk',
33
+ 'unwrap.onairos.uk',
34
+ 'internship.onairos.uk',
35
+ 'www.onairos.uk',
36
+ // Additional Onairos domains
37
+ 'onairos.io',
38
+ 'www.onairos.io'
39
+ ],
40
+
41
+ // Partner domains that use API-based cross-site SSO
42
+ // These domains cannot share cookies but can verify sessions via API
43
+ // The backend must whitelist these origins for CORS with credentials
44
+ PARTNER_DOMAINS: [
45
+ // Add partner app domains here
46
+ // 'partner-app.com',
47
+ // 'example.com',
48
+ ],
49
+
50
+ // SSO transfer token lifetime (5 minutes - short for security)
51
+ TRANSFER_TOKEN_LIFETIME: 5 * 60 * 1000,
52
+
53
+ // Token refresh threshold (refresh when less than 7 days remaining)
54
+ REFRESH_THRESHOLD_DAYS: 7,
55
+
56
+ // SSO verification endpoints
57
+ SSO_VERIFY_ENDPOINT: '/sso/verify',
58
+ SSO_REFRESH_ENDPOINT: '/sso/refresh',
59
+ SSO_TRANSFER_ENDPOINT: '/sso/transfer-token',
60
+ // Cross-site session check (for third-party partner sites)
61
+ CROSS_SITE_CHECK_ENDPOINT: '/auth/check-session',
62
+
63
+ // Cookie configuration for cross-domain
64
+ SSO_COOKIE_NAME: 'onairos_sso_session',
65
+ SSO_NONCE_COOKIE: 'onairos_sso_nonce',
66
+
67
+ // Parent domain for shared cookies (*.onairos.uk only)
68
+ PARENT_DOMAIN: '.onairos.uk',
69
+
70
+ // Storage keys
71
+ STORAGE_KEYS: {
72
+ SSO_TOKEN: 'onairos_sso_token',
73
+ SSO_NONCE: 'onairos_sso_nonce',
74
+ SSO_VERIFIED_AT: 'onairos_sso_verified_at',
75
+ SSO_DEVICE_ID: 'onairos_sso_device_id',
76
+ SSO_REFRESH_TOKEN: 'onairos_sso_refresh_token'
77
+ }
78
+ };
79
+
80
+ /**
81
+ * Check if current domain is an Onairos app
82
+ * @returns {boolean}
83
+ */
84
+ export function isOnairosApp() {
85
+ if (typeof window === 'undefined') return false;
86
+
87
+ const hostname = window.location.hostname;
88
+
89
+ // Check exact match or subdomain of onairos.uk or onairos.io
90
+ return SSO_CONFIG.ONAIROS_DOMAINS.includes(hostname) ||
91
+ hostname.endsWith('.onairos.uk') ||
92
+ hostname.endsWith('.onairos.io') ||
93
+ hostname === 'onairos.io' ||
94
+ hostname === 'localhost' || // Dev support
95
+ hostname === '127.0.0.1';
96
+ }
97
+
98
+ /**
99
+ * Check if current domain is a partner app (not onairos.uk/io subdomain)
100
+ * Partner apps use API-based cross-site SSO instead of cookie-based
101
+ * @returns {boolean}
102
+ */
103
+ export function isPartnerApp() {
104
+ if (typeof window === 'undefined') return false;
105
+
106
+ const hostname = window.location.hostname;
107
+
108
+ // If it's an Onairos domain, it's not a partner app
109
+ if (isOnairosApp()) return false;
110
+
111
+ // Any other domain embedding the SDK is a potential partner app
112
+ // The backend decides via CORS whitelist whether to allow the request
113
+ return true;
114
+ }
115
+
116
+ /**
117
+ * Get the specific Onairos app name from the domain
118
+ * @returns {string|null} 'love' | 'lunar' | 'unwrap' | 'main' | 'partner' | null
119
+ */
120
+ export function getOnairosAppType() {
121
+ if (typeof window === 'undefined') return null;
122
+
123
+ const hostname = window.location.hostname;
124
+
125
+ if (hostname.startsWith('love.')) return 'love';
126
+ if (hostname.startsWith('lunar.')) return 'lunar';
127
+ if (hostname.startsWith('unwrap.')) return 'unwrap';
128
+ if (hostname.startsWith('internship.')) return 'internship';
129
+ if (hostname === 'onairos.uk' || hostname === 'www.onairos.uk') return 'main';
130
+ if (hostname === 'onairos.io' || hostname === 'www.onairos.io') return 'main-io';
131
+ if (hostname === 'localhost' || hostname === '127.0.0.1') return 'dev';
132
+
133
+ // Partner/third-party site
134
+ if (isPartnerApp()) return 'partner';
135
+
136
+ return null;
137
+ }
138
+
139
+ /**
140
+ * Generate a cryptographic nonce for SSO security
141
+ * @returns {string} Base64 encoded nonce
142
+ */
143
+ function generateNonce() {
144
+ const array = new Uint8Array(32);
145
+ crypto.getRandomValues(array);
146
+ return btoa(String.fromCharCode.apply(null, array));
147
+ }
148
+
149
+ /**
150
+ * Generate a device fingerprint for binding tokens
151
+ * @returns {string} Device identifier hash
152
+ */
153
+ function getDeviceFingerprint() {
154
+ try {
155
+ // Check for existing device ID
156
+ let deviceId = localStorage.getItem(SSO_CONFIG.STORAGE_KEYS.SSO_DEVICE_ID);
157
+ if (deviceId) return deviceId;
158
+
159
+ // Generate new device fingerprint
160
+ const components = [
161
+ navigator.userAgent,
162
+ navigator.language,
163
+ new Date().getTimezoneOffset().toString(),
164
+ screen.width + 'x' + screen.height,
165
+ screen.colorDepth?.toString() || '24'
166
+ ];
167
+
168
+ // Simple hash function
169
+ const hash = components.join('|').split('').reduce((a, b) => {
170
+ a = ((a << 5) - a) + b.charCodeAt(0);
171
+ return a & a;
172
+ }, 0);
173
+
174
+ deviceId = 'dev_' + Math.abs(hash).toString(36) + '_' + Date.now().toString(36);
175
+
176
+ try {
177
+ localStorage.setItem(SSO_CONFIG.STORAGE_KEYS.SSO_DEVICE_ID, deviceId);
178
+ } catch (e) {}
179
+
180
+ return deviceId;
181
+ } catch (e) {
182
+ return 'dev_fallback_' + Date.now().toString(36);
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Set a cross-domain cookie on the parent .onairos.uk domain
188
+ * @param {string} name - Cookie name
189
+ * @param {string} value - Cookie value
190
+ * @param {number} maxAgeMs - Max age in milliseconds
191
+ */
192
+ function setCrossDomainCookie(name, value, maxAgeMs) {
193
+ try {
194
+ const expires = new Date(Date.now() + maxAgeMs);
195
+ const isSecure = window.location.protocol === 'https:';
196
+
197
+ let cookieString = `${name}=${encodeURIComponent(value)}`;
198
+ cookieString += `; expires=${expires.toUTCString()}`;
199
+ cookieString += `; max-age=${Math.floor(maxAgeMs / 1000)}`;
200
+ cookieString += `; path=/`;
201
+
202
+ // Set on parent domain for cross-subdomain access
203
+ if (!window.location.hostname.includes('localhost')) {
204
+ cookieString += `; domain=${SSO_CONFIG.PARENT_DOMAIN}`;
205
+ }
206
+
207
+ if (isSecure) {
208
+ cookieString += '; Secure';
209
+ }
210
+
211
+ // SameSite=None is needed for cross-subdomain cookies with Secure
212
+ cookieString += isSecure ? '; SameSite=None' : '; SameSite=Lax';
213
+
214
+ document.cookie = cookieString;
215
+ console.log(`🍪 [SSO] Set cross-domain cookie: ${name}`);
216
+ } catch (e) {
217
+ console.warn('⚠️ [SSO] Failed to set cross-domain cookie:', e);
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Get a cookie value
223
+ * @param {string} name - Cookie name
224
+ * @returns {string|null}
225
+ */
226
+ function getCookie(name) {
227
+ try {
228
+ const nameEQ = name + '=';
229
+ const ca = document.cookie.split(';');
230
+ for (let c of ca) {
231
+ while (c.charAt(0) === ' ') c = c.substring(1);
232
+ if (c.indexOf(nameEQ) === 0) {
233
+ return decodeURIComponent(c.substring(nameEQ.length));
234
+ }
235
+ }
236
+ return null;
237
+ } catch (e) {
238
+ return null;
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Delete a cross-domain cookie
244
+ * @param {string} name - Cookie name
245
+ */
246
+ function deleteCrossDomainCookie(name) {
247
+ try {
248
+ document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
249
+ if (!window.location.hostname.includes('localhost')) {
250
+ document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${SSO_CONFIG.PARENT_DOMAIN}`;
251
+ }
252
+ } catch (e) {}
253
+ }
254
+
255
+ /**
256
+ * Check if there's an existing SSO session that can be used
257
+ * This checks both localStorage (same domain) and cookies (cross-domain)
258
+ * @returns {Object} { hasSSO: boolean, needsVerification: boolean, userData: object|null }
259
+ */
260
+ export function checkSSOSession() {
261
+ console.log('🔐 [SSO] Checking for existing SSO session...');
262
+
263
+ if (!isOnairosApp()) {
264
+ console.log('📍 [SSO] Not on Onairos app domain');
265
+ return { hasSSO: false, needsVerification: false, userData: null };
266
+ }
267
+
268
+ // First check localStorage (same domain session)
269
+ const localSession = checkValidSession();
270
+ if (localSession.shouldSkipLogin && localSession.userData) {
271
+ console.log('✅ [SSO] Found valid local session');
272
+ return {
273
+ hasSSO: true,
274
+ needsVerification: shouldReVerifySession(localSession.userData),
275
+ userData: localSession.userData
276
+ };
277
+ }
278
+
279
+ // Check cross-domain SSO cookie
280
+ const ssoCookie = getCookie(SSO_CONFIG.SSO_COOKIE_NAME);
281
+ if (ssoCookie) {
282
+ console.log('🍪 [SSO] Found cross-domain SSO cookie');
283
+ try {
284
+ const ssoData = JSON.parse(ssoCookie);
285
+ if (ssoData.token && ssoData.email) {
286
+ return {
287
+ hasSSO: true,
288
+ needsVerification: true, // Always verify cross-domain tokens
289
+ userData: ssoData
290
+ };
291
+ }
292
+ } catch (e) {
293
+ console.warn('⚠️ [SSO] Failed to parse SSO cookie:', e);
294
+ }
295
+ }
296
+
297
+ console.log('❌ [SSO] No SSO session found');
298
+ return { hasSSO: false, needsVerification: false, userData: null };
299
+ }
300
+
301
+ /**
302
+ * Check if the session should be re-verified with the server
303
+ * Similar to Google's silent re-authentication
304
+ * @param {Object} userData - Current user data
305
+ * @returns {boolean}
306
+ */
307
+ function shouldReVerifySession(userData) {
308
+ try {
309
+ // If no last verification time, needs verification
310
+ const lastVerified = localStorage.getItem(SSO_CONFIG.STORAGE_KEYS.SSO_VERIFIED_AT);
311
+ if (!lastVerified) return true;
312
+
313
+ const lastVerifiedDate = new Date(lastVerified);
314
+ const now = new Date();
315
+ const hoursSinceVerification = (now - lastVerifiedDate) / (1000 * 60 * 60);
316
+
317
+ // Re-verify if more than 24 hours since last verification
318
+ if (hoursSinceVerification > 24) {
319
+ console.log('🔄 [SSO] Session verification needed (>24 hours)');
320
+ return true;
321
+ }
322
+
323
+ // Check if token is approaching expiration
324
+ const token = getStoredToken();
325
+ if (token) {
326
+ const validation = validateToken(token);
327
+ if (validation.valid && validation.payload?.exp) {
328
+ const expiresAt = new Date(validation.payload.exp * 1000);
329
+ const daysUntilExpiry = (expiresAt - now) / (1000 * 60 * 60 * 24);
330
+
331
+ if (daysUntilExpiry < SSO_CONFIG.REFRESH_THRESHOLD_DAYS) {
332
+ console.log(`🔄 [SSO] Token refresh needed (expires in ${Math.round(daysUntilExpiry)} days)`);
333
+ return true;
334
+ }
335
+ }
336
+ }
337
+
338
+ return false;
339
+ } catch (e) {
340
+ return true;
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Verify and optionally refresh the SSO session with the server
346
+ * This is the secure verification step (like Google's silent auth)
347
+ * @param {Object} options - Verification options
348
+ * @returns {Promise<Object>} { success: boolean, userData: object|null, error: string|null, newToken: string|null }
349
+ */
350
+ export async function verifySSOSession(options = {}) {
351
+ console.log('🔐 [SSO] Verifying session with server...');
352
+
353
+ const token = options.token || getStoredToken();
354
+ if (!token) {
355
+ return { success: false, userData: null, error: 'No token available', newToken: null };
356
+ }
357
+
358
+ // Generate nonce for this verification
359
+ const nonce = generateNonce();
360
+ const deviceId = getDeviceFingerprint();
361
+
362
+ try {
363
+ const baseUrl = API_CONFIG.getBaseUrl();
364
+ const response = await fetch(`${baseUrl}${SSO_CONFIG.SSO_VERIFY_ENDPOINT}`, {
365
+ method: 'POST',
366
+ headers: {
367
+ 'Content-Type': 'application/json',
368
+ 'Authorization': `Bearer ${token}`,
369
+ 'X-Onairos-Device-Id': deviceId,
370
+ 'X-Onairos-Nonce': nonce
371
+ },
372
+ body: JSON.stringify({
373
+ nonce,
374
+ deviceId,
375
+ appType: getOnairosAppType(),
376
+ requestRefresh: options.requestRefresh || false
377
+ }),
378
+ credentials: 'include'
379
+ });
380
+
381
+ if (!response.ok) {
382
+ if (response.status === 401 || response.status === 403) {
383
+ console.log('❌ [SSO] Token rejected by server - session invalid');
384
+ destroySession();
385
+ return { success: false, userData: null, error: 'Session expired', newToken: null };
386
+ }
387
+ throw new Error(`Server error: ${response.status}`);
388
+ }
389
+
390
+ const result = await response.json();
391
+
392
+ if (result.success) {
393
+ console.log('✅ [SSO] Session verified successfully');
394
+
395
+ // Store verification timestamp
396
+ localStorage.setItem(SSO_CONFIG.STORAGE_KEYS.SSO_VERIFIED_AT, new Date().toISOString());
397
+
398
+ // If server provided a refreshed token, update it
399
+ if (result.newToken) {
400
+ console.log('🔄 [SSO] Token refreshed by server');
401
+ const userData = result.userData || {};
402
+ createSession(userData, result.newToken);
403
+
404
+ // Update cross-domain SSO cookie
405
+ setCrossDomainSSOCookie(userData, result.newToken);
406
+
407
+ return { success: true, userData, error: null, newToken: result.newToken };
408
+ }
409
+
410
+ return { success: true, userData: result.userData, error: null, newToken: null };
411
+ } else {
412
+ return { success: false, userData: null, error: result.error || 'Verification failed', newToken: null };
413
+ }
414
+ } catch (e) {
415
+ console.error('❌ [SSO] Verification request failed:', e);
416
+
417
+ // On network error, allow offline usage if token is still valid locally
418
+ const validation = validateToken(token);
419
+ if (validation.valid) {
420
+ console.log('🔶 [SSO] Network error but token valid locally - allowing offline access');
421
+ return { success: true, userData: null, error: null, newToken: null, offline: true };
422
+ }
423
+
424
+ return { success: false, userData: null, error: e.message, newToken: null };
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Set the cross-domain SSO cookie for other Onairos apps to pick up
430
+ * @param {Object} userData - User data to share
431
+ * @param {string} token - JWT token
432
+ */
433
+ function setCrossDomainSSOCookie(userData, token) {
434
+ const ssoData = {
435
+ email: userData.email || userData.username,
436
+ token: token,
437
+ verified: userData.verified,
438
+ ts: Date.now()
439
+ };
440
+
441
+ setCrossDomainCookie(
442
+ SSO_CONFIG.SSO_COOKIE_NAME,
443
+ JSON.stringify(ssoData),
444
+ 30 * 24 * 60 * 60 * 1000 // 30 days
445
+ );
446
+ }
447
+
448
+ /**
449
+ * Perform automatic SSO sign-in for Onairos apps
450
+ * Returns immediately if already authenticated, otherwise attempts SSO
451
+ * @param {Object} options - Options
452
+ * @param {Function} options.onStart - Called when SSO verification starts
453
+ * @param {Function} options.onSuccess - Called on successful sign-in
454
+ * @param {Function} options.onError - Called on error
455
+ * @param {Function} options.onNotAuthenticated - Called when no SSO available
456
+ * @returns {Promise<Object>} SSO result
457
+ */
458
+ export async function performAutoSSO(options = {}) {
459
+ const { onStart, onSuccess, onError, onNotAuthenticated } = options;
460
+
461
+ console.log('🚀 [SSO] Performing automatic SSO check...');
462
+
463
+ // Check for existing SSO session
464
+ const ssoCheck = checkSSOSession();
465
+
466
+ if (!ssoCheck.hasSSO) {
467
+ console.log('❌ [SSO] No SSO session available');
468
+ onNotAuthenticated?.();
469
+ return { authenticated: false, userData: null };
470
+ }
471
+
472
+ // If no verification needed, return immediately
473
+ if (!ssoCheck.needsVerification) {
474
+ console.log('✅ [SSO] Session valid, no verification needed');
475
+ onSuccess?.(ssoCheck.userData);
476
+ return { authenticated: true, userData: ssoCheck.userData, verified: false };
477
+ }
478
+
479
+ // Need to verify with server
480
+ console.log('🔄 [SSO] Verifying session with server...');
481
+ onStart?.();
482
+
483
+ try {
484
+ const verification = await verifySSOSession({ requestRefresh: true });
485
+
486
+ if (verification.success) {
487
+ const userData = verification.userData || ssoCheck.userData;
488
+ console.log('✅ [SSO] Session verified successfully');
489
+ onSuccess?.(userData, verification.newToken);
490
+ return { authenticated: true, userData, verified: true, newToken: verification.newToken };
491
+ } else {
492
+ console.log('❌ [SSO] Session verification failed:', verification.error);
493
+ onError?.(verification.error);
494
+ return { authenticated: false, userData: null, error: verification.error };
495
+ }
496
+ } catch (e) {
497
+ console.error('❌ [SSO] Auto SSO error:', e);
498
+ onError?.(e.message);
499
+ return { authenticated: false, userData: null, error: e.message };
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Create an SSO session after successful login
505
+ * This should be called after email verification or Google sign-in
506
+ * @param {Object} userData - User data
507
+ * @param {string} token - JWT token
508
+ */
509
+ export function createSSOSession(userData, token) {
510
+ console.log('🔐 [SSO] Creating SSO session...');
511
+
512
+ // Create local session
513
+ createSession(userData, token);
514
+
515
+ // Store device binding
516
+ getDeviceFingerprint();
517
+
518
+ // Set cross-domain SSO cookie for other Onairos apps
519
+ setCrossDomainSSOCookie(userData, token);
520
+
521
+ // Mark as verified
522
+ localStorage.setItem(SSO_CONFIG.STORAGE_KEYS.SSO_VERIFIED_AT, new Date().toISOString());
523
+
524
+ console.log('✅ [SSO] SSO session created for cross-domain use');
525
+ }
526
+
527
+ /**
528
+ * Destroy SSO session across all domains
529
+ */
530
+ export function destroySSOSession() {
531
+ console.log('🚪 [SSO] Destroying SSO session...');
532
+
533
+ // Destroy local session
534
+ destroySession();
535
+
536
+ // Clear cross-domain cookies
537
+ deleteCrossDomainCookie(SSO_CONFIG.SSO_COOKIE_NAME);
538
+ deleteCrossDomainCookie(SSO_CONFIG.SSO_NONCE_COOKIE);
539
+
540
+ // Clear SSO-specific storage
541
+ try {
542
+ localStorage.removeItem(SSO_CONFIG.STORAGE_KEYS.SSO_TOKEN);
543
+ localStorage.removeItem(SSO_CONFIG.STORAGE_KEYS.SSO_NONCE);
544
+ localStorage.removeItem(SSO_CONFIG.STORAGE_KEYS.SSO_VERIFIED_AT);
545
+ localStorage.removeItem(SSO_CONFIG.STORAGE_KEYS.SSO_REFRESH_TOKEN);
546
+ } catch (e) {}
547
+
548
+ console.log('✅ [SSO] SSO session destroyed');
549
+ }
550
+
551
+ /**
552
+ * Get SSO status information for debugging
553
+ * @returns {Object} SSO status
554
+ */
555
+ export function getSSOStatus() {
556
+ const ssoCheck = checkSSOSession();
557
+ const token = getStoredToken();
558
+ const tokenValidation = token ? validateToken(token) : { valid: false };
559
+ const lastVerified = localStorage.getItem(SSO_CONFIG.STORAGE_KEYS.SSO_VERIFIED_AT);
560
+ const deviceId = localStorage.getItem(SSO_CONFIG.STORAGE_KEYS.SSO_DEVICE_ID);
561
+
562
+ return {
563
+ isOnairosApp: isOnairosApp(),
564
+ appType: getOnairosAppType(),
565
+ hasSSO: ssoCheck.hasSSO,
566
+ needsVerification: ssoCheck.needsVerification,
567
+ hasToken: !!token,
568
+ tokenValid: tokenValidation.valid,
569
+ lastVerified,
570
+ deviceId,
571
+ hasCrossDomainCookie: !!getCookie(SSO_CONFIG.SSO_COOKIE_NAME)
572
+ };
573
+ }
574
+
575
+ export default {
576
+ isOnairosApp,
577
+ isPartnerApp,
578
+ getOnairosAppType,
579
+ checkSSOSession,
580
+ verifySSOSession,
581
+ performAutoSSO,
582
+ createSSOSession,
583
+ destroySSOSession,
584
+ getSSOStatus,
585
+ SSO_CONFIG
586
+ };
587
+
@@ -0,0 +1,27 @@
1
+ export const launchOnairosApp = async () => {
2
+ const nonce = Date.now();
3
+ const returnLink = encodeURIComponent(window.location.origin + '/auth/callback');
4
+
5
+ const onairosUrl = `onairos://authenticate?nonce=${nonce}&callback=${returnLink}&appName=google`;
6
+
7
+ // Try to open Onairos app
8
+ window.location.href = onairosUrl;
9
+
10
+ // Fallback to app store after timeout
11
+ setTimeout(() => {
12
+ window.location.href = 'https://apps.apple.com/app/onairos/id123456789';
13
+ }, 2500);
14
+ };
15
+
16
+ export const handleDeepLink = () => {
17
+ // Listen for return from Onairos app
18
+ window.addEventListener('message', (event) => {
19
+ if (event.data?.type === 'ONAIROS_AUTH') {
20
+ const { token, credentials } = event.data;
21
+ if (token) {
22
+ localStorage.setItem('onairosToken', token);
23
+ localStorage.setItem('onairosCredentials', JSON.stringify(credentials));
24
+ }
25
+ }
26
+ });
27
+ };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Development Logger Utility
3
+ * Only logs when devMode is enabled. All logs are prefixed with [Onairos Dev].
4
+ */
5
+
6
+ // Check if dev mode is enabled
7
+ const isDevMode = () => {
8
+ if (typeof window !== 'undefined') {
9
+ return window.onairosDevMode === true || window.ONAIROS_DEV_MODE === true;
10
+ }
11
+ return false;
12
+ };
13
+
14
+ // Dev-only logging functions
15
+ export const devLog = (...args) => {
16
+ if (isDevMode()) {
17
+ console.log('[Onairos Dev]', ...args);
18
+ }
19
+ };
20
+
21
+ export const devWarn = (...args) => {
22
+ if (isDevMode()) {
23
+ console.warn('[Onairos Dev]', ...args);
24
+ }
25
+ };
26
+
27
+ export const devError = (...args) => {
28
+ if (isDevMode()) {
29
+ console.error('[Onairos Dev]', ...args);
30
+ }
31
+ };
32
+
33
+ // For critical errors that should always log (auth failures, API errors, etc.)
34
+ export const logError = (...args) => {
35
+ console.error('[Onairos]', ...args);
36
+ };
37
+
38
+ // For important user-facing info (should be minimal)
39
+ export const logInfo = (...args) => {
40
+ if (isDevMode()) {
41
+ console.info('[Onairos Dev]', ...args);
42
+ }
43
+ };
44
+
45
+ export default { devLog, devWarn, devError, logError, logInfo };
46
+