@astratra/notify 1.0.0 → 1.2.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/LICENSE +1 -1
- package/README.md +37 -2
- package/package.json +2 -2
- package/src/apns.js +146 -0
- package/src/index.d.ts +39 -0
- package/src/index.js +1 -0
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -220,6 +220,40 @@ Le statut du fournisseur est cherché où qu'il l'ait mis — `statusCode`,
|
|
|
220
220
|
`status`, `response.status` — parce que web-push et les clients HTTP ne sont pas
|
|
221
221
|
d'accord entre eux.
|
|
222
222
|
|
|
223
|
+
## Les notifications Apple, en direct : `createApnsTransport`
|
|
224
|
+
|
|
225
|
+
Un transport prêt pour `createPushSender`, qui parle directement aux serveurs
|
|
226
|
+
d'Apple (HTTP/2, jeton de fournisseur signé ES256 avec la clé `.p8` de
|
|
227
|
+
l'équipe). Aucun SDK, aucun relais.
|
|
228
|
+
|
|
229
|
+
```js
|
|
230
|
+
const { createApnsTransport, createPushSender } = require('@astratra/notify');
|
|
231
|
+
|
|
232
|
+
const transport = createApnsTransport({
|
|
233
|
+
key: process.env.APNS_CLE, // la clé .p8 (PEM, ou sur une seule ligne)
|
|
234
|
+
keyId: process.env.APNS_CLE_ID,
|
|
235
|
+
teamId: process.env.APNS_EQUIPE_ID,
|
|
236
|
+
topic: 'com.exemple.app', // l'identifiant de l'app
|
|
237
|
+
production: true // false : passerelle de test (sandbox)
|
|
238
|
+
});
|
|
239
|
+
const push = createPushSender({ transport, onGone: async (jeton) => supprimerAppareil(jeton) });
|
|
240
|
+
|
|
241
|
+
await push.send(jetonAppareil, { title: 'Alerte', body: 'Le serveur ne répond plus', badge: 3, urgent: true, data: { alerteId } });
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
- **Le jeton de fournisseur est gardé 50 minutes** : Apple refuse un jeton de
|
|
245
|
+
plus d'une heure et ralentit qui en signe un à chaque envoi.
|
|
246
|
+
- **Une seule connexion HTTP/2** porte tous les envois ; fermée ou cassée,
|
|
247
|
+
elle est rouverte au suivant. `transport.close()` la ferme à l'arrêt.
|
|
248
|
+
- **Un appareil mort** (410, `BadDeviceToken`, `Unregistered`) lève une erreur
|
|
249
|
+
410 : `createPushSender` te le rend pour suppression.
|
|
250
|
+
- `urgent: true` envoie une notification urgente (`time-sensitive`), qui passe
|
|
251
|
+
les modes Concentration ; `badge` pose le nombre sur l'icône ;
|
|
252
|
+
`contentAvailable` fait une notification silencieuse.
|
|
253
|
+
- La clé est lue à la création : une clé mal formée échoue au démarrage, pas
|
|
254
|
+
à la première alerte de la nuit. Une clé rangée sur une seule ligne (coffre,
|
|
255
|
+
`.env`) est acceptée.
|
|
256
|
+
|
|
223
257
|
---
|
|
224
258
|
|
|
225
259
|
# La boîte de notifications, côté serveur
|
|
@@ -369,8 +403,9 @@ test('le catalogue des notifications', () => {
|
|
|
369
403
|
|
|
370
404
|
## Ce que ce package ne fait pas
|
|
371
405
|
|
|
372
|
-
- Il n'envoie **rien** lui-même
|
|
373
|
-
|
|
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é.
|
|
374
409
|
- Il ne stocke pas les abonnements : il te rend les morts, tu les supprimes.
|
|
375
410
|
Il ne tient pas non plus de registre d'appareils par compte : tu choisis la
|
|
376
411
|
liste, `broadcast` l'envoie.
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/notify",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
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.",
|
|
5
5
|
"engines": {
|
|
6
|
-
"node": ">=
|
|
6
|
+
"node": ">=22"
|
|
7
7
|
},
|
|
8
8
|
"main": "src/index.js",
|
|
9
9
|
"types": "src/index.d.ts",
|
package/src/apns.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
const { createPrivateKey, sign } = require('crypto');
|
|
2
|
+
const http2 = require('http2');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Apple Push Notification service (APNs), straight from Apple: HTTP/2 and a
|
|
6
|
+
* provider token signed ES256 with the team's .p8 key. No SDK, no relay.
|
|
7
|
+
*
|
|
8
|
+
* It is a TRANSPORT for createPushSender: `transport(deviceToken, payload)`
|
|
9
|
+
* throws on failure with `statusCode` on the error, and a dead device (410,
|
|
10
|
+
* BadDeviceToken, Unregistered) throws 410 so createPushSender's default
|
|
11
|
+
* `isGone` hands it back for pruning.
|
|
12
|
+
*
|
|
13
|
+
* What it gets right, each one a lesson:
|
|
14
|
+
* - the provider token is reused for 50 minutes (Apple refuses one older than
|
|
15
|
+
* an hour, and throttles providers that sign a new one per request);
|
|
16
|
+
* - ONE HTTP/2 connection is kept and reused (Apple asks providers to keep it
|
|
17
|
+
* open); a closed or broken connection is opened again on the next send;
|
|
18
|
+
* - the key is parsed once, at creation: a malformed key fails loudly at
|
|
19
|
+
* startup, not at the first alert of the night.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const JWT_TTL_MS = 50 * 60_000;
|
|
23
|
+
const PRODUCTION_URL = 'https://api.push.apple.com';
|
|
24
|
+
const SANDBOX_URL = 'https://api.sandbox.push.apple.com';
|
|
25
|
+
const DEVICE_TOKEN = /^[0-9a-f]{64,200}$/i;
|
|
26
|
+
const DEAD_REASONS = new Set(['BadDeviceToken', 'Unregistered', 'DeviceTokenNotForTopic']);
|
|
27
|
+
|
|
28
|
+
function apnsError(message, statusCode, reason) {
|
|
29
|
+
const error = new Error(message);
|
|
30
|
+
error.statusCode = statusCode;
|
|
31
|
+
if (reason) error.reason = reason;
|
|
32
|
+
return error;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The .p8 key as Apple delivers it, or a single line where the newlines became
|
|
37
|
+
* spaces or literal "\n" (how keys often come back from a vault or a .env).
|
|
38
|
+
*/
|
|
39
|
+
function normalizeKey(key) {
|
|
40
|
+
if (typeof key !== 'string' || !key.trim()) throw new Error('createApnsTransport requires options.key (the .p8 private key).');
|
|
41
|
+
const body = key.replace(/\\n/g, '\n').replace(/-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----/g, '').replace(/\s+/g, '');
|
|
42
|
+
return `-----BEGIN PRIVATE KEY-----\n${body.match(/.{1,64}/g).join('\n')}\n-----END PRIVATE KEY-----\n`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The APNs body: the alert in `aps`, your own data beside it. */
|
|
46
|
+
function apnsBody(payload) {
|
|
47
|
+
const p = payload || {};
|
|
48
|
+
const aps = {};
|
|
49
|
+
if (p.title !== undefined || p.body !== undefined) aps.alert = { ...(p.title !== undefined ? { title: p.title } : {}), ...(p.body !== undefined ? { body: p.body } : {}) };
|
|
50
|
+
if (p.sound !== null) aps.sound = p.sound ?? 'default';
|
|
51
|
+
if (Number.isInteger(p.badge) && p.badge >= 0) aps.badge = p.badge;
|
|
52
|
+
if (p.urgent) aps['interruption-level'] = 'time-sensitive';
|
|
53
|
+
if (p.contentAvailable) aps['content-available'] = 1;
|
|
54
|
+
if (p.threadId) aps['thread-id'] = String(p.threadId);
|
|
55
|
+
return JSON.stringify({ ...(p.data || {}), aps });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {object} options
|
|
60
|
+
* @param {string} options.key The .p8 private key (PEM, or one line).
|
|
61
|
+
* @param {string} options.keyId The key's ID (10 characters, from Apple).
|
|
62
|
+
* @param {string} options.teamId The Apple team ID.
|
|
63
|
+
* @param {string} options.topic The app's bundle identifier.
|
|
64
|
+
* @param {boolean} [options.production=true] Production or sandbox gateway.
|
|
65
|
+
* @param {string} [options.url] Override the gateway (tests).
|
|
66
|
+
* @param {number} [options.timeoutMs=20000]
|
|
67
|
+
* @param {Function} [options.now] Clock, for tests.
|
|
68
|
+
*/
|
|
69
|
+
function createApnsTransport(options = {}) {
|
|
70
|
+
const { keyId, teamId, topic } = options;
|
|
71
|
+
for (const [name, value] of Object.entries({ keyId, teamId, topic })) {
|
|
72
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error(`createApnsTransport requires options.${name}.`);
|
|
73
|
+
}
|
|
74
|
+
const privateKey = createPrivateKey(normalizeKey(options.key));
|
|
75
|
+
if (privateKey.asymmetricKeyType !== 'ec') throw new Error('createApnsTransport options.key must be an EC (P-256) .p8 key.');
|
|
76
|
+
const url = options.url || (options.production === false ? SANDBOX_URL : PRODUCTION_URL);
|
|
77
|
+
const timeoutMs = options.timeoutMs ?? 20_000;
|
|
78
|
+
const now = options.now || Date.now;
|
|
79
|
+
|
|
80
|
+
let token = null;
|
|
81
|
+
function providerToken() {
|
|
82
|
+
if (token && now() - token.at < JWT_TTL_MS) return token.value;
|
|
83
|
+
const b64 = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
84
|
+
const head = `${b64({ alg: 'ES256', kid: keyId })}.${b64({ iss: teamId, iat: Math.floor(now() / 1000) })}`;
|
|
85
|
+
const signature = sign('sha256', Buffer.from(head), { key: privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url');
|
|
86
|
+
token = { value: `${head}.${signature}`, at: now() };
|
|
87
|
+
return token.value;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let session = null;
|
|
91
|
+
function connection() {
|
|
92
|
+
if (session && !session.closed && !session.destroyed) return session;
|
|
93
|
+
/* Chaque écouteur vise SA connexion : la variable partagée vaut null après
|
|
94
|
+
close(), ou désigne déjà la suivante après une reconnexion. Un GOAWAY
|
|
95
|
+
tardif levait alors une exception hors de toute requête. */
|
|
96
|
+
const current = http2.connect(url);
|
|
97
|
+
current.on('error', () => { /* surfaced on the request; the next send reconnects */ });
|
|
98
|
+
current.on('goaway', () => { if (!current.closed && !current.destroyed) current.close(); });
|
|
99
|
+
current.unref?.();
|
|
100
|
+
session = current;
|
|
101
|
+
return current;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function transport(subscription, payload) {
|
|
105
|
+
const deviceToken = typeof subscription === 'string' ? subscription : subscription?.token;
|
|
106
|
+
if (typeof deviceToken !== 'string' || !DEVICE_TOKEN.test(deviceToken)) throw apnsError('APNs: malformed device token.', 410, 'BadDeviceToken');
|
|
107
|
+
const p = payload || {};
|
|
108
|
+
const headers = {
|
|
109
|
+
':method': 'POST',
|
|
110
|
+
':path': `/3/device/${deviceToken}`,
|
|
111
|
+
authorization: `bearer ${providerToken()}`,
|
|
112
|
+
'apns-topic': p.pushType === 'voip' ? `${topic}.voip` : topic,
|
|
113
|
+
'apns-push-type': p.pushType || (p.contentAvailable && p.title === undefined && p.body === undefined ? 'background' : 'alert'),
|
|
114
|
+
'apns-priority': p.contentAvailable && p.title === undefined ? '5' : '10',
|
|
115
|
+
'content-type': 'application/json',
|
|
116
|
+
...(p.collapseId ? { 'apns-collapse-id': String(p.collapseId).slice(0, 64) } : {}),
|
|
117
|
+
...(Number.isInteger(p.expiration) ? { 'apns-expiration': String(p.expiration) } : {})
|
|
118
|
+
};
|
|
119
|
+
const { status, text } = await new Promise((resolve, reject) => {
|
|
120
|
+
let req;
|
|
121
|
+
try { req = connection().request(headers); } catch (error) { reject(error); return; }
|
|
122
|
+
let statusCode = 0;
|
|
123
|
+
let body = '';
|
|
124
|
+
req.setEncoding('utf8');
|
|
125
|
+
req.setTimeout(timeoutMs, () => { req.close(http2.constants.NGHTTP2_CANCEL); reject(apnsError(`APNs: no answer after ${timeoutMs} ms.`, 0)); });
|
|
126
|
+
req.on('response', (h) => { statusCode = Number(h[':status']); });
|
|
127
|
+
req.on('data', (chunk) => { body += chunk; });
|
|
128
|
+
req.on('end', () => resolve({ status: statusCode, text: body }));
|
|
129
|
+
req.on('error', reject);
|
|
130
|
+
req.end(apnsBody(p));
|
|
131
|
+
});
|
|
132
|
+
if (status === 200) return { status: 200 };
|
|
133
|
+
let reason = '';
|
|
134
|
+
try { reason = JSON.parse(text).reason || ''; } catch { /* empty body */ }
|
|
135
|
+
/* A provider token Apple calls expired or invalid is dropped, so the next send signs a fresh one. */
|
|
136
|
+
if (reason === 'ExpiredProviderToken' || reason === 'InvalidProviderToken') token = null;
|
|
137
|
+
if (status === 410 || DEAD_REASONS.has(reason)) throw apnsError(`APNs: device gone (${reason || status}).`, 410, reason || 'Unregistered');
|
|
138
|
+
throw apnsError(`APNs answered ${status}${reason ? ` ${reason}` : ''}.`, status, reason || undefined);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Closes the kept HTTP/2 connection (at shutdown). */
|
|
142
|
+
transport.close = () => { if (session && !session.closed) session.close(); session = null; };
|
|
143
|
+
return transport;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
module.exports = { createApnsTransport, apnsBody };
|
package/src/index.d.ts
CHANGED
|
@@ -311,3 +311,42 @@ export function createNotificationCatalog(options: {
|
|
|
311
311
|
/** One object, or several (one per domain) — a key declared twice throws. */
|
|
312
312
|
entries: NotificationEntries | NotificationEntries[];
|
|
313
313
|
}): NotificationCatalog;
|
|
314
|
+
|
|
315
|
+
/** What createApnsTransport sends: the alert, Apple's options, and your data beside `aps`. */
|
|
316
|
+
export interface ApnsPayload {
|
|
317
|
+
title?: string;
|
|
318
|
+
body?: string;
|
|
319
|
+
data?: Record<string, unknown>;
|
|
320
|
+
/** Number on the app icon. */
|
|
321
|
+
badge?: number;
|
|
322
|
+
/** null: silent. Default 'default'. */
|
|
323
|
+
sound?: string | null;
|
|
324
|
+
/** Time-sensitive: passes Focus modes. */
|
|
325
|
+
urgent?: boolean;
|
|
326
|
+
/** Silent background notification. */
|
|
327
|
+
contentAvailable?: boolean;
|
|
328
|
+
threadId?: string;
|
|
329
|
+
collapseId?: string;
|
|
330
|
+
/** UNIX seconds after which Apple stops trying. */
|
|
331
|
+
expiration?: number;
|
|
332
|
+
pushType?: 'alert' | 'background' | 'voip';
|
|
333
|
+
}
|
|
334
|
+
export interface ApnsTransport {
|
|
335
|
+
(deviceToken: string | { token: string }, payload: ApnsPayload): Promise<{ status: 200 }>;
|
|
336
|
+
/** Closes the kept HTTP/2 connection. */
|
|
337
|
+
close(): void;
|
|
338
|
+
}
|
|
339
|
+
export function createApnsTransport(options: {
|
|
340
|
+
/** The .p8 private key (PEM, or one line). */
|
|
341
|
+
key: string;
|
|
342
|
+
keyId: string;
|
|
343
|
+
teamId: string;
|
|
344
|
+
/** The app's bundle identifier. */
|
|
345
|
+
topic: string;
|
|
346
|
+
/** Default true; false for the sandbox gateway. */
|
|
347
|
+
production?: boolean;
|
|
348
|
+
url?: string;
|
|
349
|
+
timeoutMs?: number;
|
|
350
|
+
now?: () => number;
|
|
351
|
+
}): ApnsTransport;
|
|
352
|
+
export function apnsBody(payload: ApnsPayload): string;
|