fix(android): blindar inicializacao nativa contra crashes no push e fluxo google sso

- Tornar inicializacao de PushNotifications resiliente com verificacao de suporte nativo e tratamento seguro caso Firebase nao esteja inicializado
- Blindar MainActivity com inicializacao defensiva de FirebaseApp e tratamento de excecoes na criacao de canais e solicitacao de permissoes
- Ajustar fluxo de login Google SSO no Capacitor para utilizar Browser plugin e links externos sem sobrescrever a WebView
- Recompilar APK nativo release assinado e disponibilizar em public/maestri-remote.apk
- Atualizar bundle OTA e testes automatizados de regressao
This commit is contained in:
Winícius 2026-11-21 22:44:19 -03:00
parent 1262e85d02
commit 6c075ab0b1
8 changed files with 414 additions and 150 deletions

View File

@ -30,103 +30,163 @@ public class MainActivity extends BridgeActivity {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
createNotificationChannels(); try {
checkAndRequestPermissions(); 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() { private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { try {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (manager == null) { NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Log.w(TAG, "NotificationManager não disponível no sistema."); if (manager == null) {
return; 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.");
} }
} catch (Throwable t) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Log.e(TAG, "Erro geral ao criar canais de notificacao: " + t.getMessage(), t);
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.");
} }
} }
private void checkAndRequestPermissions() { private void checkAndRequestPermissions() {
List<String> permissionsNeeded = new ArrayList<>(); try {
List<String> permissionsNeeded = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
permissionsNeeded.add(Manifest.permission.RECORD_AUDIO); 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.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()) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, permissionsNeeded.toArray(new String[0]), PERMISSION_REQ_CODE); 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);
} }
} }
} }

View File

