@astratra/notify 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  Les messages sortants, faits une fois : **e-mail, SMS, notifications poussées**.
4
4
 
5
- Le transport est toujours injecté — SMTP, une API HTTP, Twilio, Infobip,
6
- web-push, Expo. Ce package apporte l'anneau autour, et c'est le même anneau
7
- pour les trois canaux :
5
+ Le transport est injecté — SMTP, une API HTTP, Twilio, Infobip, Expo — ou
6
+ fourni pour les notifications web et Apple, sans SDK. Ce package apporte
7
+ l'anneau autour, et c'est le même anneau pour les trois canaux :
8
8
 
9
9
  - **rien ne lève jamais** — un message est la conséquence d'une action, pas
10
10
  l'action ;
@@ -192,8 +192,8 @@ traiter** :
192
192
  const { createPushSender } = require('@astratra/notify');
193
193
 
194
194
  const push = createPushSender({
195
- transport: (subscription, payload) =>
196
- webpush.sendNotification(subscription, JSON.stringify(payload)),
195
+ // createWebPushTransport (plus bas), Expo, le tien : tout transport qui lève avec le statut du fournisseur.
196
+ transport: (subscription, payload) => monFournisseur.send(subscription, payload),
197
197
  // LE point du module : l'abonnement mort t'est rendu pour suppression.
198
198
  onGone: (subscription) => Subscriptions.deleteOne({ endpoint: subscription.endpoint }),
199
199
  concurrency: 10, // défaut : 10 envois simultanés au maximum
@@ -217,8 +217,60 @@ désordre, `errors` suit toujours l'ordre des abonnements d'entrée (et conserve
217
217
  sa limite historique de dix raisons).
218
218
 
219
219
  Le statut du fournisseur est cherché où qu'il l'ait mis — `statusCode`,
220
- `status`, `response.status` — parce que web-push et les clients HTTP ne sont pas
221
- d'accord entre eux.
220
+ `status`, `response.status` — parce que les clients HTTP ne sont pas d'accord
221
+ entre eux.
222
+
223
+ ## Les notifications web, en direct : `createWebPushTransport`
224
+
225
+ Web Push sans bibliothèque : le message est chiffré pour le navigateur
226
+ (RFC 8291, « aes128gcm »), signé par le serveur (VAPID, RFC 8292) et remis au
227
+ service de notification du navigateur (Google, Mozilla, Apple, Microsoft).
228
+ Il remplace web-push.
229
+
230
+ ```js
231
+ const { createWebPushTransport, createPushSender, generateVapidKeys } = require('@astratra/notify');
232
+
233
+ // Une fois : la paire de clés VAPID, à garder dans l'environnement.
234
+ // const { publicKey, privateKey } = generateVapidKeys();
235
+
236
+ const transport = createWebPushTransport({
237
+ vapid: { subject: 'mailto:contact@exemple.fr', publicKey: process.env.VAPID_PUBLIQUE, privateKey: process.env.VAPID_PRIVEE },
238
+ ttl: 86_400, // le service garde le message un jour (défaut : quatre semaines)
239
+ urgency: 'normal', // very-low, low, normal, high
240
+ });
241
+ const push = createPushSender({ transport, onGone: (s) => Abonnements.deleteOne({ endpoint: s.endpoint }) });
242
+
243
+ await push.broadcast(abonnements, { title: 'Nouveau message', body: 'Ouvrez l’application' });
244
+ ```
245
+
246
+ `abonnement` est ce que le navigateur donne (`PushSubscription.toJSON()` :
247
+ `{ endpoint, keys: { p256dh, auth } }`). Un objet est envoyé en JSON ; un texte
248
+ ou un Buffer tel quel.
249
+
250
+ - **L'adresse d'abonnement est vérifiée** : https:// seulement, sans
251
+ identifiants, et sur un service connu (`KNOWN_PUSH_HOSTS`). Sinon, n'importe
252
+ quel abonné ferait appeler n'importe quelle adresse à ton serveur (une adresse
253
+ interne, un service de métadonnées). Un service à toi : `extraHosts`.
254
+ - **Le service ne peut pas faire attendre ni noyer le serveur** : délai de 30 s
255
+ (`timeoutMs`), réponse lue jusqu'à 64 Kio, redirection jamais suivie.
256
+ - **Les clés sont lues à la création** : une clé VAPID mal formée, ou une clé
257
+ publique qui ne va pas avec la clé privée, échoue au démarrage (avec
258
+ web-push, le service répondait 403 à chaque envoi).
259
+ - **L'en-tête VAPID est gardé par service** et refait quand il lui reste moins
260
+ d'une heure (il vaut 12 h).
261
+ - Un message de plus de 3 993 octets (la limite de la RFC 8291) ou une clé
262
+ d'appareil hors de la courbe P-256 est refusé avant tout envoi.
263
+
264
+ Pour un envoi isolé, `sendWebPush(abonnement, texte, { vapid, ttl, urgency,
265
+ topic })` prend les mêmes arguments que `webpush.sendNotification` (`vapidDetails`,
266
+ `TTL` et `timeout` sont aussi acceptés), et rend les mêmes résultats et les
267
+ mêmes erreurs (`WebPushError` avec `statusCode`, `headers`, `body`,
268
+ `endpoint`). `buildWebPushRequest` prépare la requête sans l'envoyer.
269
+ `decryptWebPush` fait le travail du navigateur, pour tes essais.
270
+
271
+ Pas repris de web-push : l'ancien chiffrement « aesgcm » (un brouillon de 2016,
272
+ remplacé partout), les clés GCM (service fermé en 2019) et l'option `proxy`
273
+ (passe un `agent` HTTPS, par exemple celui de ton mandataire).
222
274
 
