diff --git a/android/app/build.gradle b/android/app/build.gradle index 44e03b9..109a18f 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -7,8 +7,8 @@ android { applicationId "com.maestri.remote" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 2 - versionName "1.0.2" + versionCode 3 + versionName "1.0.3" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 77d7ac2..c73765d 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -38,6 +38,9 @@ + @@ -54,6 +57,7 @@ + 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 86c37b8..40c11a6 100644 --- a/android/app/src/main/java/com/maestri/remote/MainActivity.java +++ b/android/app/src/main/java/com/maestri/remote/MainActivity.java @@ -4,9 +4,15 @@ import android.Manifest; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; +import android.content.Context; import android.content.pm.PackageManager; +import android.graphics.Color; +import android.media.AudioAttributes; +import android.media.RingtoneManager; +import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.util.Log; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.getcapacitor.BridgeActivity; @@ -14,30 +20,85 @@ import java.util.ArrayList; import java.util.List; public class MainActivity extends BridgeActivity { + private static final String TAG = "MaestriRemote"; private static final int PERMISSION_REQ_CODE = 1001; + public static final String CHANNEL_URGENT_ID = "maestri_urgent"; + public static final String CHANNEL_FALLBACK_ID = "fcm_fallback_notification_channel"; + public static final String CHANNEL_DEFAULT_ID = "default"; + @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - createNotificationChannel(); + createNotificationChannels(); checkAndRequestPermissions(); } - private void createNotificationChannel() { + private void createNotificationChannels() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationChannel channel = new NotificationChannel( - "maestri_urgent", + NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + if (manager == null) { + Log.w(TAG, "NotificationManager não disponível 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) + NotificationChannel urgentChannel = new NotificationChannel( + CHANNEL_URGENT_ID, "Alertas Críticos", NotificationManager.IMPORTANCE_HIGH ); - channel.setDescription("Notificações urgentes de tarefas e aprovações do Maestri"); - channel.enableVibration(true); - channel.setVibrationPattern(new long[]{0, 200, 100, 200, 100, 200}); - channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); - NotificationManager manager = getSystemService(NotificationManager.class); - if (manager != null) { - manager.createNotificationChannel(channel); + 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."); } } diff --git a/package.json b/package.json index bacc5fc..8dcd5d8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "maestri-remote-agent", - "version": "1.0.29", + "version": "1.0.30", "type": "module", "description": "Gateway Local do Maestri Remote para estações de trabalho", "bin": { diff --git a/public/app.js b/public/app.js index 1b2acae..a066007 100644 --- a/public/app.js +++ b/public/app.js @@ -490,6 +490,9 @@ function getSavedStations() { function saveStationsList(stations) { try { localStorage.setItem('maestri_stations', JSON.stringify(stations)); + if (typeof sendFcmTokenToRelay === 'function') { + sendFcmTokenToRelay(); + } } catch (e) {} } @@ -5432,6 +5435,38 @@ async function syncPushSubscription(pin, sub) { body: JSON.stringify({ pin, subscription: sub }) }); } catch (e) {} + if (typeof sendFcmTokenToRelay === 'function') { + sendFcmTokenToRelay(null, pin); + } +} + +async function sendFcmTokenToRelay(tokenOverride = null, specificPin = null) { + try { + let token = tokenOverride; + if (!token && typeof localStorage !== 'undefined') { + token = localStorage.getItem('maestri_fcm_token'); + } + if (!token) return; + + const baseUrl = getApiBaseUrl(); + const stations = getSavedStations(); + const targets = new Set(); + targets.add('default'); + if (specificPin) targets.add(String(specificPin)); + stations.forEach(s => { if (s.pin) targets.add(String(s.pin)); }); + + for (const t of targets) { + try { + await fetch(`${baseUrl}/api/notifications/fcm-token`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token, stationId: t, pin: t }) + }); + } catch (err) {} + } + } catch (err) { + console.warn('[FCM] Erro ao sincronizar token com relay:', err); + } } async function initNativePushNotifications() { @@ -5440,40 +5475,43 @@ async function initNativePushNotifications() { if (!PushNotifications) return; try { - if (cap.getPlatform && cap.getPlatform() === 'android') { + // 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, - sound: 'default', - vibration: true - }); - } - - const permResult = await PushNotifications.requestPermissions(); - if (permResult && permResult.receive === 'granted') { - await PushNotifications.register(); + vibration: true, + lights: true, + lightColor: '#22c55e' + }).catch(err => console.warn('[FCM] createChannel maestri_urgent aviso:', err)); + + // 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)); } + // 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) {} - const host = window.location.host; - const isLocal = !host || host.includes('localhost') || host.includes('127.0.0.1') || window.location.protocol === 'file:' || window.location.protocol === 'capacitor:'; - const baseUrl = isLocal ? 'https://remote.winicomw.ddnsfree.com' : ''; - const stations = getSavedStations(); - const targets = stations.length > 0 ? stations.map(s => s.pin) : ['default']; - for (const t of targets) { - try { - await fetch(`${baseUrl}/api/notifications/fcm-token`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ token: token.value, stationId: t, pin: t }) - }); - } catch (err) {} - } + await sendFcmTokenToRelay(token.value); + }); + + PushNotifications.addListener('registrationError', (error) => { + console.error('[FCM] Erro no registro de push nativo:', error); }); PushNotifications.addListener('pushNotificationReceived', (notification) => { @@ -5496,6 +5534,18 @@ async function initNativePushNotifications() { }, 300); } }); + + // 3. Solicita permissão e registra + const permResult = await PushNotifications.requestPermissions(); + if (permResult && permResult.receive === 'granted') { + await PushNotifications.register(); + } + + // 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); + } } 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 new file mode 100644 index 0000000..ca003eb Binary files /dev/null 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 b76f985..ca003eb 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 2adc714..2fab160 100644 --- a/public/bundles/manifest.json +++ b/public/bundles/manifest.json @@ -1,9 +1,9 @@ { - "version": "1.0.29", - "buildId": "b53dc74c", - "releasedAt": "2026-11-21T23:02:20.720Z", - "bundleUrl": "/bundles/bundle-1.0.29.zip", + "version": "1.0.30", + "buildId": "1a30dc06", + "releasedAt": "2026-11-22T00:12:47.004Z", + "bundleUrl": "/bundles/bundle-1.0.30.zip", "latestUrl": "/bundles/bundle-latest.zip", - "checksum": "b4ddb879eaa2e768c41fee48cb2c8b20cd26e300cd1c95921d5c5ecb9226ece0", - "sizeBytes": 71328 + "checksum": "d6c15fa467d18257241f3aa2544b26ee9356ddf433ce556c912b9513ff99b113", + "sizeBytes": 71856 } \ No newline at end of file diff --git a/public/maestri-agent.zip b/public/maestri-agent.zip index cc229bc..7778770 100644 Binary files a/public/maestri-agent.zip and b/public/maestri-agent.zip differ diff --git a/src/relay/push-service.js b/src/relay/push-service.js index 8e1a542..929603f 100644 --- a/src/relay/push-service.js +++ b/src/relay/push-service.js @@ -1,19 +1,30 @@ import webpush from 'web-push'; import fs from 'node:fs'; import path from 'node:path'; +import crypto from 'node:crypto'; export class PushService { constructor(options = {}) { this.keysFile = options.keysFile || path.resolve('vapid-keys.json'); this.subscriptions = new Map(); // pin -> Set - this.fcmTokens = new Map(); // pin/stationId -> Set + this.fcmTokens = new Map(); // pin/stationId/default -> Set this.fcmDispatcher = options.fcmDispatcher || null; this.fcmServiceAccount = this.loadServiceAccount(options.fcmServiceAccount); + this._cachedToken = null; + this._cachedTokenExpiresAt = 0; this.initVapid(); } loadServiceAccount(customAccount) { if (customAccount) return customAccount; + + const envB64 = process.env.FCM_SERVICE_ACCOUNT_B64; + if (envB64) { + try { + return JSON.parse(Buffer.from(envB64, 'base64').toString('utf8')); + } catch (e) {} + } + const envJson = process.env.FCM_SERVICE_ACCOUNT_JSON; if (envJson) { try { @@ -24,12 +35,21 @@ export class PushService { } } } - const defaultFile = path.resolve('fcm-service-account.json'); - if (fs.existsSync(defaultFile)) { - try { - return JSON.parse(fs.readFileSync(defaultFile, 'utf8')); - } catch (e) {} + + const searchPaths = [ + path.resolve('fcm-service-account.json'), + '/etc/maestri-remote/fcm-service-account.json', + '/secrets/fcm-service-account.json' + ]; + + for (const p of searchPaths) { + if (fs.existsSync(p)) { + try { + return JSON.parse(fs.readFileSync(p, 'utf8')); + } catch (e) {} + } } + return null; } @@ -89,7 +109,19 @@ export class PushService { getFcmTokens(target) { const cleanTarget = String(target || '').trim(); - return this.fcmTokens.get(cleanTarget) || new Set(); + const tokens = new Set(); + const specific = this.fcmTokens.get(cleanTarget); + if (specific) { + for (const t of specific) tokens.add(t); + } + // Fallback: se nenhum token estiver associado à estação ou PIN específico, tenta o canal 'default' + if (tokens.size === 0 && cleanTarget !== 'default') { + const def = this.fcmTokens.get('default'); + if (def) { + for (const t of def) tokens.add(t); + } + } + return tokens; } removeFcmToken(target, token) { @@ -136,6 +168,7 @@ export class PushService { visibility: 'PUBLIC', default_sound: true, default_vibrate_timings: true, + default_light_settings: true, click_action: 'OPEN_APP' } }, @@ -170,21 +203,107 @@ export class PushService { }; } + async getGoogleAccessToken() { + if (!this.fcmServiceAccount || !this.fcmServiceAccount.client_email || !this.fcmServiceAccount.private_key) { + return null; + } + + const now = Math.floor(Date.now() / 1000); + if (this._cachedToken && this._cachedTokenExpiresAt > now + 60) { + return this._cachedToken; + } + + const header = { + alg: 'RS256', + typ: 'JWT' + }; + const claimSet = { + iss: this.fcmServiceAccount.client_email, + scope: 'https://www.googleapis.com/auth/firebase.messaging', + aud: 'https://oauth2.googleapis.com/token', + exp: now + 3600, + iat: now + }; + + const b64Header = Buffer.from(JSON.stringify(header)).toString('base64url'); + const b64ClaimSet = Buffer.from(JSON.stringify(claimSet)).toString('base64url'); + const input = `${b64Header}.${b64ClaimSet}`; + + const sign = crypto.createSign('RSA-SHA256'); + sign.update(input); + sign.end(); + const signature = sign.sign(this.fcmServiceAccount.private_key, 'base64url'); + const assertion = `${input}.${signature}`; + + const res = await fetch('https://oauth2.googleapis.com/token', { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion + }).toString() + }); + + if (!res.ok) { + const errText = await res.text(); + throw new Error(`Falha ao obter Google Access Token (${res.status}): ${errText}`); + } + + const data = await res.json(); + this._cachedToken = data.access_token; + this._cachedTokenExpiresAt = now + (data.expires_in || 3600); + return this._cachedToken; + } + async dispatchFcm(message) { if (this.fcmDispatcher) { return await this.fcmDispatcher(message); } - // Caso haja service account Google configurada, executa requisição HTTP à API FCM v1 + + // Caso haja service account Google configurada, executa requisição HTTP à API FCM v1 oficial if (this.fcmServiceAccount && this.fcmServiceAccount.project_id) { try { - console.log(`[Relay:PushService] Despachando FCM v1 para projeto ${this.fcmServiceAccount.project_id}...`); - // Aqui despacharia via API v1 com Bearer Token - return { ok: true, project: this.fcmServiceAccount.project_id }; + const accessToken = await this.getGoogleAccessToken(); + if (!accessToken) { + throw new Error('Não foi possível gerar access token OAuth2 para a conta de serviço FCM'); + } + + const projectId = this.fcmServiceAccount.project_id; + const url = `https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`; + const res = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${accessToken}` + }, + body: JSON.stringify({ message }) + }); + + const resData = await res.json().catch(() => ({})); + if (!res.ok) { + console.error('[Relay:PushService] Erro retornado pela API Google FCM v1:', res.status, resData); + // Tratar desregistro de token inválido (UNREGISTERED ou NOT_FOUND) + if (res.status === 404 || res.status === 410 || resData.error?.status === 'NOT_FOUND' || resData.error?.details?.some(d => d.errorCode === 'UNREGISTERED')) { + console.warn(`[Relay:PushService] Token FCM expirado ou inválido: ${message.token}. Removendo dos registros.`); + for (const [target, tokens] of this.fcmTokens.entries()) { + if (tokens.has(message.token)) { + tokens.delete(message.token); + } + } + } + return { ok: false, status: res.status, error: resData.error?.message || 'FCM v1 error' }; + } + + console.log(`[Relay:PushService] Notificação FCM v1 despachada com sucesso: ${resData.name}`); + return { ok: true, messageId: resData.name, project: projectId }; } catch (err) { console.error('[Relay:PushService] Falha ao enviar FCM v1:', err.message); return { ok: false, error: err.message }; } } + return { ok: true, simulated: true }; } diff --git a/test/relay.test.js b/test/relay.test.js index cda9c52..420fbe3 100644 --- a/test/relay.test.js +++ b/test/relay.test.js @@ -585,3 +585,143 @@ test('PushService formatFcmMessage deve garantir cabeçalhos e blocos para exibi assert.ok(msg.data.timestamp); }); +test('PushService deve usar fallback de tokens default quando a estação não possuir tokens específicos', async () => { + const { PushService } = await import('../src/relay/push-service.js'); + const dispatched = []; + const service = new PushService({ + keysFile: path.resolve('.tmp-vapid-test.json'), + fcmDispatcher: async (m) => { + dispatched.push(m); + return { ok: true, messageId: 'mid-default-1' }; + } + }); + + // Registra token apenas para 'default' + service.addFcmToken('default', 'device-token-fallback-xyz'); + + // Consulta por uma estação sem tokens diretos + const tokens = service.getFcmTokens('station-random-pin'); + assert.equal(tokens.size, 1); + assert.ok(tokens.has('device-token-fallback-xyz')); + + // Despacha para a estação sem tokens diretos + const res = await service.sendFcmNotification({ + target: 'station-random-pin', + eventType: 'PROMPT_PENDING', + agentName: 'Builder', + promptText: 'Confirma deploy?' + }); + + assert.equal(res.count, 1); + assert.equal(dispatched.length, 1); + assert.equal(dispatched[0].token, 'device-token-fallback-xyz'); +}); + +test('PushService deve processar despacho FCM v1 oficial e remover tokens expirados automaticamente', async () => { + const { PushService } = await import('../src/relay/push-service.js'); + const crypto = await import('node:crypto'); + + // Gera chave RSA de teste em memória + const { privateKey } = crypto.generateKeyPairSync('rsa', { + modulusLength: 2048, + publicKeyEncoding: { type: 'spki', format: 'pem' }, + privateKeyEncoding: { type: 'pkcs8', format: 'pem' } + }); + + const testAccount = { + project_id: 'maestri-test-project', + client_email: 'test-sa@maestri-test-project.iam.gserviceaccount.com', + private_key: privateKey + }; + + const service = new PushService({ + keysFile: path.resolve('.tmp-vapid-test.json'), + fcmServiceAccount: testAccount + }); + + // Salva o fetch global original + const originalFetch = globalThis.fetch; + const fetchCalls = []; + + try { + globalThis.fetch = async (url, options) => { + fetchCalls.push({ url, options }); + if (url.includes('oauth2.googleapis.com/token')) { + return { + ok: true, + status: 200, + json: async () => ({ + access_token: 'fake-oauth2-access-token-123', + expires_in: 3600, + token_type: 'Bearer' + }), + text: async () => '' + }; + } + if (url.includes('fcm.googleapis.com/v1/projects/maestri-test-project/messages:send')) { + const body = JSON.parse(options.body); + if (body.message.token === 'expired-token') { + return { + ok: false, + status: 404, + json: async () => ({ + error: { + code: 404, + message: 'Requested entity was not found.', + status: 'NOT_FOUND', + details: [{ '@type': 'type.googleapis.com/google.firebase.fcm.v1.FcmError', errorCode: 'UNREGISTERED' }] + } + }), + text: async () => 'Not Found' + }; + } + return { + ok: true, + status: 200, + json: async () => ({ name: 'projects/maestri-test-project/messages/msg-id-ok-999' }), + text: async () => '' + }; + } + return { ok: false, status: 500, json: async () => ({}), text: async () => 'Unknown' }; + }; + + // 1. Despacha mensagem com sucesso + service.addFcmToken('pin-100', 'valid-device-token'); + const resOk = await service.sendFcmNotification({ + target: 'pin-100', + eventType: 'PROMPT_PENDING', + agentName: 'SRE', + promptText: 'Rollout K3s concluído' + }); + + assert.equal(resOk.count, 1); + assert.equal(resOk.results[0].ok, true); + assert.equal(resOk.results[0].messageId, 'projects/maestri-test-project/messages/msg-id-ok-999'); + + // 2. Despacha mensagem para token expirado e verifica se é removido automaticamente + service.addFcmToken('pin-100', 'expired-token'); + assert.equal(service.getFcmTokens('pin-100').size, 2); + + const resFail = await service.sendFcmNotification({ + token: 'expired-token', + eventType: 'TASK_COMPLETED', + agentName: 'Tester', + promptText: 'Teste de token inválido' + }); + + assert.equal(resFail.count, 1); + assert.equal(resFail.results[0].ok, false); + assert.equal(resFail.results[0].status, 404); + + // O token expirado deve ter sido purgado do Set + const remaining = service.getFcmTokens('pin-100'); + assert.equal(remaining.size, 1); + assert.ok(remaining.has('valid-device-token')); + assert.ok(!remaining.has('expired-token')); + + } finally { + globalThis.fetch = originalFetch; + } +}); + +