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:
parent
1262e85d02
commit
6c075ab0b1
@ -30,15 +30,56 @@ public class MainActivity extends BridgeActivity {
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
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() {
|
||||
try {
|
||||
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.");
|
||||
Log.w(TAG, "NotificationManager nao disponivel no sistema.");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -49,6 +90,7 @@ public class MainActivity extends BridgeActivity {
|
||||
.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",
|
||||
@ -66,8 +108,12 @@ public class MainActivity extends BridgeActivity {
|
||||
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 importância default se não encontrar o canal)
|
||||
// 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",
|
||||
@ -82,8 +128,12 @@ public class MainActivity extends BridgeActivity {
|
||||
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",
|
||||
@ -97,12 +147,19 @@ public class MainActivity extends BridgeActivity {
|
||||
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 notificação Android (maestri_urgent, fcm_fallback, default) inicializados com sucesso.");
|
||||
Log.i(TAG, "Canais de notificacao Android inicializados defensivamente.");
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.e(TAG, "Erro geral ao criar canais de notificacao: " + t.getMessage(), t);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkAndRequestPermissions() {
|
||||
try {
|
||||
List<String> permissionsNeeded = new ArrayList<>();
|
||||
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
@ -128,5 +185,8 @@ public class MainActivity extends BridgeActivity {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
136
public/app.js
136
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 <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) {
|
||||
try {
|
||||
@ -5364,7 +5417,11 @@ async function initApp() {
|
||||
}
|
||||
|
||||
initServiceWorker();
|
||||
try {
|
||||
initNativePushNotifications();
|
||||
} catch (pushInitErr) {
|
||||
console.warn('[Boot] Erro seguro ao disparar initNativePushNotifications:', pushInitErr);
|
||||
}
|
||||
initOtaChecker();
|
||||
|
||||
// Gate obrigatório de autenticação Google SSO
|
||||
@ -5548,14 +5605,30 @@ 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
|
||||
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);
|
||||
}
|
||||
|
||||
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) {
|
||||
// Canal Crítico com importância máxima (5) e luzes (sem forçar raw sound customizado para usar som padrão do sistema)
|
||||
if (isAndroid && typeof PushNotifications.createChannel === 'function') {
|
||||
try {
|
||||
await PushNotifications.createChannel({
|
||||
id: 'maestri_urgent',
|
||||
name: 'Alertas Críticos',
|
||||
@ -5566,8 +5639,11 @@ async function initNativePushNotifications() {
|
||||
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);
|
||||
}
|
||||
|
||||
// Canal Fallback do FCM
|
||||
try {
|
||||
await PushNotifications.createChannel({
|
||||
id: 'fcm_fallback_notification_channel',
|
||||
name: 'Notificações Maestri',
|
||||
@ -5578,26 +5654,33 @@ async function initNativePushNotifications() {
|
||||
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
|
||||
if (typeof PushNotifications.addListener === 'function') {
|
||||
try {
|
||||
PushNotifications.addListener('registration', async (token) => {
|
||||
console.log('[FCM] Token de registro nativo recebido:', 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) => {
|
||||
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) => {
|
||||
console.log('[FCM] Notificação recebida no cliente:', notification);
|
||||
if (typeof playNotificationSound === 'function') {
|
||||
playNotificationSound();
|
||||
try { playNotificationSound(); } catch (e) {}
|
||||
}
|
||||
if (typeof navigator !== 'undefined' && navigator.vibrate) {
|
||||
navigator.vibrate([200, 100, 200]);
|
||||
try { navigator.vibrate([200, 100, 200]); } catch (e) {}
|
||||
}
|
||||
});
|
||||
|
||||
@ -5611,18 +5694,45 @@ async function initNativePushNotifications() {
|
||||
}, 300);
|
||||
}
|
||||
});
|
||||
} catch (listenerErr) {
|
||||
console.warn('[FCM] Erro defensivo ao registrar listeners do PushNotifications:', listenerErr);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Solicita permissão e registra
|
||||
const permResult = await PushNotifications.requestPermissions();
|
||||
if (permResult && permResult.receive === 'granted') {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
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);
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@ -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
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user