diff options
Diffstat (limited to 'nwcpush')
| -rw-r--r-- | nwcpush/server.js | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/nwcpush/server.js b/nwcpush/server.js index b8c1ecd..82257da 100644 --- a/nwcpush/server.js +++ b/nwcpush/server.js @@ -61,8 +61,73 @@ webpush.setVapidDetails(CFG.vapid.subject, CFG.vapid.publicKey, CFG.vapid.privat // A subscription marked `unifiedpush` is the second kind; everything else is // a browser's. One function, so every send path serves both. const isUP = (sub) => !!(sub && sub.unifiedpush && typeof sub.endpoint === 'string'); + +// Firebase Cloud Messaging, for the Android app that runs the wallet in its +// own WebView: a phone with Google Play Services is reached through Google's +// push channel without a distributor app. The app hands the web app +// "fcm:<token>" where a UnifiedPush endpoint would go (same road, ?up=), so +// it registers as a UnifiedPush subscription and only delivery differs: the +// same JSON payload, as the data message's `body`. Needs CFG.fcm.serviceAccount +// (path to the Firebase service-account JSON); without it these fail like a +// down endpoint, and are kept. +const FCM_PREFIX = 'fcm:'; +const isFCM = (sub) => isUP(sub) && sub.endpoint.startsWith(FCM_PREFIX); +let fcmCreds = null, fcmToken = null; +function fcmAccount() { + if (fcmCreds !== null) return fcmCreds; + try { fcmCreds = CFG.fcm?.serviceAccount ? JSON.parse(readFileSync(CFG.fcm.serviceAccount, 'utf8')) : false; } + catch (e) { log(`fcm: can't read the service account (${e.message})`); fcmCreds = false; } + return fcmCreds; +} +const b64url = (b) => Buffer.from(b).toString('base64url'); +async function fcmAccessToken() { + if (fcmToken && fcmToken.exp > Date.now() + 60_000) return fcmToken.value; + const acct = fcmAccount(); + if (!acct) throw Object.assign(new Error('fcm not configured'), { statusCode: 503 }); + const now = Math.floor(Date.now() / 1000); + const head = b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' })); + const claims = b64url(JSON.stringify({ + iss: acct.client_email, scope: 'https://www.googleapis.com/auth/firebase.messaging', + aud: 'https://oauth2.googleapis.com/token', iat: now, exp: now + 3600, + })); + const pem = acct.private_key.replace(/-----[^-]+-----/g, '').replace(/\s+/g, ''); + const key = await crypto.subtle.importKey('pkcs8', Buffer.from(pem, 'base64'), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign']); + const sig = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(`${head}.${claims}`)); + 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: `${head}.${claims}.${b64url(sig)}` }), + signal: AbortSignal.timeout(8000), + }); + const j = await res.json().catch(() => ({})); + if (!res.ok || !j.access_token) throw Object.assign(new Error(`fcm auth ${res.status}`), { statusCode: 503 }); + fcmToken = { value: j.access_token, exp: Date.now() + (j.expires_in || 3600) * 1000 }; + return fcmToken.value; +} +async function deliverFCM(sub, payload, opts) { + const token = sub.endpoint.slice(FCM_PREFIX.length); + const res = await fetch(`https://fcm.googleapis.com/v1/projects/${fcmAccount().project_id}/messages:send`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: `Bearer ${await fcmAccessToken()}` }, + body: JSON.stringify({ message: { + token, + data: { body: payload }, + android: { priority: opts.urgency === 'high' ? 'HIGH' : 'NORMAL', ttl: `${opts.TTL || 3600}s` }, + } }), + signal: AbortSignal.timeout(8000), + }); + if (res.ok) return res; + const text = await res.text().catch(() => ''); + // a token the app no longer holds (uninstalled, data cleared, rotated): + // shaped as a 410 so the callers drop the registration + const gone = res.status === 404 || /UNREGISTERED|registration token is not a valid/i.test(text); + const err = new Error(`fcm ${res.status} ${text.slice(0, 120)}`); + err.statusCode = gone ? 410 : res.status; + throw err; +} + async function deliver(sub, payload, opts = {}) { if (!isUP(sub)) return webpush.sendNotification(sub, payload, opts); + if (isFCM(sub)) return deliverFCM(sub, payload, opts); const res = await fetch(sub.endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, |
