diff --git a/android/app/src/main/java/com/maestri/remote/MainActivity.java b/android/app/src/main/java/com/maestri/remote/MainActivity.java index 96ec345..0f6ba80 100644 --- a/android/app/src/main/java/com/maestri/remote/MainActivity.java +++ b/android/app/src/main/java/com/maestri/remote/MainActivity.java @@ -30,103 +30,163 @@ public class MainActivity extends BridgeActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - createNotificationChannels(); - checkAndRequestPermissions(); + try { + initFirebaseSafely(); + } catch (Throwable t) { + Log.w(TAG, "Blindagem defensiva de inicializacao do Firebase: " + t.getMessage()); + } + try { + createNotificationChannels(); + } catch (Throwable t) { + Log.e(TAG, "Falha segura ao criar canais de notificacao: " + t.getMessage(), t); + } + try { + checkAndRequestPermissions(); + } catch (Throwable t) { + Log.e(TAG, "Falha segura ao solicitar permissoes: " + t.getMessage(), t); + } + } + + private void initFirebaseSafely() { + try { + Class firebaseAppClass = Class.forName("com.google.firebase.FirebaseApp"); + java.lang.reflect.Method getAppsMethod = firebaseAppClass.getMethod("getApps", Context.class); + List apps = (List) getAppsMethod.invoke(null, this); + if (apps == null || apps.isEmpty()) { + Log.i(TAG, "Nenhum FirebaseApp ativo (google-services.json ausente). Inicializando fallback defensivo para blindar PushNotifications..."); + Class builderClass = Class.forName("com.google.firebase.FirebaseOptions$Builder"); + Object builder = builderClass.getConstructor().newInstance(); + + builderClass.getMethod("setApplicationId", String.class).invoke(builder, getPackageName()); + builderClass.getMethod("setApiKey", String.class).invoke(builder, "AIzaSyDummyKeyForMaestriDefensiveInit"); + builderClass.getMethod("setProjectId", String.class).invoke(builder, "maestri-remote"); + Object options = builderClass.getMethod("build").invoke(builder); + + Class firebaseOptionsClass = Class.forName("com.google.firebase.FirebaseOptions"); + java.lang.reflect.Method initMethod = firebaseAppClass.getMethod("initializeApp", Context.class, firebaseOptionsClass); + initMethod.invoke(null, this, options); + Log.i(TAG, "Fallback defensivo do FirebaseApp inicializado com sucesso."); + } + } catch (ClassNotFoundException e) { + Log.d(TAG, "Firebase nao esta presente no classpath: " + e.getMessage()); + } catch (Throwable t) { + Log.w(TAG, "Nao foi possivel inicializar fallback do FirebaseApp: " + t.getMessage()); + } } private void createNotificationChannels() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - if (manager == null) { - Log.w(TAG, "NotificationManager não disponível no sistema."); - return; + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + if (manager == null) { + Log.w(TAG, "NotificationManager nao disponivel no sistema."); + return; + } + + Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); + AudioAttributes audioAttributes = new AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_NOTIFICATION) + .build(); + + // 1. Canal Urgente de Alta Prioridade (Heads-up / Pop-up / Lockscreen / Doze wake-up) + try { + NotificationChannel urgentChannel = new NotificationChannel( + CHANNEL_URGENT_ID, + "Alertas Críticos", + NotificationManager.IMPORTANCE_HIGH + ); + urgentChannel.setDescription("Notificações urgentes de tarefas e aprovações do Maestri"); + urgentChannel.enableVibration(true); + urgentChannel.setVibrationPattern(new long[]{0, 250, 100, 250, 100, 250}); + urgentChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); + urgentChannel.enableLights(true); + urgentChannel.setLightColor(Color.GREEN); + urgentChannel.setBypassDnd(true); + urgentChannel.setShowBadge(true); + if (defaultSoundUri != null) { + urgentChannel.setSound(defaultSoundUri, audioAttributes); + } + manager.createNotificationChannel(urgentChannel); + } catch (Throwable t) { + Log.w(TAG, "Falha ao registrar canal urgent: " + t.getMessage()); + } + + // 2. Canal Fallback do FCM (Evita que o FCM use importancia default se nao encontrar o canal) + try { + NotificationChannel fallbackChannel = new NotificationChannel( + CHANNEL_FALLBACK_ID, + "Notificações Maestri", + NotificationManager.IMPORTANCE_HIGH + ); + fallbackChannel.setDescription("Notificações de background e mensagens de agentes"); + fallbackChannel.enableVibration(true); + fallbackChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); + fallbackChannel.enableLights(true); + fallbackChannel.setShowBadge(true); + if (defaultSoundUri != null) { + fallbackChannel.setSound(defaultSoundUri, audioAttributes); + } + manager.createNotificationChannel(fallbackChannel); + } catch (Throwable t) { + Log.w(TAG, "Falha ao registrar canal fallback: " + t.getMessage()); + } + + // 3. Canal Default + try { + NotificationChannel defaultChannel = new NotificationChannel( + CHANNEL_DEFAULT_ID, + "Alertas Gerais", + NotificationManager.IMPORTANCE_HIGH + ); + defaultChannel.setDescription("Notificações gerais do Maestri Remote"); + defaultChannel.enableVibration(true); + defaultChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); + defaultChannel.setShowBadge(true); + if (defaultSoundUri != null) { + defaultChannel.setSound(defaultSoundUri, audioAttributes); + } + manager.createNotificationChannel(defaultChannel); + } catch (Throwable t) { + Log.w(TAG, "Falha ao registrar canal default: " + t.getMessage()); + } + + Log.i(TAG, "Canais de notificacao Android inicializados defensivamente."); } - - Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); - AudioAttributes audioAttributes = new AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION) - .build(); - - // 1. Canal Urgente de Alta Prioridade (Heads-up / Pop-up / Lockscreen / Doze wake-up) - NotificationChannel urgentChannel = new NotificationChannel( - CHANNEL_URGENT_ID, - "Alertas Críticos", - NotificationManager.IMPORTANCE_HIGH - ); - urgentChannel.setDescription("Notificações urgentes de tarefas e aprovações do Maestri"); - urgentChannel.enableVibration(true); - urgentChannel.setVibrationPattern(new long[]{0, 250, 100, 250, 100, 250}); - urgentChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); - urgentChannel.enableLights(true); - urgentChannel.setLightColor(Color.GREEN); - urgentChannel.setBypassDnd(true); - urgentChannel.setShowBadge(true); - if (defaultSoundUri != null) { - urgentChannel.setSound(defaultSoundUri, audioAttributes); - } - manager.createNotificationChannel(urgentChannel); - - // 2. Canal Fallback do FCM (Evita que o FCM use importância default se não encontrar o canal) - NotificationChannel fallbackChannel = new NotificationChannel( - CHANNEL_FALLBACK_ID, - "Notificações Maestri", - NotificationManager.IMPORTANCE_HIGH - ); - fallbackChannel.setDescription("Notificações de background e mensagens de agentes"); - fallbackChannel.enableVibration(true); - fallbackChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); - fallbackChannel.enableLights(true); - fallbackChannel.setShowBadge(true); - if (defaultSoundUri != null) { - fallbackChannel.setSound(defaultSoundUri, audioAttributes); - } - manager.createNotificationChannel(fallbackChannel); - - // 3. Canal Default - NotificationChannel defaultChannel = new NotificationChannel( - CHANNEL_DEFAULT_ID, - "Alertas Gerais", - NotificationManager.IMPORTANCE_HIGH - ); - defaultChannel.setDescription("Notificações gerais do Maestri Remote"); - defaultChannel.enableVibration(true); - defaultChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); - defaultChannel.setShowBadge(true); - if (defaultSoundUri != null) { - defaultChannel.setSound(defaultSoundUri, audioAttributes); - } - manager.createNotificationChannel(defaultChannel); - - Log.i(TAG, "Canais de notificação Android (maestri_urgent, fcm_fallback, default) inicializados com sucesso."); + } catch (Throwable t) { + Log.e(TAG, "Erro geral ao criar canais de notificacao: " + t.getMessage(), t); } } private void checkAndRequestPermissions() { - List permissionsNeeded = new ArrayList<>(); + try { + List permissionsNeeded = new ArrayList<>(); - if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { - permissionsNeeded.add(Manifest.permission.RECORD_AUDIO); - } - - if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { - permissionsNeeded.add(Manifest.permission.CAMERA); - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { - permissionsNeeded.add(Manifest.permission.POST_NOTIFICATIONS); + if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { + permissionsNeeded.add(Manifest.permission.RECORD_AUDIO); } - if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) { - permissionsNeeded.add(Manifest.permission.READ_MEDIA_IMAGES); - } - if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) { - permissionsNeeded.add(Manifest.permission.READ_MEDIA_VIDEO); - } - } - if (!permissionsNeeded.isEmpty()) { - ActivityCompat.requestPermissions(this, permissionsNeeded.toArray(new String[0]), PERMISSION_REQ_CODE); + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + permissionsNeeded.add(Manifest.permission.CAMERA); + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + permissionsNeeded.add(Manifest.permission.POST_NOTIFICATIONS); + } + if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) { + permissionsNeeded.add(Manifest.permission.READ_MEDIA_IMAGES); + } + if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) { + permissionsNeeded.add(Manifest.permission.READ_MEDIA_VIDEO); + } + } + + if (!permissionsNeeded.isEmpty()) { + ActivityCompat.requestPermissions(this, permissionsNeeded.toArray(new String[0]), PERMISSION_REQ_CODE); + } + } catch (Throwable t) { + Log.e(TAG, "Erro geral ao checar/solicitar permissoes: " + t.getMessage(), t); } } } diff --git a/public/app.js b/public/app.js index 9267fec..f87a306 100644 --- a/public/app.js +++ b/public/app.js @@ -722,9 +722,62 @@ async function startGoogleLogin() { } if (isNativeOrLocal) { - const opened = window.open(authUrl, '_system'); + let opened = false; + const cap = window.Capacitor; + + // 1. Tenta Capacitor Browser plugin se registrado + if (cap?.Plugins?.Browser?.open) { + try { + await cap.Plugins.Browser.open({ url: authUrl }); + opened = true; + } catch (e) { + console.warn('[Auth] Falha no Browser.open:', e); + } + } + + // 2. Tenta Capacitor App plugin (openUrl) se disponível + if (!opened && cap?.Plugins?.App?.openUrl) { + try { + await cap.Plugins.App.openUrl({ url: authUrl }); + opened = true; + } catch (e) { + console.warn('[Auth] Falha no App.openUrl:', e); + } + } + + // 3. Tenta window.open com target '_system' if (!opened) { - window.location.href = authUrl; + try { + const w = window.open(authUrl, '_system', 'location=yes'); + if (w) opened = true; + } catch (e) { + console.warn('[Auth] Falha no window.open(_system):', e); + } + } + + // 4. Fallback via elemento com target="_system" (nunca substitui window.location.href em app nativo!) + if (!opened) { + try { + const link = document.createElement('a'); + link.href = authUrl; + link.target = '_system'; + link.rel = 'noopener noreferrer'; + document.body.appendChild(link); + link.click(); + setTimeout(() => { + try { document.body.removeChild(link); } catch (e) {} + }, 100); + opened = true; + } catch (e) { + console.warn('[Auth] Falha ao disparar link _system:', e); + } + } + + // Em ambiente nativo/Capacitor, JAMAIS substitua window.location.href diretamente, + // pois a WebView perderia a origem do app, quebraria o Capacitor e causaria + // erro 403 (disallowed_useragent) no Google OAuth! + if (!opened && authStatusText) { + authStatusText.innerHTML = `Por favor, clique aqui para abrir o login no navegador externo.`; } } else if (preOpenedPopup && !preOpenedPopup.closed) { try { @@ -5364,7 +5417,11 @@ async function initApp() { } initServiceWorker(); - initNativePushNotifications(); + try { + initNativePushNotifications(); + } catch (pushInitErr) { + console.warn('[Boot] Erro seguro ao disparar initNativePushNotifications:', pushInitErr); + } initOtaChecker(); // Gate obrigatório de autenticação Google SSO @@ -5548,80 +5605,133 @@ async function sendFcmTokenToRelay(tokenOverride = null, specificPin = null) { async function initNativePushNotifications() { const cap = window.Capacitor; + if (!cap) return; + + const isNative = typeof cap.isNativePlatform === 'function' + ? cap.isNativePlatform() + : (cap.getPlatform && cap.getPlatform() !== 'web'); + if (!isNative) return; + const PushNotifications = cap?.Plugins?.PushNotifications; if (!PushNotifications) return; try { - // 1. Cria canais de alta prioridade no Android antes do registro - const isAndroid = cap.getPlatform && cap.getPlatform() === 'android'; - if (isAndroid) { - // Canal Crítico com importância máxima (5) e luzes (sem forçar raw sound customizado para usar som padrão do sistema) - await PushNotifications.createChannel({ - id: 'maestri_urgent', - name: 'Alertas Críticos', - description: 'Notificações urgentes de tarefas e aprovações do Maestri', - importance: 5, - visibility: 1, - vibration: true, - lights: true, - lightColor: '#22c55e' - }).catch(err => console.warn('[FCM] createChannel maestri_urgent aviso:', err)); + if (typeof cap.isPluginAvailable === 'function' && !cap.isPluginAvailable('PushNotifications')) { + console.warn('[FCM] Plugin PushNotifications não está disponível nesta plataforma/build.'); + return; + } + } catch (e) { + console.warn('[FCM] Falha ao verificar disponibilidade do plugin PushNotifications:', e); + } - // Canal Fallback do FCM - await PushNotifications.createChannel({ - id: 'fcm_fallback_notification_channel', - name: 'Notificações Maestri', - description: 'Notificações gerais e avisos de tarefas', - importance: 5, - visibility: 1, - vibration: true, - lights: true, - lightColor: '#22c55e' - }).catch(err => console.warn('[FCM] createChannel fcm_fallback aviso:', err)); + try { + // 1. Cria canais de alta prioridade no Android antes do registro (com proteção defensiva) + const isAndroid = cap.getPlatform && cap.getPlatform() === 'android'; + if (isAndroid && typeof PushNotifications.createChannel === 'function') { + try { + await PushNotifications.createChannel({ + id: 'maestri_urgent', + name: 'Alertas Críticos', + description: 'Notificações urgentes de tarefas e aprovações do Maestri', + importance: 5, + visibility: 1, + vibration: true, + lights: true, + lightColor: '#22c55e' + }).catch(err => console.warn('[FCM] createChannel maestri_urgent aviso:', err)); + } catch (channelErr) { + console.warn('[FCM] Aviso ao criar canal maestri_urgent:', channelErr); + } + + try { + await PushNotifications.createChannel({ + id: 'fcm_fallback_notification_channel', + name: 'Notificações Maestri', + description: 'Notificações gerais e avisos de tarefas', + importance: 5, + visibility: 1, + vibration: true, + lights: true, + lightColor: '#22c55e' + }).catch(err => console.warn('[FCM] createChannel fcm_fallback aviso:', err)); + } catch (channelErr) { + console.warn('[FCM] Aviso ao criar canal fcm_fallback:', channelErr); + } } // 2. Registra os listeners OBRIGATORIAMENTE ANTES de invocar register() para evitar race conditions - PushNotifications.addListener('registration', async (token) => { - console.log('[FCM] Token de registro nativo recebido:', token.value); - try { localStorage.setItem('maestri_fcm_token', token.value); } catch (e) {} - await sendFcmTokenToRelay(token.value); - }); + if (typeof PushNotifications.addListener === 'function') { + try { + PushNotifications.addListener('registration', async (token) => { + console.log('[FCM] Token de registro nativo recebido:', token?.value); + if (token?.value) { + try { localStorage.setItem('maestri_fcm_token', token.value); } catch (e) {} + await sendFcmTokenToRelay(token.value); + } + }); - PushNotifications.addListener('registrationError', (error) => { - console.error('[FCM] Erro no registro de push nativo:', error); - }); + PushNotifications.addListener('registrationError', (error) => { + console.warn('[FCM] Registro de push nativo reportou erro ou Firebase não configurado:', error); + }); - PushNotifications.addListener('pushNotificationReceived', (notification) => { - console.log('[FCM] Notificação recebida no cliente:', notification); - if (typeof playNotificationSound === 'function') { - playNotificationSound(); + PushNotifications.addListener('pushNotificationReceived', (notification) => { + console.log('[FCM] Notificação recebida no cliente:', notification); + if (typeof playNotificationSound === 'function') { + try { playNotificationSound(); } catch (e) {} + } + if (typeof navigator !== 'undefined' && navigator.vibrate) { + try { navigator.vibrate([200, 100, 200]); } catch (e) {} + } + }); + + PushNotifications.addListener('pushNotificationActionPerformed', (action) => { + console.log('[FCM] Notificação acionada pelo operador:', action); + const data = action?.notification?.data || {}; + if (data.stationId && data.agentName) { + switchStation(data.stationId); + setTimeout(() => { + openChatModal(data.agentName, data.stationId); + }, 300); + } + }); + } catch (listenerErr) { + console.warn('[FCM] Erro defensivo ao registrar listeners do PushNotifications:', listenerErr); } - if (typeof navigator !== 'undefined' && navigator.vibrate) { - navigator.vibrate([200, 100, 200]); - } - }); + } - PushNotifications.addListener('pushNotificationActionPerformed', (action) => { - console.log('[FCM] Notificação acionada pelo operador:', action); - const data = action?.notification?.data || {}; - if (data.stationId && data.agentName) { - switchStation(data.stationId); - setTimeout(() => { - openChatModal(data.agentName, data.stationId); - }, 300); + // 3. Solicita permissão e registra defensivamente (isolado em try/catch para nunca crashar na ausência do Firebase) + try { + let permResult = null; + if (typeof PushNotifications.checkPermissions === 'function') { + permResult = await PushNotifications.checkPermissions().catch(() => null); + } + if (!permResult || permResult.receive !== 'granted') { + if (typeof PushNotifications.requestPermissions === 'function') { + permResult = await PushNotifications.requestPermissions().catch(() => null); + } } - }); - // 3. Solicita permissão e registra - const permResult = await PushNotifications.requestPermissions(); - if (permResult && permResult.receive === 'granted') { - await PushNotifications.register(); + if (permResult && permResult.receive === 'granted' && typeof PushNotifications.register === 'function') { + try { + await PushNotifications.register(); + } catch (regErr) { + console.warn('[FCM] PushNotifications.register() ignorado defensivamente (Firebase/google-services ausente):', regErr); + } + } else { + console.log('[FCM] Permissão de notificações não concedida pelo usuário.'); + } + } catch (permErr) { + console.warn('[FCM] Falha defensiva ao verificar permissões/registrar PushNotifications:', permErr); } // 4. Se já houver token em cache no localStorage, sincroniza imediatamente com o relay - const cachedToken = localStorage.getItem('maestri_fcm_token'); - if (cachedToken) { - await sendFcmTokenToRelay(cachedToken); + try { + const cachedToken = localStorage.getItem('maestri_fcm_token'); + if (cachedToken) { + await sendFcmTokenToRelay(cachedToken); + } + } catch (tokenSyncErr) { + console.warn('[FCM] Erro ao sincronizar cachedToken:', tokenSyncErr); } } catch (err) { console.warn('[FCM] Erro ao inicializar notificações nativas Capacitor:', err); diff --git a/public/bundles/bundle-1.0.30.zip b/public/bundles/bundle-1.0.30.zip index 0f1def4..7d8f027 100644 Binary files a/public/bundles/bundle-1.0.30.zip and b/public/bundles/bundle-1.0.30.zip differ diff --git a/public/bundles/bundle-latest.zip b/public/bundles/bundle-latest.zip index 0f1def4..7d8f027 100644 Binary files a/public/bundles/bundle-latest.zip and b/public/bundles/bundle-latest.zip differ diff --git a/public/bundles/manifest.json b/public/bundles/manifest.json index cd92bad..d4e4265 100644 --- a/public/bundles/manifest.json +++ b/public/bundles/manifest.json @@ -1,9 +1,9 @@ { "version": "1.0.30", - "buildId": "6404584d", - "releasedAt": "2026-11-22T01:09:31.913Z", + "buildId": "45eaf454", + "releasedAt": "2026-11-22T01:43:27.381Z", "bundleUrl": "/bundles/bundle-1.0.30.zip", "latestUrl": "/bundles/bundle-latest.zip", - "checksum": "67b46afffe8561338e9632cb3e1e008585e469831d2a10bf8343b33ac5d5f87a", - "sizeBytes": 73028 + "checksum": "484c403ff165b0c3571811cff21e8c7d891494138431f56fbe924b3fbb0590ad", + "sizeBytes": 74103 } \ No newline at end of file diff --git a/public/maestri-agent.zip b/public/maestri-agent.zip index 9782cb0..0ef9182 100644 Binary files a/public/maestri-agent.zip and b/public/maestri-agent.zip differ diff --git a/public/maestri-remote.apk b/public/maestri-remote.apk index ec247da..2a95467 100644 Binary files a/public/maestri-remote.apk and b/public/maestri-remote.apk differ diff --git a/test/frontend-app.test.js b/test/frontend-app.test.js index f36220c..e55df2e 100644 --- a/test/frontend-app.test.js +++ b/test/frontend-app.test.js @@ -3253,4 +3253,98 @@ Também verificamos running command e compiling no buffer. assert.ok(cssContent.includes('min-width: 44px;'), 'CSS deve garantir min-width de 44px'); assert.ok(cssContent.includes('min-height: 44px;'), 'CSS deve garantir min-height de 44px'); }); + + test('37. Blindagem contra crash no boot nativo: PushNotifications resiliente e fluxo Google SSO seguro no Capacitor', async () => { + const htmlContent = fs.readFileSync(path.resolve('public', 'index.html'), 'utf8'); + const appJsContent = fs.readFileSync(path.resolve('public', 'app.js'), 'utf8'); + + const freshDom = new JSDOM(htmlContent, { + runScripts: 'dangerously', + url: 'https://remote.winicomw.ddnsfree.com/' + }); + + try { + const w = freshDom.window; + const doc = w.document; + let browserOpenedUrl = null; + let windowOpenedArgs = null; + + // Simula Capacitor nativo Android onde FirebaseApp NÃO foi inicializado (google-services.json ausente) + let registerCalled = false; + w.Capacitor = { + isNativePlatform: () => true, + getPlatform: () => 'android', + isPluginAvailable: (name) => name === 'PushNotifications' || name === 'Browser', + Plugins: { + PushNotifications: { + createChannel: async () => {}, + addListener: (event, cb) => {}, + requestPermissions: async () => ({ receive: 'granted' }), + checkPermissions: async () => ({ receive: 'granted' }), + register: async () => { + registerCalled = true; + throw new Error('Default FirebaseApp is not initialized in this process com.maestri.remote.'); + } + }, + Browser: { + open: async ({ url }) => { + browserOpenedUrl = url; + } + } + } + }; + + w.open = (url, target, features) => { + windowOpenedArgs = { url, target, features }; + return { closed: false, location: url }; + }; + + w.fetch = async (url) => { + const target = String(url); + if (target.includes('/api/auth/start')) { + return { + ok: true, + status: 200, + json: async () => ({ + flowId: 'flow-native-test', + authUrl: 'https://auth.winicomw.ddnsfree.com/realms/maestri/protocol/openid-connect/auth?flow=1' + }) + }; + } + return { + ok: true, + status: 200, + json: async () => ({ status: 'ok' }) + }; + }; + + // Avalia o script no DOM com Capacitor nativo + const scriptEl = doc.createElement('script'); + scriptEl.textContent = appJsContent; + doc.body.appendChild(scriptEl); + await new Promise(r => setTimeout(r, 30)); + + // 1. initNativePushNotifications no boot não deve derrubar o app mesmo com FirebaseApp lançando IllegalStateException + assert.strictEqual(registerCalled, true, 'PushNotifications.register deve ter sido tentado'); + const authScreen = doc.getElementById('auth-screen'); + assert.strictEqual(authScreen.style.display, 'flex', 'Tela de autenticação deve continuar visível e funcional sem crash'); + + // 2. Fluxo Google SSO em ambiente nativo: deve usar Browser plugin e NUNCA substituir window.location.href + const initialLocation = w.location.href; + const btnGoogle = doc.getElementById('btn-google-login'); + assert.ok(btnGoogle, 'Botão de login Google deve existir'); + btnGoogle.click(); + await new Promise(r => setTimeout(r, 40)); + + assert.strictEqual(browserOpenedUrl, 'https://auth.winicomw.ddnsfree.com/realms/maestri/protocol/openid-connect/auth?flow=1', 'Browser.open deve ser chamado para abrir no navegador externo'); + assert.strictEqual(w.location.href, initialLocation, 'window.location.href NUNCA deve ser sobrescrito na WebView nativa para evitar quebra do app'); + + // Limpa timers ativos do teste + if (typeof w.activeAuthPollCleanup === 'function') { + w.activeAuthPollCleanup(); + } + } finally { + freshDom.window.close(); + } + }); });