381 lines
12 KiB
JavaScript
381 lines
12 KiB
JavaScript
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<subscription>
|
|
this.fcmTokens = new Map(); // pin/stationId/default -> Set<deviceToken>
|
|
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 {
|
|
return JSON.parse(envJson);
|
|
} catch (e) {
|
|
if (fs.existsSync(envJson)) {
|
|
return JSON.parse(fs.readFileSync(envJson, 'utf8'));
|
|
}
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
initVapid() {
|
|
let vapidKeys;
|
|
if (fs.existsSync(this.keysFile)) {
|
|
try {
|
|
vapidKeys = JSON.parse(fs.readFileSync(this.keysFile, 'utf8'));
|
|
} catch (err) {
|
|
console.warn('[Relay:PushService] Erro ao ler chaves VAPID existentes, gerando novas.');
|
|
}
|
|
}
|
|
|
|
if (!vapidKeys || !vapidKeys.publicKey || !vapidKeys.privateKey) {
|
|
vapidKeys = webpush.generateVAPIDKeys();
|
|
try {
|
|
fs.writeFileSync(this.keysFile, JSON.stringify(vapidKeys, null, 2));
|
|
} catch (err) {
|
|
// Ignora se read-only
|
|
}
|
|
}
|
|
|
|
this.vapidKeys = vapidKeys;
|
|
webpush.setVapidDetails(
|
|
'mailto:admin@winicomw.ddnsfree.com',
|
|
this.vapidKeys.publicKey,
|
|
this.vapidKeys.privateKey
|
|
);
|
|
console.log('[Relay:PushService] VAPID configurado com sucesso');
|
|
}
|
|
|
|
getPublicKey() {
|
|
return this.vapidKeys.publicKey;
|
|
}
|
|
|
|
addSubscription(pin, subscription) {
|
|
if (!pin || !subscription || !subscription.endpoint) return;
|
|
if (!this.subscriptions.has(pin)) {
|
|
this.subscriptions.set(pin, new Set());
|
|
}
|
|
this.subscriptions.get(pin).add(JSON.stringify(subscription));
|
|
console.log(`[Relay:PushService] Nova subscrição de push registrada para o PIN ${pin}`);
|
|
}
|
|
|
|
addFcmToken(target, token) {
|
|
if (!target || !token || typeof token !== 'string') return;
|
|
const cleanTarget = String(target).trim();
|
|
const cleanToken = token.trim();
|
|
if (!cleanTarget || !cleanToken) return;
|
|
|
|
if (!this.fcmTokens.has(cleanTarget)) {
|
|
this.fcmTokens.set(cleanTarget, new Set());
|
|
}
|
|
this.fcmTokens.get(cleanTarget).add(cleanToken);
|
|
console.log(`[Relay:PushService] Token FCM registrado para "${cleanTarget}"`);
|
|
}
|
|
|
|
getFcmTokens(target) {
|
|
const cleanTarget = String(target || '').trim();
|
|
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) {
|
|
const cleanTarget = String(target || '').trim();
|
|
const cleanToken = String(token || '').trim();
|
|
if (this.fcmTokens.has(cleanTarget)) {
|
|
this.fcmTokens.get(cleanTarget).delete(cleanToken);
|
|
}
|
|
}
|
|
|
|
formatFcmMessage({ token, eventType, agentName, stationId, promptText, options }) {
|
|
const title = `Maestri: ${agentName || 'Alerta'}`;
|
|
const body = promptText || 'Tarefa concluída no terminal.';
|
|
const optionsStr = typeof options === 'string' ? options : JSON.stringify(options || []);
|
|
|
|
return {
|
|
token,
|
|
// 1. Bloco raiz 'notification': obrigatório para Android e iOS exibirem notificação nativa
|
|
// mesmo quando o aplicativo estiver em background, suspenso (Doze Mode) ou com a tela bloqueada.
|
|
notification: {
|
|
title,
|
|
body
|
|
},
|
|
// 2. Bloco 'data': dados operacionais para o aplicativo manipular internamente
|
|
data: {
|
|
type: eventType || 'PROMPT_PENDING',
|
|
agentName: agentName || '',
|
|
stationId: stationId || '',
|
|
prompt: body,
|
|
title,
|
|
body,
|
|
options: optionsStr,
|
|
timestamp: String(Date.now())
|
|
},
|
|
// 3. Bloco 'android': prioridade alta, canal urgente com importância máxima e visibilidade pública na tela de bloqueio
|
|
android: {
|
|
priority: 'high',
|
|
notification: {
|
|
title,
|
|
body,
|
|
channel_id: 'maestri_urgent',
|
|
channelId: 'maestri_urgent',
|
|
notification_priority: 'PRIORITY_MAX',
|
|
visibility: 'PUBLIC',
|
|
default_sound: true,
|
|
default_vibrate_timings: true,
|
|
default_light_settings: true,
|
|
click_action: 'OPEN_APP'
|
|
}
|
|
},
|
|
// 4. Bloco 'apns': Apple Push Notification Service com prioridade máxima e som
|
|
apns: {
|
|
headers: {
|
|
'apns-priority': '10'
|
|
},
|
|
payload: {
|
|
aps: {
|
|
alert: {
|
|
title,
|
|
body
|
|
},
|
|
sound: 'default',
|
|
contentAvailable: true,
|
|
badge: 1
|
|
}
|
|
}
|
|
},
|
|
// 5. Bloco 'webpush': PWA e navegadores desktop/mobile
|
|
webpush: {
|
|
headers: {
|
|
Urgency: 'high'
|
|
},
|
|
notification: {
|
|
title,
|
|
body,
|
|
requireInteraction: true
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
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 oficial
|
|
if (this.fcmServiceAccount && this.fcmServiceAccount.project_id) {
|
|
try {
|
|
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 };
|
|
}
|
|
|
|
async sendFcmNotification({ target, token, eventType, agentName, stationId, promptText, options }) {
|
|
const tokens = new Set();
|
|
if (token) tokens.add(token);
|
|
if (target) {
|
|
const stored = this.getFcmTokens(target);
|
|
for (const t of stored) tokens.add(t);
|
|
}
|
|
|
|
if (tokens.size === 0) return { count: 0 };
|
|
|
|
const results = [];
|
|
for (const t of tokens) {
|
|
const message = this.formatFcmMessage({
|
|
token: t,
|
|
eventType,
|
|
agentName,
|
|
stationId: stationId || target,
|
|
promptText,
|
|
options
|
|
});
|
|
const res = await this.dispatchFcm(message);
|
|
results.push(res);
|
|
}
|
|
|
|
return { count: tokens.size, results };
|
|
}
|
|
|
|
async sendNotification(pin, { title, body, data = {} }) {
|
|
// 1. Despacha FCM de alta prioridade se houver tokens cadastrados para a estação/PIN
|
|
const fcmTarget = pin || data?.stationId;
|
|
if (fcmTarget) {
|
|
await this.sendFcmNotification({
|
|
target: fcmTarget,
|
|
eventType: data?.type || 'PROMPT_PENDING',
|
|
agentName: data?.agentName || '',
|
|
stationId: data?.stationId || String(pin || ''),
|
|
promptText: body || title,
|
|
options: data?.options || []
|
|
}).catch(err => console.error('[Relay:PushService] Erro ao despachar FCM:', err.message));
|
|
}
|
|
|
|
// 2. Despacha WebPush para navegadores conectados
|
|
const subs = this.subscriptions.get(pin);
|
|
if (!subs || subs.size === 0) return;
|
|
|
|
const payload = JSON.stringify({
|
|
title: title || 'Maestri Remote',
|
|
body: body || 'Novo prompt aguardando sua resposta',
|
|
data,
|
|
timestamp: Date.now()
|
|
});
|
|
|
|
const deadSubs = [];
|
|
for (const subStr of subs) {
|
|
try {
|
|
const sub = JSON.parse(subStr);
|
|
await webpush.sendNotification(sub, payload);
|
|
} catch (err) {
|
|
if (err.statusCode === 410 || err.statusCode === 404) {
|
|
deadSubs.push(subStr);
|
|
} else {
|
|
console.error('[Relay:PushService] Erro ao enviar push notification:', err.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const dead of deadSubs) {
|
|
subs.delete(dead);
|
|
}
|
|
}
|
|
}
|