Fa arrivare le push ad app chiusa e rende diagnosticabile quando non arrivano.
Il testo della notifica viaggia ora cifrato dentro la push (aes128gcm, RFC
8188/8291) invece di essere recuperato dal service worker con una fetch al
risveglio. Era quella fetch a non chiudersi in tempo: ad app chiusa il browser
tiene vivo il worker pochi secondi, showNotification non veniva mai chiamata e
non compariva niente, mentre ad app aperta con la rete calda sembrava tutto a
posto. La POST porta anche Urgency: high, che chiede la consegna immediata
invece di far accumulare i messaggi fino al risveglio del dispositivo.
Cadono i pezzi che esistevano solo per rimediare al payload vuoto: la route
push-messaggio, la coda promemoria_push con la sua scadenza a 12 ore,
messaggioPalloniOggi() e il timeout nel worker. Tutti e tre i mittenti avevano
gia il testo pronto prima di inviare.
Il worker si aggiorna da solo all'avvio e a ogni ritorno in primo piano
(mantieniWorkerPushAggiornato): nella webapp installata quello vecchio puo
sopravvivere a lungo, e senza questo un dispositivo resterebbe fermo alla
versione che va a cercare il testo in rete.
Profilo -> Opzioni ha "Mandami una notifica di prova", visibile solo a notifiche
attive: manda una push a questo dispositivo e riporta stato HTTP, corpo della
risposta e se l'endpoint risulta davvero in push_subscriptions. Senza, "non
arriva" era cieco: ogni prova richiedeva un admin, un evento nello stato giusto
e una seconda persona, e la risposta del servizio push veniva buttata via.
inviaPush torna { stato, corpo } e logga il corpo sui rifiuti.
Dalle prove sul campo: a parita di server, iPhone installato da Home riceve ad
app chiusa. Su Android installato come webapp resta da verificare: il WebAPK e
un'app Android a se, con permesso notifiche (Android 13+) e voce batteria
distinti da quelli di Chrome. Annotato nei limiti noti.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2b8ba340a6
commit
d8f334007b
26 files changed
+782
-306
No files matched your search
+112
-21
@@ -1,4 +1,4 @@
|
||||
/** Invio di notifiche web push (senza payload) firmate con VAPID, compatibile con il runtime edge. */
|
||||
/** Invio di notifiche web push con payload cifrato (RFC 8291), firmate con VAPID, compatibile con il runtime edge. */
|
||||
|
||||
function base64UrlDecode(value: string): Uint8Array {
|
||||
const padding = "=".repeat((4 - (value.length % 4)) % 4);
|
||||
@@ -17,6 +17,16 @@ function base64UrlEncode(bytes: Uint8Array): string {
|
||||
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
|
||||
function concat(...parti: Uint8Array[]): Uint8Array {
|
||||
const out = new Uint8Array(parti.reduce((n, p) => n + p.length, 0));
|
||||
let offset = 0;
|
||||
for (const parte of parti) {
|
||||
out.set(parte, offset);
|
||||
offset += parte.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function encodeJson(value: unknown): string {
|
||||
return base64UrlEncode(new TextEncoder().encode(JSON.stringify(value)));
|
||||
}
|
||||
@@ -60,40 +70,121 @@ async function creaVapidJwt(
|
||||
return `${header}.${payload}.${base64UrlEncode(new Uint8Array(firma))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per quante ore un messaggio in coda su `promemoria_push` resta un promemoria.
|
||||
*
|
||||
* La coda si svuota solo quando il dispositivo legge il messaggio, e se la push non arriva
|
||||
* mai (registrazione scaduta: i server push accettano con 2xx e poi buttano via) la riga
|
||||
* resta lì. Senza una scadenza, la notifica successiva — di qualunque tipo — mostrerebbe
|
||||
* un sollecito di giorni prima, per un evento ormai passato.
|
||||
*/
|
||||
export const ORE_VALIDITA_PROMEMORIA = 12;
|
||||
/** Un dispositivo iscritto: endpoint del servizio push e chiavi con cui cifrare per lui. */
|
||||
export type IscrizionePush = { endpoint: string; p256dh: string; auth: string };
|
||||
|
||||
/** Un promemoria accodato è ancora attuale? */
|
||||
export function promemoriaAncoraValido(creatoIl: string, adesso: Date = new Date()): boolean {
|
||||
const creato = Date.parse(creatoIl);
|
||||
if (Number.isNaN(creato)) return false;
|
||||
return adesso.getTime() - creato < ORE_VALIDITA_PROMEMORIA * 60 * 60 * 1000;
|
||||
async function hkdf(salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, byte: number) {
|
||||
const chiave = await crypto.subtle.importKey("raw", ikm as BufferSource, "HKDF", false, [
|
||||
"deriveBits",
|
||||
]);
|
||||
const bits = await crypto.subtle.deriveBits(
|
||||
{ name: "HKDF", hash: "SHA-256", salt: salt as BufferSource, info: info as BufferSource },
|
||||
chiave,
|
||||
byte * 8,
|
||||
);
|
||||
return new Uint8Array(bits);
|
||||
}
|
||||
|
||||
/** Invia una notifica "vuota": il service worker recupera poi il testo aggiornato. */
|
||||
export async function inviaPush(endpoint: string): Promise<number> {
|
||||
function etichetta(testo: string): Uint8Array {
|
||||
return concat(new TextEncoder().encode(testo), new Uint8Array([0]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cifra il testo della notifica nel corpo della push, in formato `aes128gcm`.
|
||||
*
|
||||
* Esportata solo per i test: il payload viaggia dentro la push proprio perché il service
|
||||
* worker non abbia bisogno della rete per sapere cosa mostrare — a dispositivo dormiente
|
||||
* il browser lo sveglia per pochi secondi e una fetch di troppo lo fa morire prima di
|
||||
* `showNotification`, cioè niente notifica ad app chiusa.
|
||||
*/
|
||||
export async function cifraPayload(
|
||||
iscrizione: IscrizionePush,
|
||||
testoInChiaro: string,
|
||||
): Promise<Uint8Array> {
|
||||
const uaPublic = base64UrlDecode(iscrizione.p256dh);
|
||||
const authSecret = base64UrlDecode(iscrizione.auth);
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||
|
||||
const effimera = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [
|
||||
"deriveBits",
|
||||
]);
|
||||
const asPublic = new Uint8Array(await crypto.subtle.exportKey("raw", effimera.publicKey));
|
||||
const uaKey = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
uaPublic as BufferSource,
|
||||
{ name: "ECDH", namedCurve: "P-256" },
|
||||
false,
|
||||
[],
|
||||
);
|
||||
const condiviso = new Uint8Array(
|
||||
await crypto.subtle.deriveBits({ name: "ECDH", public: uaKey }, effimera.privateKey, 256),
|
||||
);
|
||||
|
||||
const ikm = await hkdf(
|
||||
authSecret,
|
||||
condiviso,
|
||||
concat(etichetta("WebPush: info"), uaPublic, asPublic),
|
||||
32,
|
||||
);
|
||||
const cek = await hkdf(salt, ikm, etichetta("Content-Encoding: aes128gcm"), 16);
|
||||
const nonce = await hkdf(salt, ikm, etichetta("Content-Encoding: nonce"), 12);
|
||||
|
||||
// Il delimitatore 0x02 chiude l'ultimo (e unico) record: il testo sta sotto i 4 KB.
|
||||
const chiaro = concat(new TextEncoder().encode(testoInChiaro), new Uint8Array([2]));
|
||||
const aes = await crypto.subtle.importKey("raw", cek as BufferSource, "AES-GCM", false, [
|
||||
"encrypt",
|
||||
]);
|
||||
const cifrato = new Uint8Array(
|
||||
await crypto.subtle.encrypt(
|
||||
{ name: "AES-GCM", iv: nonce as BufferSource },
|
||||
aes,
|
||||
chiaro as BufferSource,
|
||||
),
|
||||
);
|
||||
|
||||
// Intestazione RFC 8188: salt(16) | record size(4) | lunghezza chiave(1) | chiave(65).
|
||||
const dimensioneRecord = new Uint8Array(4);
|
||||
new DataView(dimensioneRecord.buffer).setUint32(0, 4096);
|
||||
return concat(salt, dimensioneRecord, new Uint8Array([asPublic.length]), asPublic, cifrato);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invia la notifica: titolo e testo viaggiano cifrati dentro la push.
|
||||
*
|
||||
* Torna anche il corpo della risposta, non solo lo stato: un servizio push che rifiuta
|
||||
* spiega il perché lì dentro, e buttarlo via lasciava i guasti indistinguibili fra loro.
|
||||
*/
|
||||
export async function inviaPush(
|
||||
iscrizione: IscrizionePush,
|
||||
titolo: string,
|
||||
testo: string,
|
||||
): Promise<{ stato: number; corpo: string }> {
|
||||
const publicKey = process.env["VAPID_PUBLIC_KEY"];
|
||||
const privateKey = process.env["VAPID_PRIVATE_KEY"];
|
||||
const subject = process.env["VAPID_SUBJECT"] ?? "mailto:crapp@crapvolley.it";
|
||||
if (!publicKey || !privateKey) throw new Error("Chiavi VAPID non configurate");
|
||||
|
||||
const audience = new URL(endpoint).origin;
|
||||
const audience = new URL(iscrizione.endpoint).origin;
|
||||
const jwt = await creaVapidJwt(audience, subject, publicKey, privateKey);
|
||||
const corpo = await cifraPayload(iscrizione, JSON.stringify({ title: titolo, body: testo }));
|
||||
|
||||
const res = await fetch(endpoint, {
|
||||
const res = await fetch(iscrizione.endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
TTL: "86400",
|
||||
// Senza `Urgency` il servizio push usa "normal", e un telefono in risparmio
|
||||
// energetico (doze) accumula i messaggi normali fino al risveglio: la notifica
|
||||
// arriva solo quando il dispositivo è già attivo, cioè quando l'app è aperta.
|
||||
// "high" chiede la consegna immediata anche a schermo spento (RFC 8030 §5.3).
|
||||
Urgency: "high",
|
||||
Authorization: `vapid t=${jwt}, k=${publicKey}`,
|
||||
"Content-Length": "0",
|
||||
"Content-Encoding": "aes128gcm",
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
body: corpo as BodyInit,
|
||||
});
|
||||
return res.status;
|
||||
|
||||
const risposta = (await res.text().catch(() => "")).slice(0, 500);
|
||||
if (!res.ok) console.error("inviaPush", res.status, risposta);
|
||||
return { stato: res.status, corpo: risposta };
|
||||
}
|
||||
Reference in new issue
Block a user