223
275
  ## Les notifications Apple, en direct : `createApnsTransport`
224
276
 
@@ -403,9 +455,10 @@ test('le catalogue des notifications', () => {
403
455
 
404
456
  ## Ce que ce package ne fait pas
405
457
 
406
- - Il n'envoie **rien** lui-même, sauf vers Apple avec `createApnsTransport` :
407
- les autres transports sont injectés. Aucun SDK — ni nodemailer, ni Twilio,
408
- ni web-push — n'est importé.
458
+ - Il n'envoie **rien** lui-même, sauf vers Apple avec `createApnsTransport` et
459
+ vers les navigateurs avec `createWebPushTransport` : les autres transports
460
+ sont injectés. Aucun SDK — ni nodemailer, ni Twilio, ni web-push — n'est
461
+ importé.
409
462
  - Il ne stocke pas les abonnements : il te rend les morts, tu les supprimes.
410
463
  Il ne tient pas non plus de registre d'appareils par compte : tu choisis la
411
464
  liste, `broadcast` l'envoie.
@@ -420,4 +473,5 @@ test('le catalogue des notifications', () => {
420
473
 
421
474
  ```bash
422
475
  npm test --workspace @astratra/notify
476
+ npm run verify:mutations --workspace @astratra/notify # 16 mutations du module Web Push
423
477
  ```
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@astratra/notify",
3
- "version": "1.2.0",
4
- "description": "Outbound messages done once — email, SMS and push. Transport injected, never throws, header-injection safe, loud simulation when unconfigured, dead push subscriptions handed back for pruning.",
3
+ "version": "1.3.0",
4
+ "description": "Outbound messages done once — email, SMS and push. Transport injected, never throws, header-injection safe, loud simulation when unconfigured, dead push subscriptions handed back for pruning. Web Push (RFC 8291, VAPID) and APNs built in, no SDK.",
5
5
  "engines": {
6
6
  "node": ">=22"
7
7
  },
@@ -12,7 +12,8 @@
12
12
  "src"
13
13
  ],
14
14
  "scripts": {
15
- "test": "jest"
15
+ "test": "jest",
16
+ "verify:mutations": "node scripts/verify-web-push-mutations.cjs"
16
17
  },
17
18
  "jest": {
18
19
  "testMatch": [
@@ -24,6 +25,8 @@
24
25
  "email",
25
26
  "sms",
26
27
  "push",
28
+ "web-push",
29
+ "vapid",
27
30
  "notifications",
28
31
  "transactional"
29
32
  ],
@@ -32,6 +35,7 @@
32
35
  "access": "public"
33
36
  },
34
37
  "devDependencies": {
38
+ "@astratra/testkit": "^2.0.0",
35
39
  "jest": "30.4.2"
36
40
  }
37
41
  }
package/src/index.d.ts CHANGED
@@ -350,3 +350,80 @@ export function createApnsTransport(options: {
350
350
  now?: () => number;
351
351
  }): ApnsTransport;
352
352
  export function apnsBody(payload: ApnsPayload): string;
353
+
354
+ /** A browser push subscription, as PushSubscription.toJSON() gives it. */
355
+ export interface WebPushSubscription {
356
+ endpoint: string;
357
+ keys?: { p256dh: string; auth: string };
358
+ }
359
+ export interface VapidKeys {
360
+ /** An https: URL or a mailto: address the push service can reach you at. */
361
+ subject: string;
362
+ /** 65-byte uncompressed P-256 point, URL-safe base64 without "=". */
363
+ publicKey: string;
364
+ /** 32-byte P-256 scalar, URL-safe base64 without "=". */
365
+ privateKey: string;
366
+ }
367
+ export interface WebPushOptions {
368
+ vapid?: VapidKeys;
369
+ /** web-push's name for `vapid`. */
370
+ vapidDetails?: VapidKeys;
371
+ /** Seconds the push service keeps the message. Default 2 419 200 (four weeks). */
372
+ ttl?: number;
373
+ /** web-push's name for `ttl`. */
374
+ TTL?: number | string;
375
+ urgency?: 'very-low' | 'low' | 'normal' | 'high';
376
+ /** Replaces an undelivered message with the same topic (at most 32 URL-safe base64 characters). */
377
+ topic?: string;
378
+ /** Extra headers; the ones the library sets cannot be overridden. */
379
+ headers?: Record<string, string | number>;
380
+ /** Default 30 000. */
381
+ timeoutMs?: number;
382
+ /** web-push's name for `timeoutMs`. */
383
+ timeout?: number;
384
+ /** An https.Agent (a proxy agent, a custom CA). */
385
+ agent?: import('node:https').Agent;
386
+ /** Push service hosts allowed besides KNOWN_PUSH_HOSTS (a subdomain matches). */
387
+ extraHosts?: string[];
388
+ /** Skip the host check (a self-hosted push service whose hosts you cannot list). */
389
+ allowAnyHost?: boolean;
390
+ /** VAPID token expiry, UNIX seconds, at most 24 hours ahead. Default 12 hours. */
391
+ expiration?: number;
392
+ /** Only 'aes128gcm'. */
393
+ contentEncoding?: 'aes128gcm';
394
+ now?: () => number;
395
+ }
396
+ export interface WebPushResult {
397
+ statusCode: number;
398
+ body: string;
399
+ headers: Record<string, string | string[] | undefined>;
400
+ }
401
+ export class WebPushError extends Error {
402
+ name: 'WebPushError';
403
+ /** 'invalid_request' (refused before sending), 'timeout', 'decrypt_failed'. */
404
+ code?: 'invalid_request' | 'timeout' | 'decrypt_failed';
405
+ /** The push service's status, when it answered outside 2xx. */
406
+ statusCode?: number;
407
+ headers?: Record<string, string | string[] | undefined>;
408
+ /** The service's answer, cut at 64 KiB. */
409
+ body?: string;
410
+ endpoint?: string;
411
+ }
412
+ export const KNOWN_PUSH_HOSTS: readonly string[];
413
+ export function generateVapidKeys(): { publicKey: string; privateKey: string };
414
+ export function vapidAuthorization(options: { audience: string; vapid: VapidKeys; expiration?: number; now?: () => number }): { authorization: string; expiration: number };
415
+ export function encryptWebPush(options: { p256dh: string; auth: string; payload: string | Uint8Array; deterministic?: { salt: string; privateKey: string } }): Buffer;
416
+ export function decryptWebPush(options: { body: Uint8Array; privateKey: string; p256dh: string; auth: string }): Buffer;
417
+ export function buildWebPushRequest(subscription: WebPushSubscription, payload?: string | Uint8Array | null, options?: WebPushOptions): {
418
+ endpoint: string;
419
+ method: 'POST';
420
+ headers: Record<string, string>;
421
+ body: Buffer | null;
422
+ timeoutMs: number;
423
+ agent?: import('node:https').Agent;
424
+ };
425
+ export function sendWebPush(subscription: WebPushSubscription, payload?: string | Uint8Array | null, options?: WebPushOptions): Promise<WebPushResult>;
426
+ export interface WebPushTransport {
427
+ (subscription: WebPushSubscription, payload: string | Uint8Array | Record<string, unknown> | null, overrides?: Omit<WebPushOptions, 'vapid' | 'vapidDetails'>): Promise<WebPushResult>;
428
+ }
429
+ export function createWebPushTransport(options: WebPushOptions & { vapid: VapidKeys }): WebPushTransport;
package/src/index.js CHANGED
@@ -5,6 +5,7 @@ module.exports = {
5
5
  ...require('./sms'),
6
6
  ...require('./push'),
7
7
  ...require('./apns'),
8
+ ...require('./webPush'),
8
9
  ...require('./inbox'),
9
10
  ...require('./catalog')
10
11
  };
package/src/webPush.js ADDED
@@ -0,0 +1,428 @@
1
+ const crypto = require('node:crypto');
2
+ const https = require('node:https');
3
+
4
+ /*
5
+ * Web Push, sans bibliothèque : le chiffrement du message (RFC 8291 sur RFC 8188, « aes128gcm »), la signature du
6
+ * serveur (VAPID, RFC 8292) et l'envoi au service de notification du navigateur (RFC 8030), avec node:crypto et
7
+ * node:https. Il remplace web-push : mêmes octets que http_ece à sel et clé égaux, mêmes en-têtes que web-push 3.6.7,
8
+ * vecteur de la RFC 8291 vérifié.
9
+ *
10
+ * Différences voulues avec web-push :
11
+ * - l'adresse d'un abonnement doit être en https:// et viser un service de notification connu (KNOWN_PUSH_HOSTS,
12
+ * plus `extraHosts`) : sinon, n'importe quel abonné ferait appeler n'importe quelle adresse au serveur ;
13
+ * - la réponse du service est lue jusqu'à 64 Kio, un délai de 30 s s'applique par défaut, une redirection n'est
14
+ * jamais suivie ;
15
+ * - un message de plus de 3 993 octets est refusé (la limite de la RFC 8291), une clé d'appareil hors de la courbe
16
+ * aussi, avant tout envoi ;
17
+ * - la clé publique VAPID doit aller avec la clé privée (web-push enverrait, et le service répondrait 403) ;
18
+ * - une échéance VAPID passée, un TTL qui n'est pas un entier, un en-tête en double ou mal formé sont refusés ;
19
+ * - seul « aes128gcm » est pris : « aesgcm » (brouillon de 2016) et les clés GCM (service fermé en 2019) ne
20
+ * servent plus ; un mandataire passe par `agent`.
21
+ * Toute erreur d'entrée est une WebPushError de code « invalid_request », sans `statusCode` ; une réponse du service
22
+ * hors 2xx est une WebPushError avec `statusCode`, `headers`, `body` et `endpoint`, comme web-push.
23
+ */
24
+
25
+ const KNOWN_PUSH_HOSTS = Object.freeze(['fcm.googleapis.com', 'push.services.mozilla.com', 'web.push.apple.com', 'notify.windows.com']);
26
+ const DEFAULT_TTL = 2_419_200; // quatre semaines, comme web-push
27
+ const DEFAULT_TIMEOUT_MS = 30_000;
28
+ const DEFAULT_EXPIRATION_SECONDS = 12 * 3600;
29
+ const MAX_EXPIRATION_SECONDS = 24 * 3600;
30
+ const RECORD_SIZE = 4096;
31
+ const MAX_PAYLOAD = 3993; // RFC 8291, section 4 : 4096 − 86 (en-tête) − 16 (étiquette) − 1 (délimiteur)
32
+ const MAX_RESPONSE = 64 * 1024;
33
+ const URGENCIES = new Set(['very-low', 'low', 'normal', 'high']);
34
+ const MANAGED_HEADERS = new Set(['ttl', 'content-length', 'content-type', 'content-encoding', 'authorization', 'urgency', 'topic', 'host', 'crypto-key', 'encryption']);
35
+ const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]{1,64}$/;
36
+ const B64URL = /^[A-Za-z0-9_-]+$/;
37
+ const B64_ANY = /^[A-Za-z0-9+/_-]+={0,2}$/;
38
+ const OPTION_KEYS = new Set(['vapid', 'vapidDetails', 'ttl', 'TTL', 'urgency', 'topic', 'headers', 'timeoutMs', 'timeout', 'agent', 'extraHosts', 'allowAnyHost', 'expiration', 'contentEncoding', 'now']);
39
+
40
+ class WebPushError extends Error {
41
+ constructor(message, { statusCode, headers, body, endpoint, code } = {}) {
42
+ super(message);
43
+ this.name = 'WebPushError';
44
+ if (code) this.code = code;
45
+ if (statusCode !== undefined) this.statusCode = statusCode;
46
+ if (headers !== undefined) this.headers = headers;
47
+ if (body !== undefined) this.body = body;
48
+ if (endpoint !== undefined) this.endpoint = endpoint;
49
+ }
50
+ }
51
+
52
+ const invalid = (message) => new WebPushError(message, { code: 'invalid_request' });
53
+
54
+ /** Une clé d'abonnement : base64url (ou base64, avec ou sans « = »), comme le navigateur la donne. */
55
+ function decodeSubscriptionKey(value, name, { min, max }) {
56
+ if (typeof value !== 'string' || value.length === 0 || value.length > 200 || !B64_ANY.test(value)) throw invalid(`subscription keys.${name} must be a base64url string`);
57
+ const bytes = Buffer.from(value, 'base64url');
58
+ if (bytes.length < min || bytes.length > max) throw invalid(min === max ? `subscription keys.${name} must be ${min} bytes` : `subscription keys.${name} must be ${min} to ${max} bytes`);
59
+ return bytes;
60
+ }
61
+
62
+ /** Une clé VAPID : base64url strict, sans « = » (comme web-push). */
63
+ function decodeVapidKey(value, name, length) {
64
+ if (typeof value !== 'string' || value.length === 0 || value.length > 100 || !B64URL.test(value)) throw invalid(`VAPID ${name} must be a URL-safe base64 string without "="`);
65
+ const bytes = Buffer.from(value, 'base64url');
66
+ if (bytes.length !== length) throw invalid(`VAPID ${name} must be ${length} bytes long when decoded`);
67
+ return bytes;
68
+ }
69
+
70
+ /** Un point P-256 non compressé (65 octets, 0x04 en tête) qui est bien sur la courbe. */
71
+ function checkPoint(bytes, name) {
72
+ if (bytes[0] !== 0x04) throw invalid(`${name} must be an uncompressed P-256 point`);
73
+ try {
74
+ crypto.ECDH.convertKey(bytes, 'prime256v1', undefined, undefined, 'uncompressed');
75
+ } catch {
76
+ throw invalid(`${name} is not a point on P-256`);
77
+ }
78
+ return bytes;
79
+ }
80
+
81
+ function checkSubject(subject) {
82
+ if (typeof subject !== 'string' || !subject || subject.length > 512) throw invalid('VAPID subject must be an https: URL or a mailto: address');
83
+ let parsed;
84
+ try {
85
+ parsed = new URL(subject);
86
+ } catch {
87
+ throw invalid('VAPID subject is not a valid URL');
88
+ }
89
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'mailto:') throw invalid('VAPID subject must be an https: URL or a mailto: address');
90
+ return subject;
91
+ }
92
+
93
+ /**
94
+ * Les clés VAPID lues une fois : le sujet, la clé publique, et la clé privée en objet KeyObject. La clé publique doit
95
+ * être celle de la clé privée.
96
+ */
97
+ function parseVapid(vapid) {
98
+ if (!vapid || typeof vapid !== 'object') throw invalid('vapid must be { subject, publicKey, privateKey }');
99
+ const subject = checkSubject(vapid.subject);
100
+ const publicBytes = checkPoint(decodeVapidKey(vapid.publicKey, 'public key', 65), 'VAPID public key');
101
+ const privateBytes = decodeVapidKey(vapid.privateKey, 'private key', 32);
102
+ const ecdh = crypto.createECDH('prime256v1');
103
+ try {
104
+ ecdh.setPrivateKey(privateBytes);
105
+ } catch {
106
+ throw invalid('VAPID private key is not a valid P-256 key');
107
+ }
108
+ if (!ecdh.getPublicKey().equals(publicBytes)) throw invalid('VAPID public key does not match the private key');
109
+ const key = crypto.createPrivateKey({
110
+ format: 'jwk',
111
+ key: { kty: 'EC', crv: 'P-256', d: privateBytes.toString('base64url'), x: publicBytes.subarray(1, 33).toString('base64url'), y: publicBytes.subarray(33).toString('base64url') },
112
+ });
113
+ return { subject, publicKey: vapid.publicKey, key };
114
+ }
115
+
116
+ /** Une paire de clés VAPID neuve, au format de web-push (base64url : 65 octets publics, 32 privés). */
117
+ function generateVapidKeys() {
118
+ const ecdh = crypto.createECDH('prime256v1');
119
+ ecdh.generateKeys();
120
+ // Une clé privée qui commence par des zéros sort plus courte : elle est complétée à 32 octets (comme web-push).
121
+ const privateKey = ecdh.getPrivateKey();
122
+ return { publicKey: ecdh.getPublicKey().toString('base64url'), privateKey: Buffer.concat([Buffer.alloc(32 - privateKey.length), privateKey]).toString('base64url') };
123
+ }
124
+
125
+ const b64json = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
126
+
127
+ /**
128
+ * L'en-tête Authorization VAPID (RFC 8292) : « vapid t=<JWT ES256>, k=<clé publique> ». `audience` est l'origine du
129
+ * service (« https://fcm.googleapis.com ») ; `expiration` (secondes) au plus 24 h plus tard, 12 h par défaut.
130
+ */
131
+ function vapidAuthorization({ audience, vapid, expiration, now = Date.now } = {}) {
132
+ const parsed = vapid && vapid.key ? vapid : parseVapid(vapid);
133
+ let origin;
134
+ try {
135
+ origin = new URL(audience);
136
+ } catch {
137
+ throw invalid('VAPID audience must be the origin of a push service');
138
+ }
139
+ if (origin.protocol !== 'https:' || `${origin.protocol}//${origin.host}` !== audience) throw invalid('VAPID audience must be an https origin, without path');
140
+ const seconds = Math.floor(now() / 1000);
141
+ let exp = seconds + DEFAULT_EXPIRATION_SECONDS;
142
+ if (expiration !== undefined) {
143
+ if (!Number.isInteger(expiration) || expiration <= seconds) throw invalid('VAPID expiration must be a future timestamp in seconds');
144
+ if (expiration > seconds + MAX_EXPIRATION_SECONDS) throw invalid('VAPID expiration must be at most 24 hours ahead');
145
+ exp = expiration;
146
+ }
147
+ const unsigned = `${b64json({ typ: 'JWT', alg: 'ES256' })}.${b64json({ aud: audience, exp, sub: parsed.subject })}`;
148
+ const signature = crypto.sign('sha256', Buffer.from(unsigned), { key: parsed.key, dsaEncoding: 'ieee-p1363' }).toString('base64url');
149
+ return { authorization: `vapid t=${unsigned}.${signature}, k=${parsed.publicKey}`, expiration: exp };
150
+ }
151
+
152
+ function toPayload(payload) {
153
+ if (payload === undefined || payload === null || payload === '') return null;
154
+ let bytes;
155
+ if (typeof payload === 'string') bytes = Buffer.from(payload, 'utf8');
156
+ else if (payload instanceof Uint8Array) bytes = Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
157
+ else throw invalid('payload must be a string or a Buffer');
158
+ // La taille est vérifiée par encryptWebPush.
159
+ return bytes.length === 0 ? null : bytes;
160
+ }
161
+
162
+ /**
163
+ * Chiffre un message pour un abonnement (RFC 8291, un seul enregistrement aes128gcm). Rend le corps à envoyer :
164
+ * en-tête de 86 octets (sel, taille d'enregistrement, clé publique éphémère du serveur) puis le texte chiffré.
165
+ * `deterministic: { salt, privateKey }` (base64url) ne sert qu'aux vecteurs d'essai : un sel réutilisé avec la même
166
+ * clé éphémère révèle les messages.
167
+ */
168
+ function encryptWebPush({ p256dh, auth, payload, deterministic } = {}) {
169
+ const uaPublic = checkPoint(decodeSubscriptionKey(p256dh, 'p256dh', { min: 65, max: 65 }), 'subscription keys.p256dh');
170
+ const authSecret = decodeSubscriptionKey(auth, 'auth', { min: 16, max: 64 });
171
+ const plaintext = typeof payload === 'string' || payload instanceof Uint8Array ? Buffer.from(payload) : null;
172
+ if (!plaintext) throw invalid('payload must be a string or a Buffer');
173
+ if (plaintext.length > MAX_PAYLOAD) throw invalid(`payload must be at most ${MAX_PAYLOAD} bytes (RFC 8291)`);
174
+ const ecdh = crypto.createECDH('prime256v1');
175
+ let salt;
176
+ if (deterministic) {
177
+ try {
178
+ ecdh.setPrivateKey(Buffer.from(String(deterministic.privateKey), 'base64url'));
179
+ } catch {
180
+ throw invalid('deterministic.privateKey is not a valid P-256 key');
181
+ }
182
+ salt = Buffer.from(String(deterministic.salt), 'base64url');
183
+ if (salt.length !== 16) throw invalid('deterministic.salt must be 16 bytes');
184
+ } else {
185
+ ecdh.generateKeys();
186
+ salt = crypto.randomBytes(16);
187
+ }
188
+ const asPublic = ecdh.getPublicKey();
189
+ const secret = ecdh.computeSecret(uaPublic);
190
+ const ikm = Buffer.from(crypto.hkdfSync('sha256', secret, authSecret, Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]), 32));
191
+ const cek = Buffer.from(crypto.hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
192
+ const nonce = Buffer.from(crypto.hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
193
+ const cipher = crypto.createCipheriv('aes-128-gcm', cek, nonce);
194
+ // 0x02 : le délimiteur du dernier (et seul) enregistrement, sans remplissage.
195
+ const sealed = Buffer.concat([cipher.update(plaintext), cipher.update(Buffer.from([2])), cipher.final(), cipher.getAuthTag()]);
196
+ const header = Buffer.alloc(21);
197
+ salt.copy(header, 0);
198
+ header.writeUInt32BE(RECORD_SIZE, 16);
199
+ header[20] = asPublic.length;
200
+ return Buffer.concat([header, asPublic, sealed]);
201
+ }
202
+
203
+ /**
204
+ * Le côté de l'appareil (pour les essais, ou un récepteur écrit en Node) : déchiffre un corps aes128gcm avec la clé
205
+ * privée de l'abonnement (`privateKey`, 32 octets en base64url), sa clé publique `p256dh` et `auth`.
206
+ */
207
+ function decryptWebPush({ body, privateKey, p256dh, auth } = {}) {
208
+ if (!(body instanceof Uint8Array)) throw invalid('body must be a Buffer');
209
+ const data = Buffer.from(body);
210
+ const uaPublic = checkPoint(decodeSubscriptionKey(p256dh, 'p256dh', { min: 65, max: 65 }), 'subscription keys.p256dh');
211
+ const authSecret = decodeSubscriptionKey(auth, 'auth', { min: 16, max: 64 });
212
+ if (data.length < 21 + 65 + 17) throw invalid('body is too short');
213
+ const salt = data.subarray(0, 16);
214
+ const recordSize = data.readUInt32BE(16);
215
+ const idLength = data[20];
216
+ if (idLength !== 65) throw invalid('body key id must be a 65-byte P-256 key');
217
+ const asPublic = checkPoint(data.subarray(21, 86), 'body key id');
218
+ const sealed = data.subarray(86);
219
+ if (recordSize < 18 || sealed.length > recordSize) throw invalid('body must hold a single record');
220
+ const ecdh = crypto.createECDH('prime256v1');
221
+ try {
222
+ ecdh.setPrivateKey(Buffer.from(String(privateKey), 'base64url'));
223
+ } catch {
224
+ throw invalid('privateKey is not a valid P-256 key');
225
+ }
226
+ if (!ecdh.getPublicKey().equals(uaPublic)) throw invalid('privateKey does not match p256dh');
227
+ const secret = ecdh.computeSecret(asPublic);
228
+ const ikm = Buffer.from(crypto.hkdfSync('sha256', secret, authSecret, Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]), 32));
229
+ const cek = Buffer.from(crypto.hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
230
+ const nonce = Buffer.from(crypto.hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
231
+ let plain;
232
+ try {
233
+ const decipher = crypto.createDecipheriv('aes-128-gcm', cek, nonce);
234
+ decipher.setAuthTag(sealed.subarray(sealed.length - 16));
235
+ plain = Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - 16)), decipher.final()]);
236
+ } catch {
237
+ throw new WebPushError('body could not be decrypted', { code: 'decrypt_failed' });
238
+ }
239
+ let end = plain.length;
240
+ while (end > 0 && plain[end - 1] === 0) end -= 1;
241
+ if (end === 0 || plain[end - 1] !== 2) throw new WebPushError('body has no final record delimiter', { code: 'decrypt_failed' });
242
+ return plain.subarray(0, end - 1);
243
+ }
244
+
245
+ /** L'adresse d'abonnement, vérifiée : https://, sans identifiants, sur un service connu (ou ajouté). */
246
+ function checkEndpoint(endpoint, { extraHosts = [], allowAnyHost = false } = {}) {
247
+ if (typeof endpoint !== 'string' || !endpoint || endpoint.length > 2048) throw invalid('subscription endpoint must be a URL');
248
+ let url;
249
+ try {
250
+ url = new URL(endpoint);
251
+ } catch {
252
+ throw invalid('subscription endpoint must be a URL');
253
+ }
254
+ if (url.protocol !== 'https:') throw invalid('subscription endpoint must use https://');
255
+ if (url.username || url.password) throw invalid('subscription endpoint must not contain credentials');
256
+ if (!Array.isArray(extraHosts) || extraHosts.some((h) => typeof h !== 'string' || !h)) throw invalid('extraHosts must be an array of host names');
257
+ if (!allowAnyHost) {
258
+ const host = url.hostname.toLowerCase();
259
+ const allowed = [...KNOWN_PUSH_HOSTS, ...extraHosts.map((h) => h.toLowerCase())];
260
+ if (!allowed.some((h) => host === h || host.endsWith(`.${h}`))) throw invalid(`subscription endpoint host ${host} is not a known push service (add it to extraHosts)`);
261
+ }
262
+ return url;
263
+ }
264
+
265
+ function readOptions(options) {
266
+ if (options === undefined || options === null) options = {};
267
+ if (typeof options !== 'object') throw invalid('options must be an object');
268
+ for (const key of Object.keys(options)) {
269
+ if (key === 'gcmAPIKey') throw invalid('gcmAPIKey is not supported: GCM closed in 2019, use VAPID');
270
+ if (key === 'proxy') throw invalid('proxy is not supported: pass an https.Agent (for example a proxy agent) as agent');
271
+ if (!OPTION_KEYS.has(key)) throw invalid(`'${key}' is an invalid option`);
272
+ }
273
+ const pick = (a, b) => {
274
+ if (options[a] !== undefined && options[b] !== undefined) throw invalid(`give ${a} or ${b}, not both`);
275
+ return options[a] !== undefined ? options[a] : options[b];
276
+ };
277
+ const vapid = pick('vapid', 'vapidDetails');
278
+ let ttl = pick('ttl', 'TTL');
279
+ if (ttl === undefined) ttl = DEFAULT_TTL;
280
+ if (typeof ttl === 'string' && /^\d{1,10}$/.test(ttl)) ttl = Number(ttl);
281
+ if (!Number.isSafeInteger(ttl) || ttl < 0) throw invalid('TTL must be a non-negative integer (seconds)');
282
+ const urgency = options.urgency === undefined ? 'normal' : options.urgency;
283
+ if (!URGENCIES.has(urgency)) throw invalid('urgency must be very-low, low, normal or high');
284
+ const topic = options.topic;
285
+ if (topic !== undefined && (typeof topic !== 'string' || !B64URL.test(topic) || topic.length > 32)) throw invalid('topic must be at most 32 URL-safe base64 characters');
286
+ if (options.contentEncoding !== undefined && options.contentEncoding !== 'aes128gcm') throw invalid('only the aes128gcm content encoding is supported (aesgcm is an obsolete draft)');
287
+ const timeoutMs = pick('timeoutMs', 'timeout') ?? DEFAULT_TIMEOUT_MS;
288
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000) throw invalid('timeout must be a number of milliseconds');
289
+ const headers = options.headers ?? {};
290
+ if (typeof headers !== 'object' || Array.isArray(headers)) throw invalid('headers must be an object');
291
+ const extra = {};
292
+ for (const [name, value] of Object.entries(headers)) {
293
+ if (!HEADER_NAME.test(name)) throw invalid(`header name ${JSON.stringify(name)} is not valid`);
294
+ if (MANAGED_HEADERS.has(name.toLowerCase())) throw invalid(`header ${name} is set by the library; use the option instead`);
295
+ const text = String(value);
296
+ if (text.length > 1024 || /[\0\r\n]/.test(text)) throw invalid(`header ${name} has an invalid value`);
297
+ extra[name] = text;
298
+ }
299
+ return { vapid, ttl, urgency, topic, timeoutMs, extra, agent: options.agent, extraHosts: options.extraHosts, allowAnyHost: options.allowAnyHost === true, expiration: options.expiration, now: options.now };
300
+ }
301
+
302
+ /**
303
+ * La requête à envoyer, sans l'envoyer (comme generateRequestDetails de web-push) : { endpoint, method, headers, body }.
304
+ * `payload` : texte ou Buffer (aucun message : une simple notification sans contenu).
305
+ */
306
+ function buildWebPushRequest(subscription, payload, options) {
307
+ const opts = readOptions(options);
308
+ if (!subscription || typeof subscription !== 'object') throw invalid('subscription must be { endpoint, keys: { p256dh, auth } }');
309
+ const url = checkEndpoint(subscription.endpoint, opts);
310
+ const bytes = toPayload(payload);
311
+ const headers = { TTL: String(opts.ttl), ...opts.extra };
312
+ let body = null;
313
+ if (bytes) {
314
+ const keys = subscription.keys;
315
+ if (!keys || typeof keys !== 'object') throw invalid('to send a payload, the subscription must have keys.p256dh and keys.auth');
316
+ body = encryptWebPush({ p256dh: keys.p256dh, auth: keys.auth, payload: bytes });
317
+ headers['Content-Length'] = String(body.length);
318
+ headers['Content-Type'] = 'application/octet-stream';
319
+ headers['Content-Encoding'] = 'aes128gcm';
320
+ } else {
321
+ headers['Content-Length'] = '0';
322
+ }
323
+ if (opts.vapid) headers.Authorization = vapidAuthorization({ audience: `${url.protocol}//${url.host}`, vapid: opts.vapid, expiration: opts.expiration, now: opts.now }).authorization;
324
+ headers.Urgency = opts.urgency;
325
+ if (opts.topic) headers.Topic = opts.topic;
326
+ return { endpoint: subscription.endpoint, method: 'POST', headers, body, timeoutMs: opts.timeoutMs, agent: opts.agent };
327
+ }
328
+
329
+ /** Envoie une requête préparée : une réponse 2xx rend { statusCode, body, headers }, une autre lève WebPushError. */
330
+ function deliver(request) {
331
+ const url = new URL(request.endpoint);
332
+ return new Promise((resolve, reject) => {
333
+ let settled = false;
334
+ const finish = (fn, value) => {
335
+ if (settled) return;
336
+ settled = true;
337
+ clearTimeout(timer);
338
+ fn(value);
339
+ };
340
+ const req = https.request(
341
+ {
342
+ hostname: url.hostname.replace(/^\[|\]$/g, ''),
343
+ port: url.port || 443,
344
+ path: `${url.pathname}${url.search}`,
345
+ method: 'POST',
346
+ headers: request.headers,
347
+ agent: request.agent,
348
+ },
349
+ (res) => {
350
+ const chunks = [];
351
+ let size = 0;
352
+ const done = (truncated) => {
353
+ const text = Buffer.concat(chunks).toString('utf8');
354
+ if (res.statusCode >= 200 && res.statusCode <= 299) finish(resolve, { statusCode: res.statusCode, body: text, headers: res.headers });
355
+ else finish(reject, new WebPushError(truncated ? 'Received unexpected response code (body truncated)' : 'Received unexpected response code', { statusCode: res.statusCode, headers: res.headers, body: text, endpoint: request.endpoint }));
356
+ };
357
+ res.on('data', (chunk) => {
358
+ if (settled) return;
359
+ const room = MAX_RESPONSE - size;
360
+ chunks.push(chunk.length > room ? chunk.subarray(0, room) : chunk);
361
+ size += chunk.length;
362
+ if (size >= MAX_RESPONSE) {
363
+ done(true);
364
+ res.destroy();
365
+ }
366
+ });
367
+ res.on('end', () => done(false));
368
+ res.on('error', (error) => finish(reject, error));
369
+ }
370
+ );
371
+ const timer = setTimeout(() => {
372
+ const error = new WebPushError(`Push service did not answer within ${request.timeoutMs} ms`, { code: 'timeout', endpoint: request.endpoint });
373
+ finish(reject, error);
374
+ req.destroy(error);
375
+ }, request.timeoutMs);
376
+ timer.unref?.();
377
+ req.on('error', (error) => finish(reject, error));
378
+ if (request.body) req.write(request.body);
379
+ req.end();
380
+ });
381
+ }
382
+
383
+ /** Envoie une notification (comme webpush.sendNotification) : mêmes arguments, mêmes résultats, mêmes erreurs. */
384
+ async function sendWebPush(subscription, payload, options) {
385
+ return deliver(buildWebPushRequest(subscription, payload, options));
386
+ }
387
+
388
+ /**
389
+ * Un TRANSPORT pour createPushSender : `transport(subscription, payload)`, payload texte, Buffer ou objet (envoyé en
390
+ * JSON). Les clés VAPID sont lues et vérifiées une fois, à la création ; l'en-tête VAPID est gardé par service tant
391
+ * qu'il lui reste plus d'une heure.
392
+ */
393
+ function createWebPushTransport(options = {}) {
394
+ const { vapid, ...rest } = options;
395
+ const parsed = parseVapid(vapid);
396
+ readOptions(rest);
397
+ const now = rest.now || Date.now;
398
+ const cache = new Map();
399
+ return async function webPushTransport(subscription, payload, overrides = {}) {
400
+ if (overrides.vapid !== undefined || overrides.vapidDetails !== undefined) throw invalid('the transport signs with the VAPID keys given at creation');
401
+ const opts = { ...rest, ...overrides };
402
+ const body = payload !== null && typeof payload === 'object' && !(payload instanceof Uint8Array) ? JSON.stringify(payload) : payload;
403
+ const request = buildWebPushRequest(subscription, body, opts);
404
+ const url = new URL(request.endpoint);
405
+ const audience = `${url.protocol}//${url.host}`;
406
+ const seconds = Math.floor(now() / 1000);
407
+ let entry = cache.get(audience);
408
+ if (!entry || entry.expiration - seconds < 3600) {
409
+ entry = vapidAuthorization({ audience, vapid: parsed, now });
410
+ if (cache.size >= 100) cache.delete(cache.keys().next().value);
411
+ cache.set(audience, entry);
412
+ }
413
+ request.headers.Authorization = entry.authorization;
414
+ return deliver(request);
415
+ };
416
+ }
417
+
418
+ module.exports = {
419
+ generateVapidKeys,
420
+ vapidAuthorization,
421
+ encryptWebPush,
422
+ decryptWebPush,
423
+ buildWebPushRequest,
424
+ sendWebPush,
425
+ createWebPushTransport,
426
+ WebPushError,
427
+ KNOWN_PUSH_HOSTS,
428
+ };