@ -722,9 +722,62 @@ async function startGoogleLogin() {
} }
if (isNativeOrLocal) { 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) { 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 <a> 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, <a href="${authUrl}" target="_system" style="color:var(--primary-color);text-decoration:underline;">clique aqui para abrir o login</a> no navegador externo.`;
} }
} else if (preOpenedPopup && !preOpenedPopup.closed) { } else if (preOpenedPopup && !preOpenedPopup.closed) {
try { try {
@ -5364,7 +5417,11 @@ async function initApp() {
} }
initServiceWorker(); initServiceWorker();
initNativePushNotifications(); try {
initNativePushNotifications();
} catch (pushInitErr) {
console.warn('[Boot] Erro seguro ao disparar initNativePushNotifications:', pushInitErr);
}
initOtaChecker(); initOtaChecker();
// Gate obrigatório de autenticação Google SSO // Gate obrigatório de autenticação Google SSO
@ -5548,80 +5605,133 @@ async function sendFcmTokenToRelay(tokenOverride = null, specificPin = null) {
async function initNativePushNotifications() { async function initNativePushNotifications() {
const cap = window.Capacitor; 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; const PushNotifications = cap?.Plugins?.PushNotifications;
if (!PushNotifications) return; if (!PushNotifications) return;
try { try {
// 1. Cria canais de alta prioridade no Android antes do registro if (typeof cap.isPluginAvailable === 'function' && !cap.isPluginAvailable('PushNotifications')) {
const isAndroid = cap.getPlatform && cap.getPlatform() === 'android'; console.warn('[FCM] Plugin PushNotifications não está disponível nesta plataforma/build.');
if (isAndroid) { return;
// 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({ } catch (e) {
id: 'maestri_urgent', console.warn('[FCM] Falha ao verificar disponibilidade do plugin PushNotifications:', e);
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));
// Canal Fallback do FCM try {
await PushNotifications.createChannel({ // 1. Cria canais de alta prioridade no Android antes do registro (com proteção defensiva)
id: 'fcm_fallback_notification_channel', const isAndroid = cap.getPlatform && cap.getPlatform() === 'android';
name: 'Notificações Maestri', if (isAndroid && typeof PushNotifications.createChannel === 'function') {
description: 'Notificações gerais e avisos de tarefas', try {
importance: 5, await PushNotifications.createChannel({
visibility: 1, id: 'maestri_urgent',
vibration: true, name: 'Alertas Críticos',
lights: true, description: 'Notificações urgentes de tarefas e aprovações do Maestri',
lightColor: '#22c55e' importance: 5,
}).catch(err => console.warn('[FCM] createChannel fcm_fallback aviso:', err)); 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 // 2. Registra os listeners OBRIGATORIAMENTE ANTES de invocar register() para evitar race conditions
PushNotifications.addListener('registration', async (token) => { if (typeof PushNotifications.addListener === 'function') {
console.log('[FCM] Token de registro nativo recebido:', token.value); try {
try { localStorage.setItem('maestri_fcm_token', token.value); } catch (e) {} PushNotifications.addListener('registration', async (token) => {
await sendFcmTokenToRelay(token.value); 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) => { PushNotifications.addListener('registrationError', (error) => {
console.error('[FCM] Erro no registro de push nativo:', error); console.warn('[FCM] Registro de push nativo reportou erro ou Firebase não configurado:', error);
}); });
PushNotifications.addListener('pushNotificationReceived', (notification) => { PushNotifications.addListener('pushNotificationReceived', (notification) => {
console.log('[FCM] Notificação recebida no cliente:', notification); console.log('[FCM] Notificação recebida no cliente:', notification);
if (typeof playNotificationSound === 'function') { if (typeof playNotificationSound === 'function') {
playNotificationSound(); 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) => { // 3. Solicita permissão e registra defensivamente (isolado em try/catch para nunca crashar na ausência do Firebase)
console.log('[FCM] Notificação acionada pelo operador:', action); try {
const data = action?.notification?.data || {}; let permResult = null;
if (data.stationId && data.agentName) { if (typeof PushNotifications.checkPermissions === 'function') {
switchStation(data.stationId); permResult = await PushNotifications.checkPermissions().catch(() => null);
setTimeout(() => { }
openChatModal(data.agentName, data.stationId); if (!permResult || permResult.receive !== 'granted') {
}, 300); if (typeof PushNotifications.requestPermissions === 'function') {
permResult = await PushNotifications.requestPermissions().catch(() => null);
}
} }
});
// 3. Solicita permissão e registra if (permResult && permResult.receive === 'granted' && typeof PushNotifications.register === 'function') {
const permResult = await PushNotifications.requestPermissions(); try {
if (permResult && permResult.receive === 'granted') { await PushNotifications.register();
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 // 4. Se já houver token em cache no localStorage, sincroniza imediatamente com o relay
const cachedToken = localStorage.getItem('maestri_fcm_token'); try {
if (cachedToken) { const cachedToken = localStorage.getItem('maestri_fcm_token');
await sendFcmTokenToRelay(cachedToken); if (cachedToken) {
await sendFcmTokenToRelay(cachedToken);
}
} catch (tokenSyncErr) {
console.warn('[FCM] Erro ao sincronizar cachedToken:', tokenSyncErr);
} }
} catch (err) { } catch (err) {
console.warn('[FCM] Erro ao inicializar notificações nativas Capacitor:', err); console.warn('[FCM] Erro ao inicializar notificações nativas Capacitor:', err);

Binary file not shown.

Binary file not shown.

View File

@ -1,9 +1,9 @@
{ {
"version": "1.0.30", "version": "1.0.30",
"buildId": "6404584d", "buildId": "45eaf454",
"releasedAt": "2026-11-22T01:09:31.913Z", "releasedAt": "2026-11-22T01:43:27.381Z",
"bundleUrl": "/bundles/bundle-1.0.30.zip", "bundleUrl": "/bundles/bundle-1.0.30.zip",
"latestUrl": "/bundles/bundle-latest.zip", "latestUrl": "/bundles/bundle-latest.zip",
"checksum": "67b46afffe8561338e9632cb3e1e008585e469831d2a10bf8343b33ac5d5f87a", "checksum": "484c403ff165b0c3571811cff21e8c7d891494138431f56fbe924b3fbb0590ad",
"sizeBytes": 73028 "sizeBytes": 74103
} }

Binary file not shown.

Binary file not shown.

View File

@ -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-width: 44px;'), 'CSS deve garantir min-width de 44px');
assert.ok(cssContent.includes('min-height: 44px;'), 'CSS deve garantir min-height 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();
}
});
}); });